1/******************************************************************************
2** This file is an amalgamation of many separate C source files from SQLite
3** version 3.7.11.  By combining all the individual C code files into this
4** single large file, the entire code can be compiled as a single translation
5** unit.  This allows many compilers to do optimizations that would not be
6** possible if the files were compiled separately.  Performance improvements
7** of 5% or more are commonly seen when SQLite is compiled as a single
8** translation unit.
9**
10** This file is all you need to compile SQLite.  To use SQLite in other
11** programs, you need this file and the "sqlite3.h" header file that defines
12** the programming interface to the SQLite library.  (If you do not have
13** the "sqlite3.h" header file at hand, you will find a copy embedded within
14** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15** of the embedded sqlite3.h header file.) Additional code files may be needed
16** if you want a wrapper to interface SQLite with your choice of programming
17** language. The code for the "sqlite3" command-line shell is also in a
18** separate file. This file contains only code for the core SQLite library.
19*/
20#define SQLITE_CORE 1
21#define SQLITE_AMALGAMATION 1
22#ifndef SQLITE_PRIVATE
23# define SQLITE_PRIVATE static
24#endif
25#ifndef SQLITE_API
26# define SQLITE_API
27#endif
28/************** Begin file sqliteInt.h ***************************************/
29/*
30** 2001 September 15
31**
32** The author disclaims copyright to this source code.  In place of
33** a legal notice, here is a blessing:
34**
35**    May you do good and not evil.
36**    May you find forgiveness for yourself and forgive others.
37**    May you share freely, never taking more than you give.
38**
39*************************************************************************
40** Internal interface definitions for SQLite.
41**
42*/
43#ifndef _SQLITEINT_H_
44#define _SQLITEINT_H_
45
46/*
47** These #defines should enable >2GB file support on POSIX if the
48** underlying operating system supports it.  If the OS lacks
49** large file support, or if the OS is windows, these should be no-ops.
50**
51** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52** system #includes.  Hence, this block of code must be the very first
53** code in all source files.
54**
55** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56** on the compiler command line.  This is necessary if you are compiling
57** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59** without this option, LFS is enable.  But LFS does not exist in the kernel
60** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61** portability you should omit LFS.
62**
63** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64*/
65#ifndef SQLITE_DISABLE_LFS
66# define _LARGE_FILE       1
67# ifndef _FILE_OFFSET_BITS
68#   define _FILE_OFFSET_BITS 64
69# endif
70# define _LARGEFILE_SOURCE 1
71#endif
72
73/*
74** Include the configuration header output by 'configure' if we're using the
75** autoconf-based build
76*/
77#ifdef _HAVE_SQLITE_CONFIG_H
78#include "config.h"
79#endif
80
81/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82/************** Begin file sqliteLimit.h *************************************/
83/*
84** 2007 May 7
85**
86** The author disclaims copyright to this source code.  In place of
87** a legal notice, here is a blessing:
88**
89**    May you do good and not evil.
90**    May you find forgiveness for yourself and forgive others.
91**    May you share freely, never taking more than you give.
92**
93*************************************************************************
94**
95** This file defines various limits of what SQLite can process.
96*/
97
98/*
99** The maximum length of a TEXT or BLOB in bytes.   This also
100** limits the size of a row in a table or index.
101**
102** The hard limit is the ability of a 32-bit signed integer
103** to count the size: 2^31-1 or 2147483647.
104*/
105#ifndef SQLITE_MAX_LENGTH
106# define SQLITE_MAX_LENGTH 1000000000
107#endif
108
109/*
110** This is the maximum number of
111**
112**    * Columns in a table
113**    * Columns in an index
114**    * Columns in a view
115**    * Terms in the SET clause of an UPDATE statement
116**    * Terms in the result set of a SELECT statement
117**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118**    * Terms in the VALUES clause of an INSERT statement
119**
120** The hard upper limit here is 32676.  Most database people will
121** tell you that in a well-normalized database, you usually should
122** not have more than a dozen or so columns in any table.  And if
123** that is the case, there is no point in having more than a few
124** dozen values in any of the other situations described above.
125*/
126#ifndef SQLITE_MAX_COLUMN
127# define SQLITE_MAX_COLUMN 2000
128#endif
129
130/*
131** The maximum length of a single SQL statement in bytes.
132**
133** It used to be the case that setting this value to zero would
134** turn the limit off.  That is no longer true.  It is not possible
135** to turn this limit off.
136*/
137#ifndef SQLITE_MAX_SQL_LENGTH
138# define SQLITE_MAX_SQL_LENGTH 1000000000
139#endif
140
141/*
142** The maximum depth of an expression tree. This is limited to
143** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
144** want to place more severe limits on the complexity of an
145** expression.
146**
147** A value of 0 used to mean that the limit was not enforced.
148** But that is no longer true.  The limit is now strictly enforced
149** at all times.
150*/
151#ifndef SQLITE_MAX_EXPR_DEPTH
152# define SQLITE_MAX_EXPR_DEPTH 1000
153#endif
154
155/*
156** The maximum number of terms in a compound SELECT statement.
157** The code generator for compound SELECT statements does one
158** level of recursion for each term.  A stack overflow can result
159** if the number of terms is too large.  In practice, most SQL
160** never has more than 3 or 4 terms.  Use a value of 0 to disable
161** any limit on the number of terms in a compount SELECT.
162*/
163#ifndef SQLITE_MAX_COMPOUND_SELECT
164# define SQLITE_MAX_COMPOUND_SELECT 500
165#endif
166
167/*
168** The maximum number of opcodes in a VDBE program.
169** Not currently enforced.
170*/
171#ifndef SQLITE_MAX_VDBE_OP
172# define SQLITE_MAX_VDBE_OP 25000
173#endif
174
175/*
176** The maximum number of arguments to an SQL function.
177*/
178#ifndef SQLITE_MAX_FUNCTION_ARG
179# define SQLITE_MAX_FUNCTION_ARG 127
180#endif
181
182/*
183** The maximum number of in-memory pages to use for the main database
184** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185*/
186#ifndef SQLITE_DEFAULT_CACHE_SIZE
187# define SQLITE_DEFAULT_CACHE_SIZE  2000
188#endif
189#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191#endif
192
193/*
194** The default number of frames to accumulate in the log file before
195** checkpointing the database in WAL mode.
196*/
197#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
198# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
199#endif
200
201/*
202** The maximum number of attached databases.  This must be between 0
203** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
204** is used internally to track attached databases.
205*/
206#ifndef SQLITE_MAX_ATTACHED
207# define SQLITE_MAX_ATTACHED 10
208#endif
209
210
211/*
212** The maximum value of a ?nnn wildcard that the parser will accept.
213*/
214#ifndef SQLITE_MAX_VARIABLE_NUMBER
215# define SQLITE_MAX_VARIABLE_NUMBER 999
216#endif
217
218/* Maximum page size.  The upper bound on this value is 65536.  This a limit
219** imposed by the use of 16-bit offsets within each page.
220**
221** Earlier versions of SQLite allowed the user to change this value at
222** compile time. This is no longer permitted, on the grounds that it creates
223** a library that is technically incompatible with an SQLite library
224** compiled with a different limit. If a process operating on a database
225** with a page-size of 65536 bytes crashes, then an instance of SQLite
226** compiled with the default page-size limit will not be able to rollback
227** the aborted transaction. This could lead to database corruption.
228*/
229#ifdef SQLITE_MAX_PAGE_SIZE
230# undef SQLITE_MAX_PAGE_SIZE
231#endif
232#define SQLITE_MAX_PAGE_SIZE 65536
233
234
235/*
236** The default size of a database page.
237*/
238#ifndef SQLITE_DEFAULT_PAGE_SIZE
239# define SQLITE_DEFAULT_PAGE_SIZE 1024
240#endif
241#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
242# undef SQLITE_DEFAULT_PAGE_SIZE
243# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
244#endif
245
246/*
247** Ordinarily, if no value is explicitly provided, SQLite creates databases
248** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
249** device characteristics (sector-size and atomic write() support),
250** SQLite may choose a larger value. This constant is the maximum value
251** SQLite will choose on its own.
252*/
253#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
254# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
255#endif
256#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
257# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
258# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
259#endif
260
261
262/*
263** Maximum number of pages in one database file.
264**
265** This is really just the default value for the max_page_count pragma.
266** This value can be lowered (or raised) at run-time using that the
267** max_page_count macro.
268*/
269#ifndef SQLITE_MAX_PAGE_COUNT
270# define SQLITE_MAX_PAGE_COUNT 1073741823
271#endif
272
273/*
274** Maximum length (in bytes) of the pattern in a LIKE or GLOB
275** operator.
276*/
277#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
278# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
279#endif
280
281/*
282** Maximum depth of recursion for triggers.
283**
284** A value of 1 means that a trigger program will not be able to itself
285** fire any triggers. A value of 0 means that no trigger programs at all
286** may be executed.
287*/
288#ifndef SQLITE_MAX_TRIGGER_DEPTH
289# define SQLITE_MAX_TRIGGER_DEPTH 1000
290#endif
291
292/************** End of sqliteLimit.h *****************************************/
293/************** Continuing where we left off in sqliteInt.h ******************/
294
295/* Disable nuisance warnings on Borland compilers */
296#if defined(__BORLANDC__)
297#pragma warn -rch /* unreachable code */
298#pragma warn -ccc /* Condition is always true or false */
299#pragma warn -aus /* Assigned value is never used */
300#pragma warn -csu /* Comparing signed and unsigned */
301#pragma warn -spa /* Suspicious pointer arithmetic */
302#endif
303
304/* Needed for various definitions... */
305#ifndef _GNU_SOURCE
306# define _GNU_SOURCE
307#endif
308
309/*
310** Include standard header files as necessary
311*/
312#ifdef HAVE_STDINT_H
313#include <stdint.h>
314#endif
315#ifdef HAVE_INTTYPES_H
316#include <inttypes.h>
317#endif
318
319/*
320** The following macros are used to cast pointers to integers and
321** integers to pointers.  The way you do this varies from one compiler
322** to the next, so we have developed the following set of #if statements
323** to generate appropriate macros for a wide range of compilers.
324**
325** The correct "ANSI" way to do this is to use the intptr_t type.
326** Unfortunately, that typedef is not available on all compilers, or
327** if it is available, it requires an #include of specific headers
328** that vary from one machine to the next.
329**
330** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
331** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
332** So we have to define the macros in different ways depending on the
333** compiler.
334*/
335#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
336# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
337# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
338#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
339# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
340# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
341#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
342# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
343# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
344#else                          /* Generates a warning - but it always works */
345# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
346# define SQLITE_PTR_TO_INT(X)  ((int)(X))
347#endif
348
349/*
350** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
351** 0 means mutexes are permanently disable and the library is never
352** threadsafe.  1 means the library is serialized which is the highest
353** level of threadsafety.  2 means the libary is multithreaded - multiple
354** threads can use SQLite as long as no two threads try to use the same
355** database connection at the same time.
356**
357** Older versions of SQLite used an optional THREADSAFE macro.
358** We support that for legacy.
359*/
360#if !defined(SQLITE_THREADSAFE)
361#if defined(THREADSAFE)
362# define SQLITE_THREADSAFE THREADSAFE
363#else
364# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
365#endif
366#endif
367
368/*
369** Powersafe overwrite is on by default.  But can be turned off using
370** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
371*/
372#ifndef SQLITE_POWERSAFE_OVERWRITE
373# define SQLITE_POWERSAFE_OVERWRITE 1
374#endif
375
376/*
377** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
378** It determines whether or not the features related to
379** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
380** be overridden at runtime using the sqlite3_config() API.
381*/
382#if !defined(SQLITE_DEFAULT_MEMSTATUS)
383# define SQLITE_DEFAULT_MEMSTATUS 1
384#endif
385
386/*
387** Exactly one of the following macros must be defined in order to
388** specify which memory allocation subsystem to use.
389**
390**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
391**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
392**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
393**
394** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
395** assert() macro is enabled, each call into the Win32 native heap subsystem
396** will cause HeapValidate to be called.  If heap validation should fail, an
397** assertion will be triggered.
398**
399** (Historical note:  There used to be several other options, but we've
400** pared it down to just these three.)
401**
402** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
403** the default.
404*/
405#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)>1
406# error "At most one of the following compile-time configuration options\
407 is allows: SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG"
408#endif
409#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_WIN32_MALLOC)+defined(SQLITE_MEMDEBUG)==0
410# define SQLITE_SYSTEM_MALLOC 1
411#endif
412
413/*
414** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
415** sizes of memory allocations below this value where possible.
416*/
417#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
418# define SQLITE_MALLOC_SOFT_LIMIT 1024
419#endif
420
421/*
422** We need to define _XOPEN_SOURCE as follows in order to enable
423** recursive mutexes on most Unix systems.  But Mac OS X is different.
424** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
425** so it is omitted there.  See ticket #2673.
426**
427** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
428** implemented on some systems.  So we avoid defining it at all
429** if it is already defined or if it is unneeded because we are
430** not doing a threadsafe build.  Ticket #2681.
431**
432** See also ticket #2741.
433*/
434#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
435#  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
436#endif
437
438/*
439** The TCL headers are only needed when compiling the TCL bindings.
440*/
441#if defined(SQLITE_TCL) || defined(TCLSH)
442# include <tcl.h>
443#endif
444
445/*
446** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
447** Setting NDEBUG makes the code smaller and run faster.  So the following
448** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
449** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
450** feature.
451*/
452#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
453# define NDEBUG 1
454#endif
455
456/*
457** The testcase() macro is used to aid in coverage testing.  When
458** doing coverage testing, the condition inside the argument to
459** testcase() must be evaluated both true and false in order to
460** get full branch coverage.  The testcase() macro is inserted
461** to help ensure adequate test coverage in places where simple
462** condition/decision coverage is inadequate.  For example, testcase()
463** can be used to make sure boundary values are tested.  For
464** bitmask tests, testcase() can be used to make sure each bit
465** is significant and used at least once.  On switch statements
466** where multiple cases go to the same block of code, testcase()
467** can insure that all cases are evaluated.
468**
469*/
470#ifdef SQLITE_COVERAGE_TEST
471SQLITE_PRIVATE   void sqlite3Coverage(int);
472# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
473#else
474# define testcase(X)
475#endif
476
477/*
478** The TESTONLY macro is used to enclose variable declarations or
479** other bits of code that are needed to support the arguments
480** within testcase() and assert() macros.
481*/
482#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
483# define TESTONLY(X)  X
484#else
485# define TESTONLY(X)
486#endif
487
488/*
489** Sometimes we need a small amount of code such as a variable initialization
490** to setup for a later assert() statement.  We do not want this code to
491** appear when assert() is disabled.  The following macro is therefore
492** used to contain that setup code.  The "VVA" acronym stands for
493** "Verification, Validation, and Accreditation".  In other words, the
494** code within VVA_ONLY() will only run during verification processes.
495*/
496#ifndef NDEBUG
497# define VVA_ONLY(X)  X
498#else
499# define VVA_ONLY(X)
500#endif
501
502/*
503** The ALWAYS and NEVER macros surround boolean expressions which
504** are intended to always be true or false, respectively.  Such
505** expressions could be omitted from the code completely.  But they
506** are included in a few cases in order to enhance the resilience
507** of SQLite to unexpected behavior - to make the code "self-healing"
508** or "ductile" rather than being "brittle" and crashing at the first
509** hint of unplanned behavior.
510**
511** In other words, ALWAYS and NEVER are added for defensive code.
512**
513** When doing coverage testing ALWAYS and NEVER are hard-coded to
514** be true and false so that the unreachable code then specify will
515** not be counted as untested code.
516*/
517#if defined(SQLITE_COVERAGE_TEST)
518# define ALWAYS(X)      (1)
519# define NEVER(X)       (0)
520#elif !defined(NDEBUG)
521# define ALWAYS(X)      ((X)?1:(assert(0),0))
522# define NEVER(X)       ((X)?(assert(0),1):0)
523#else
524# define ALWAYS(X)      (X)
525# define NEVER(X)       (X)
526#endif
527
528/*
529** Return true (non-zero) if the input is a integer that is too large
530** to fit in 32-bits.  This macro is used inside of various testcase()
531** macros to verify that we have tested SQLite for large-file support.
532*/
533#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
534
535/*
536** The macro unlikely() is a hint that surrounds a boolean
537** expression that is usually false.  Macro likely() surrounds
538** a boolean expression that is usually true.  GCC is able to
539** use these hints to generate better code, sometimes.
540*/
541#if defined(__GNUC__) && 0
542# define likely(X)    __builtin_expect((X),1)
543# define unlikely(X)  __builtin_expect((X),0)
544#else
545# define likely(X)    !!(X)
546# define unlikely(X)  !!(X)
547#endif
548
549/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
550/************** Begin file sqlite3.h *****************************************/
551/*
552** 2001 September 15
553**
554** The author disclaims copyright to this source code.  In place of
555** a legal notice, here is a blessing:
556**
557**    May you do good and not evil.
558**    May you find forgiveness for yourself and forgive others.
559**    May you share freely, never taking more than you give.
560**
561*************************************************************************
562** This header file defines the interface that the SQLite library
563** presents to client programs.  If a C-function, structure, datatype,
564** or constant definition does not appear in this file, then it is
565** not a published API of SQLite, is subject to change without
566** notice, and should not be referenced by programs that use SQLite.
567**
568** Some of the definitions that are in this file are marked as
569** "experimental".  Experimental interfaces are normally new
570** features recently added to SQLite.  We do not anticipate changes
571** to experimental interfaces but reserve the right to make minor changes
572** if experience from use "in the wild" suggest such changes are prudent.
573**
574** The official C-language API documentation for SQLite is derived
575** from comments in this file.  This file is the authoritative source
576** on how SQLite interfaces are suppose to operate.
577**
578** The name of this file under configuration management is "sqlite.h.in".
579** The makefile makes some minor changes to this file (such as inserting
580** the version number) and changes its name to "sqlite3.h" as
581** part of the build process.
582*/
583#ifndef _SQLITE3_H_
584#define _SQLITE3_H_
585#include <stdarg.h>     /* Needed for the definition of va_list */
586
587/*
588** Make sure we can call this stuff from C++.
589*/
590#if 0
591extern "C" {
592#endif
593
594
595/*
596** Add the ability to override 'extern'
597*/
598#ifndef SQLITE_EXTERN
599# define SQLITE_EXTERN extern
600#endif
601
602#ifndef SQLITE_API
603# define SQLITE_API
604#endif
605
606
607/*
608** These no-op macros are used in front of interfaces to mark those
609** interfaces as either deprecated or experimental.  New applications
610** should not use deprecated interfaces - they are support for backwards
611** compatibility only.  Application writers should be aware that
612** experimental interfaces are subject to change in point releases.
613**
614** These macros used to resolve to various kinds of compiler magic that
615** would generate warning messages when they were used.  But that
616** compiler magic ended up generating such a flurry of bug reports
617** that we have taken it all out and gone back to using simple
618** noop macros.
619*/
620#define SQLITE_DEPRECATED
621#define SQLITE_EXPERIMENTAL
622
623/*
624** Ensure these symbols were not defined by some previous header file.
625*/
626#ifdef SQLITE_VERSION
627# undef SQLITE_VERSION
628#endif
629#ifdef SQLITE_VERSION_NUMBER
630# undef SQLITE_VERSION_NUMBER
631#endif
632
633/*
634** CAPI3REF: Compile-Time Library Version Numbers
635**
636** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
637** evaluates to a string literal that is the SQLite version in the
638** format "X.Y.Z" where X is the major version number (always 3 for
639** SQLite3) and Y is the minor version number and Z is the release number.)^
640** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
641** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
642** numbers used in [SQLITE_VERSION].)^
643** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
644** be larger than the release from which it is derived.  Either Y will
645** be held constant and Z will be incremented or else Y will be incremented
646** and Z will be reset to zero.
647**
648** Since version 3.6.18, SQLite source code has been stored in the
649** <a href="http://www.fossil-scm.org/">Fossil configuration management
650** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
651** a string which identifies a particular check-in of SQLite
652** within its configuration management system.  ^The SQLITE_SOURCE_ID
653** string contains the date and time of the check-in (UTC) and an SHA1
654** hash of the entire source tree.
655**
656** See also: [sqlite3_libversion()],
657** [sqlite3_libversion_number()], [sqlite3_sourceid()],
658** [sqlite_version()] and [sqlite_source_id()].
659*/
660#define SQLITE_VERSION        "3.7.11"
661#define SQLITE_VERSION_NUMBER 3007011
662#define SQLITE_SOURCE_ID      "2012-03-20 11:35:50 00bb9c9ce4f465e6ac321ced2a9d0062dc364669"
663
664/*
665** CAPI3REF: Run-Time Library Version Numbers
666** KEYWORDS: sqlite3_version, sqlite3_sourceid
667**
668** These interfaces provide the same information as the [SQLITE_VERSION],
669** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
670** but are associated with the library instead of the header file.  ^(Cautious
671** programmers might include assert() statements in their application to
672** verify that values returned by these interfaces match the macros in
673** the header, and thus insure that the application is
674** compiled with matching library and header files.
675**
676** <blockquote><pre>
677** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
678** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
679** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
680** </pre></blockquote>)^
681**
682** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
683** macro.  ^The sqlite3_libversion() function returns a pointer to the
684** to the sqlite3_version[] string constant.  The sqlite3_libversion()
685** function is provided for use in DLLs since DLL users usually do not have
686** direct access to string constants within the DLL.  ^The
687** sqlite3_libversion_number() function returns an integer equal to
688** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns
689** a pointer to a string constant whose value is the same as the
690** [SQLITE_SOURCE_ID] C preprocessor macro.
691**
692** See also: [sqlite_version()] and [sqlite_source_id()].
693*/
694SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
695SQLITE_API const char *sqlite3_libversion(void);
696SQLITE_API const char *sqlite3_sourceid(void);
697SQLITE_API int sqlite3_libversion_number(void);
698
699/*
700** CAPI3REF: Run-Time Library Compilation Options Diagnostics
701**
702** ^The sqlite3_compileoption_used() function returns 0 or 1
703** indicating whether the specified option was defined at
704** compile time.  ^The SQLITE_ prefix may be omitted from the
705** option name passed to sqlite3_compileoption_used().
706**
707** ^The sqlite3_compileoption_get() function allows iterating
708** over the list of options that were defined at compile time by
709** returning the N-th compile time option string.  ^If N is out of range,
710** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_
711** prefix is omitted from any strings returned by
712** sqlite3_compileoption_get().
713**
714** ^Support for the diagnostic functions sqlite3_compileoption_used()
715** and sqlite3_compileoption_get() may be omitted by specifying the
716** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
717**
718** See also: SQL functions [sqlite_compileoption_used()] and
719** [sqlite_compileoption_get()] and the [compile_options pragma].
720*/
721#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
722SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
723SQLITE_API const char *sqlite3_compileoption_get(int N);
724#endif
725
726/*
727** CAPI3REF: Test To See If The Library Is Threadsafe
728**
729** ^The sqlite3_threadsafe() function returns zero if and only if
730** SQLite was compiled with mutexing code omitted due to the
731** [SQLITE_THREADSAFE] compile-time option being set to 0.
732**
733** SQLite can be compiled with or without mutexes.  When
734** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
735** are enabled and SQLite is threadsafe.  When the
736** [SQLITE_THREADSAFE] macro is 0,
737** the mutexes are omitted.  Without the mutexes, it is not safe
738** to use SQLite concurrently from more than one thread.
739**
740** Enabling mutexes incurs a measurable performance penalty.
741** So if speed is of utmost importance, it makes sense to disable
742** the mutexes.  But for maximum safety, mutexes should be enabled.
743** ^The default behavior is for mutexes to be enabled.
744**
745** This interface can be used by an application to make sure that the
746** version of SQLite that it is linking against was compiled with
747** the desired setting of the [SQLITE_THREADSAFE] macro.
748**
749** This interface only reports on the compile-time mutex setting
750** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
751** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
752** can be fully or partially disabled using a call to [sqlite3_config()]
753** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
754** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
755** sqlite3_threadsafe() function shows only the compile-time setting of
756** thread safety, not any run-time changes to that setting made by
757** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
758** is unchanged by calls to sqlite3_config().)^
759**
760** See the [threading mode] documentation for additional information.
761*/
762SQLITE_API int sqlite3_threadsafe(void);
763
764/*
765** CAPI3REF: Database Connection Handle
766** KEYWORDS: {database connection} {database connections}
767**
768** Each open SQLite database is represented by a pointer to an instance of
769** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
770** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
771** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
772** is its destructor.  There are many other interfaces (such as
773** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
774** [sqlite3_busy_timeout()] to name but three) that are methods on an
775** sqlite3 object.
776*/
777typedef struct sqlite3 sqlite3;
778
779/*
780** CAPI3REF: 64-Bit Integer Types
781** KEYWORDS: sqlite_int64 sqlite_uint64
782**
783** Because there is no cross-platform way to specify 64-bit integer types
784** SQLite includes typedefs for 64-bit signed and unsigned integers.
785**
786** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
787** The sqlite_int64 and sqlite_uint64 types are supported for backwards
788** compatibility only.
789**
790** ^The sqlite3_int64 and sqlite_int64 types can store integer values
791** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
792** sqlite3_uint64 and sqlite_uint64 types can store integer values
793** between 0 and +18446744073709551615 inclusive.
794*/
795#ifdef SQLITE_INT64_TYPE
796  typedef SQLITE_INT64_TYPE sqlite_int64;
797  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
798#elif defined(_MSC_VER) || defined(__BORLANDC__)
799  typedef __int64 sqlite_int64;
800  typedef unsigned __int64 sqlite_uint64;
801#else
802  typedef long long int sqlite_int64;
803  typedef unsigned long long int sqlite_uint64;
804#endif
805typedef sqlite_int64 sqlite3_int64;
806typedef sqlite_uint64 sqlite3_uint64;
807
808/*
809** If compiling for a processor that lacks floating point support,
810** substitute integer for floating-point.
811*/
812#ifdef SQLITE_OMIT_FLOATING_POINT
813# define double sqlite3_int64
814#endif
815
816/*
817** CAPI3REF: Closing A Database Connection
818**
819** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
820** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
821** successfully destroyed and all associated resources are deallocated.
822**
823** Applications must [sqlite3_finalize | finalize] all [prepared statements]
824** and [sqlite3_blob_close | close] all [BLOB handles] associated with
825** the [sqlite3] object prior to attempting to close the object.  ^If
826** sqlite3_close() is called on a [database connection] that still has
827** outstanding [prepared statements] or [BLOB handles], then it returns
828** SQLITE_BUSY.
829**
830** ^If [sqlite3_close()] is invoked while a transaction is open,
831** the transaction is automatically rolled back.
832**
833** The C parameter to [sqlite3_close(C)] must be either a NULL
834** pointer or an [sqlite3] object pointer obtained
835** from [sqlite3_open()], [sqlite3_open16()], or
836** [sqlite3_open_v2()], and not previously closed.
837** ^Calling sqlite3_close() with a NULL pointer argument is a
838** harmless no-op.
839*/
840SQLITE_API int sqlite3_close(sqlite3 *);
841
842/*
843** The type for a callback function.
844** This is legacy and deprecated.  It is included for historical
845** compatibility and is not documented.
846*/
847typedef int (*sqlite3_callback)(void*,int,char**, char**);
848
849/*
850** CAPI3REF: One-Step Query Execution Interface
851**
852** The sqlite3_exec() interface is a convenience wrapper around
853** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
854** that allows an application to run multiple statements of SQL
855** without having to use a lot of C code.
856**
857** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
858** semicolon-separate SQL statements passed into its 2nd argument,
859** in the context of the [database connection] passed in as its 1st
860** argument.  ^If the callback function of the 3rd argument to
861** sqlite3_exec() is not NULL, then it is invoked for each result row
862** coming out of the evaluated SQL statements.  ^The 4th argument to
863** sqlite3_exec() is relayed through to the 1st argument of each
864** callback invocation.  ^If the callback pointer to sqlite3_exec()
865** is NULL, then no callback is ever invoked and result rows are
866** ignored.
867**
868** ^If an error occurs while evaluating the SQL statements passed into
869** sqlite3_exec(), then execution of the current statement stops and
870** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
871** is not NULL then any error message is written into memory obtained
872** from [sqlite3_malloc()] and passed back through the 5th parameter.
873** To avoid memory leaks, the application should invoke [sqlite3_free()]
874** on error message strings returned through the 5th parameter of
875** of sqlite3_exec() after the error message string is no longer needed.
876** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
877** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
878** NULL before returning.
879**
880** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
881** routine returns SQLITE_ABORT without invoking the callback again and
882** without running any subsequent SQL statements.
883**
884** ^The 2nd argument to the sqlite3_exec() callback function is the
885** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
886** callback is an array of pointers to strings obtained as if from
887** [sqlite3_column_text()], one for each column.  ^If an element of a
888** result row is NULL then the corresponding string pointer for the
889** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
890** sqlite3_exec() callback is an array of pointers to strings where each
891** entry represents the name of corresponding result column as obtained
892** from [sqlite3_column_name()].
893**
894** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
895** to an empty string, or a pointer that contains only whitespace and/or
896** SQL comments, then no SQL statements are evaluated and the database
897** is not changed.
898**
899** Restrictions:
900**
901** <ul>
902** <li> The application must insure that the 1st parameter to sqlite3_exec()
903**      is a valid and open [database connection].
904** <li> The application must not close [database connection] specified by
905**      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
906** <li> The application must not modify the SQL statement text passed into
907**      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
908** </ul>
909*/
910SQLITE_API int sqlite3_exec(
911  sqlite3*,                                  /* An open database */
912  const char *sql,                           /* SQL to be evaluated */
913  int (*callback)(void*,int,char**,char**),  /* Callback function */
914  void *,                                    /* 1st argument to callback */
915  char **errmsg                              /* Error msg written here */
916);
917
918/*
919** CAPI3REF: Result Codes
920** KEYWORDS: SQLITE_OK {error code} {error codes}
921** KEYWORDS: {result code} {result codes}
922**
923** Many SQLite functions return an integer result code from the set shown
924** here in order to indicate success or failure.
925**
926** New error codes may be added in future versions of SQLite.
927**
928** See also: [SQLITE_IOERR_READ | extended result codes],
929** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
930*/
931#define SQLITE_OK           0   /* Successful result */
932/* beginning-of-error-codes */
933#define SQLITE_ERROR        1   /* SQL error or missing database */
934#define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
935#define SQLITE_PERM         3   /* Access permission denied */
936#define SQLITE_ABORT        4   /* Callback routine requested an abort */
937#define SQLITE_BUSY         5   /* The database file is locked */
938#define SQLITE_LOCKED       6   /* A table in the database is locked */
939#define SQLITE_NOMEM        7   /* A malloc() failed */
940#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
941#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
942#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
943#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
944#define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
945#define SQLITE_FULL        13   /* Insertion failed because database is full */
946#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
947#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
948#define SQLITE_EMPTY       16   /* Database is empty */
949#define SQLITE_SCHEMA      17   /* The database schema changed */
950#define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
951#define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
952#define SQLITE_MISMATCH    20   /* Data type mismatch */
953#define SQLITE_MISUSE      21   /* Library used incorrectly */
954#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
955#define SQLITE_AUTH        23   /* Authorization denied */
956#define SQLITE_FORMAT      24   /* Auxiliary database format error */
957#define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
958#define SQLITE_NOTADB      26   /* File opened that is not a database file */
959#define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
960#define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
961/* end-of-error-codes */
962
963/*
964** CAPI3REF: Extended Result Codes
965** KEYWORDS: {extended error code} {extended error codes}
966** KEYWORDS: {extended result code} {extended result codes}
967**
968** In its default configuration, SQLite API routines return one of 26 integer
969** [SQLITE_OK | result codes].  However, experience has shown that many of
970** these result codes are too coarse-grained.  They do not provide as
971** much information about problems as programmers might like.  In an effort to
972** address this, newer versions of SQLite (version 3.3.8 and later) include
973** support for additional result codes that provide more detailed information
974** about errors. The extended result codes are enabled or disabled
975** on a per database connection basis using the
976** [sqlite3_extended_result_codes()] API.
977**
978** Some of the available extended result codes are listed here.
979** One may expect the number of extended result codes will be expand
980** over time.  Software that uses extended result codes should expect
981** to see new result codes in future releases of SQLite.
982**
983** The SQLITE_OK result code will never be extended.  It will always
984** be exactly zero.
985*/
986#define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
987#define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
988#define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
989#define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
990#define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
991#define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
992#define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
993#define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
994#define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
995#define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
996#define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
997#define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
998#define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
999#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1000#define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1001#define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1002#define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1003#define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1004#define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1005#define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1006#define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1007#define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1008#define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1009#define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1010#define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1011#define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1012#define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1013#define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1014#define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1015
1016/*
1017** CAPI3REF: Flags For File Open Operations
1018**
1019** These bit values are intended for use in the
1020** 3rd parameter to the [sqlite3_open_v2()] interface and
1021** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1022*/
1023#define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1024#define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1025#define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1026#define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1027#define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1028#define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1029#define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1030#define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1031#define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1032#define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1033#define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1034#define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1035#define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1036#define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1037#define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1038#define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1039#define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1040#define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1041#define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1042
1043/* Reserved:                         0x00F00000 */
1044
1045/*
1046** CAPI3REF: Device Characteristics
1047**
1048** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1049** object returns an integer which is a vector of the these
1050** bit values expressing I/O characteristics of the mass storage
1051** device that holds the file that the [sqlite3_io_methods]
1052** refers to.
1053**
1054** The SQLITE_IOCAP_ATOMIC property means that all writes of
1055** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1056** mean that writes of blocks that are nnn bytes in size and
1057** are aligned to an address which is an integer multiple of
1058** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1059** that when data is appended to a file, the data is appended
1060** first then the size of the file is extended, never the other
1061** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1062** information is written to disk in the same order as calls
1063** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1064** after reboot following a crash or power loss, the only bytes in a
1065** file that were written at the application level might have changed
1066** and that adjacent bytes, even bytes within the same sector are
1067** guaranteed to be unchanged.
1068*/
1069#define SQLITE_IOCAP_ATOMIC                 0x00000001
1070#define SQLITE_IOCAP_ATOMIC512              0x00000002
1071#define SQLITE_IOCAP_ATOMIC1K               0x00000004
1072#define SQLITE_IOCAP_ATOMIC2K               0x00000008
1073#define SQLITE_IOCAP_ATOMIC4K               0x00000010
1074#define SQLITE_IOCAP_ATOMIC8K               0x00000020
1075#define SQLITE_IOCAP_ATOMIC16K              0x00000040
1076#define SQLITE_IOCAP_ATOMIC32K              0x00000080
1077#define SQLITE_IOCAP_ATOMIC64K              0x00000100
1078#define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1079#define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1080#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1081#define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1082
1083/*
1084** CAPI3REF: File Locking Levels
1085**
1086** SQLite uses one of these integer values as the second
1087** argument to calls it makes to the xLock() and xUnlock() methods
1088** of an [sqlite3_io_methods] object.
1089*/
1090#define SQLITE_LOCK_NONE          0
1091#define SQLITE_LOCK_SHARED        1
1092#define SQLITE_LOCK_RESERVED      2
1093#define SQLITE_LOCK_PENDING       3
1094#define SQLITE_LOCK_EXCLUSIVE     4
1095
1096/*
1097** CAPI3REF: Synchronization Type Flags
1098**
1099** When SQLite invokes the xSync() method of an
1100** [sqlite3_io_methods] object it uses a combination of
1101** these integer values as the second argument.
1102**
1103** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1104** sync operation only needs to flush data to mass storage.  Inode
1105** information need not be flushed. If the lower four bits of the flag
1106** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1107** If the lower four bits equal SQLITE_SYNC_FULL, that means
1108** to use Mac OS X style fullsync instead of fsync().
1109**
1110** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1111** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1112** settings.  The [synchronous pragma] determines when calls to the
1113** xSync VFS method occur and applies uniformly across all platforms.
1114** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1115** energetic or rigorous or forceful the sync operations are and
1116** only make a difference on Mac OSX for the default SQLite code.
1117** (Third-party VFS implementations might also make the distinction
1118** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1119** operating systems natively supported by SQLite, only Mac OSX
1120** cares about the difference.)
1121*/
1122#define SQLITE_SYNC_NORMAL        0x00002
1123#define SQLITE_SYNC_FULL          0x00003
1124#define SQLITE_SYNC_DATAONLY      0x00010
1125
1126/*
1127** CAPI3REF: OS Interface Open File Handle
1128**
1129** An [sqlite3_file] object represents an open file in the
1130** [sqlite3_vfs | OS interface layer].  Individual OS interface
1131** implementations will
1132** want to subclass this object by appending additional fields
1133** for their own use.  The pMethods entry is a pointer to an
1134** [sqlite3_io_methods] object that defines methods for performing
1135** I/O operations on the open file.
1136*/
1137typedef struct sqlite3_file sqlite3_file;
1138struct sqlite3_file {
1139  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1140};
1141
1142/*
1143** CAPI3REF: OS Interface File Virtual Methods Object
1144**
1145** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1146** [sqlite3_file] object (or, more commonly, a subclass of the
1147** [sqlite3_file] object) with a pointer to an instance of this object.
1148** This object defines the methods used to perform various operations
1149** against the open file represented by the [sqlite3_file] object.
1150**
1151** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
1152** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1153** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1154** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1155** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1156** to NULL.
1157**
1158** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1159** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1160** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1161** flag may be ORed in to indicate that only the data of the file
1162** and not its inode needs to be synced.
1163**
1164** The integer values to xLock() and xUnlock() are one of
1165** <ul>
1166** <li> [SQLITE_LOCK_NONE],
1167** <li> [SQLITE_LOCK_SHARED],
1168** <li> [SQLITE_LOCK_RESERVED],
1169** <li> [SQLITE_LOCK_PENDING], or
1170** <li> [SQLITE_LOCK_EXCLUSIVE].
1171** </ul>
1172** xLock() increases the lock. xUnlock() decreases the lock.
1173** The xCheckReservedLock() method checks whether any database connection,
1174** either in this process or in some other process, is holding a RESERVED,
1175** PENDING, or EXCLUSIVE lock on the file.  It returns true
1176** if such a lock exists and false otherwise.
1177**
1178** The xFileControl() method is a generic interface that allows custom
1179** VFS implementations to directly control an open file using the
1180** [sqlite3_file_control()] interface.  The second "op" argument is an
1181** integer opcode.  The third argument is a generic pointer intended to
1182** point to a structure that may contain arguments or space in which to
1183** write return values.  Potential uses for xFileControl() might be
1184** functions to enable blocking locks with timeouts, to change the
1185** locking strategy (for example to use dot-file locks), to inquire
1186** about the status of a lock, or to break stale locks.  The SQLite
1187** core reserves all opcodes less than 100 for its own use.
1188** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1189** Applications that define a custom xFileControl method should use opcodes
1190** greater than 100 to avoid conflicts.  VFS implementations should
1191** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1192** recognize.
1193**
1194** The xSectorSize() method returns the sector size of the
1195** device that underlies the file.  The sector size is the
1196** minimum write that can be performed without disturbing
1197** other bytes in the file.  The xDeviceCharacteristics()
1198** method returns a bit vector describing behaviors of the
1199** underlying device:
1200**
1201** <ul>
1202** <li> [SQLITE_IOCAP_ATOMIC]
1203** <li> [SQLITE_IOCAP_ATOMIC512]
1204** <li> [SQLITE_IOCAP_ATOMIC1K]
1205** <li> [SQLITE_IOCAP_ATOMIC2K]
1206** <li> [SQLITE_IOCAP_ATOMIC4K]
1207** <li> [SQLITE_IOCAP_ATOMIC8K]
1208** <li> [SQLITE_IOCAP_ATOMIC16K]
1209** <li> [SQLITE_IOCAP_ATOMIC32K]
1210** <li> [SQLITE_IOCAP_ATOMIC64K]
1211** <li> [SQLITE_IOCAP_SAFE_APPEND]
1212** <li> [SQLITE_IOCAP_SEQUENTIAL]
1213** </ul>
1214**
1215** The SQLITE_IOCAP_ATOMIC property means that all writes of
1216** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1217** mean that writes of blocks that are nnn bytes in size and
1218** are aligned to an address which is an integer multiple of
1219** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1220** that when data is appended to a file, the data is appended
1221** first then the size of the file is extended, never the other
1222** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1223** information is written to disk in the same order as calls
1224** to xWrite().
1225**
1226** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1227** in the unread portions of the buffer with zeros.  A VFS that
1228** fails to zero-fill short reads might seem to work.  However,
1229** failure to zero-fill short reads will eventually lead to
1230** database corruption.
1231*/
1232typedef struct sqlite3_io_methods sqlite3_io_methods;
1233struct sqlite3_io_methods {
1234  int iVersion;
1235  int (*xClose)(sqlite3_file*);
1236  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1237  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1238  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1239  int (*xSync)(sqlite3_file*, int flags);
1240  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1241  int (*xLock)(sqlite3_file*, int);
1242  int (*xUnlock)(sqlite3_file*, int);
1243  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1244  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1245  int (*xSectorSize)(sqlite3_file*);
1246  int (*xDeviceCharacteristics)(sqlite3_file*);
1247  /* Methods above are valid for version 1 */
1248  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1249  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1250  void (*xShmBarrier)(sqlite3_file*);
1251  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1252  /* Methods above are valid for version 2 */
1253  /* Additional methods may be added in future releases */
1254};
1255
1256/*
1257** CAPI3REF: Standard File Control Opcodes
1258**
1259** These integer constants are opcodes for the xFileControl method
1260** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1261** interface.
1262**
1263** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1264** opcode causes the xFileControl method to write the current state of
1265** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1266** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1267** into an integer that the pArg argument points to. This capability
1268** is used during testing and only needs to be supported when SQLITE_TEST
1269** is defined.
1270** <ul>
1271** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1272** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1273** layer a hint of how large the database file will grow to be during the
1274** current transaction.  This hint is not guaranteed to be accurate but it
1275** is often close.  The underlying VFS might choose to preallocate database
1276** file space based on this hint in order to help writes to the database
1277** file run faster.
1278**
1279** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1280** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1281** extends and truncates the database file in chunks of a size specified
1282** by the user. The fourth argument to [sqlite3_file_control()] should
1283** point to an integer (type int) containing the new chunk-size to use
1284** for the nominated database. Allocating database file space in large
1285** chunks (say 1MB at a time), may reduce file-system fragmentation and
1286** improve performance on some systems.
1287**
1288** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1289** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1290** to the [sqlite3_file] object associated with a particular database
1291** connection.  See the [sqlite3_file_control()] documentation for
1292** additional information.
1293**
1294** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1295** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1296** SQLite and sent to all VFSes in place of a call to the xSync method
1297** when the database connection has [PRAGMA synchronous] set to OFF.)^
1298** Some specialized VFSes need this signal in order to operate correctly
1299** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
1300** VFSes do not need this signal and should silently ignore this opcode.
1301** Applications should not call [sqlite3_file_control()] with this
1302** opcode as doing so may disrupt the operation of the specialized VFSes
1303** that do require it.
1304**
1305** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1306** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1307** retry counts and intervals for certain disk I/O operations for the
1308** windows [VFS] in order to provide robustness in the presence of
1309** anti-virus programs.  By default, the windows VFS will retry file read,
1310** file write, and file delete operations up to 10 times, with a delay
1311** of 25 milliseconds before the first retry and with the delay increasing
1312** by an additional 25 milliseconds with each subsequent retry.  This
1313** opcode allows these two values (10 retries and 25 milliseconds of delay)
1314** to be adjusted.  The values are changed for all database connections
1315** within the same process.  The argument is a pointer to an array of two
1316** integers where the first integer i the new retry count and the second
1317** integer is the delay.  If either integer is negative, then the setting
1318** is not changed but instead the prior value of that setting is written
1319** into the array entry, allowing the current retry settings to be
1320** interrogated.  The zDbName parameter is ignored.
1321**
1322** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1323** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1324** persistent [WAL | Write AHead Log] setting.  By default, the auxiliary
1325** write ahead log and shared memory files used for transaction control
1326** are automatically deleted when the latest connection to the database
1327** closes.  Setting persistent WAL mode causes those files to persist after
1328** close.  Persisting the files is useful when other processes that do not
1329** have write permission on the directory containing the database file want
1330** to read the database file, as the WAL and shared memory files must exist
1331** in order for the database to be readable.  The fourth parameter to
1332** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1333** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1334** WAL mode.  If the integer is -1, then it is overwritten with the current
1335** WAL persistence setting.
1336**
1337** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1338** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1339** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1340** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1341** xDeviceCharacteristics methods. The fourth parameter to
1342** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1343** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1344** mode.  If the integer is -1, then it is overwritten with the current
1345** zero-damage mode setting.
1346**
1347** <li>[[SQLITE_FCNTL_OVERWRITE]]
1348** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1349** a write transaction to indicate that, unless it is rolled back for some
1350** reason, the entire database file will be overwritten by the current
1351** transaction. This is used by VACUUM operations.
1352**
1353** <li>[[SQLITE_FCNTL_VFSNAME]]
1354** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1355** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1356** final bottom-level VFS are written into memory obtained from
1357** [sqlite3_malloc()] and the result is stored in the char* variable
1358** that the fourth parameter of [sqlite3_file_control()] points to.
1359** The caller is responsible for freeing the memory when done.  As with
1360** all file-control actions, there is no guarantee that this will actually
1361** do anything.  Callers should initialize the char* variable to a NULL
1362** pointer in case this file-control is not implemented.  This file-control
1363** is intended for diagnostic use only.
1364**
1365** <li>[[SQLITE_FCNTL_PRAGMA]]
1366** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1367** file control is sent to the open [sqlite3_file] object corresponding
1368** to the database file to which the pragma statement refers. ^The argument
1369** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1370** pointers to strings (char**) in which the second element of the array
1371** is the name of the pragma and the third element is the argument to the
1372** pragma or NULL if the pragma has no argument.  ^The handler for an
1373** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1374** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1375** or the equivalent and that string will become the result of the pragma or
1376** the error message if the pragma fails. ^If the
1377** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1378** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1379** file control returns [SQLITE_OK], then the parser assumes that the
1380** VFS has handled the PRAGMA itself and the parser generates a no-op
1381** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1382** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1383** that the VFS encountered an error while handling the [PRAGMA] and the
1384** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1385** file control occurs at the beginning of pragma statement analysis and so
1386** it is able to override built-in [PRAGMA] statements.
1387** </ul>
1388*/
1389#define SQLITE_FCNTL_LOCKSTATE               1
1390#define SQLITE_GET_LOCKPROXYFILE             2
1391#define SQLITE_SET_LOCKPROXYFILE             3
1392#define SQLITE_LAST_ERRNO                    4
1393#define SQLITE_FCNTL_SIZE_HINT               5
1394#define SQLITE_FCNTL_CHUNK_SIZE              6
1395#define SQLITE_FCNTL_FILE_POINTER            7
1396#define SQLITE_FCNTL_SYNC_OMITTED            8
1397#define SQLITE_FCNTL_WIN32_AV_RETRY          9
1398#define SQLITE_FCNTL_PERSIST_WAL            10
1399#define SQLITE_FCNTL_OVERWRITE              11
1400#define SQLITE_FCNTL_VFSNAME                12
1401#define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1402#define SQLITE_FCNTL_PRAGMA                 14
1403
1404/*
1405** CAPI3REF: Mutex Handle
1406**
1407** The mutex module within SQLite defines [sqlite3_mutex] to be an
1408** abstract type for a mutex object.  The SQLite core never looks
1409** at the internal representation of an [sqlite3_mutex].  It only
1410** deals with pointers to the [sqlite3_mutex] object.
1411**
1412** Mutexes are created using [sqlite3_mutex_alloc()].
1413*/
1414typedef struct sqlite3_mutex sqlite3_mutex;
1415
1416/*
1417** CAPI3REF: OS Interface Object
1418**
1419** An instance of the sqlite3_vfs object defines the interface between
1420** the SQLite core and the underlying operating system.  The "vfs"
1421** in the name of the object stands for "virtual file system".  See
1422** the [VFS | VFS documentation] for further information.
1423**
1424** The value of the iVersion field is initially 1 but may be larger in
1425** future versions of SQLite.  Additional fields may be appended to this
1426** object when the iVersion value is increased.  Note that the structure
1427** of the sqlite3_vfs object changes in the transaction between
1428** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1429** modified.
1430**
1431** The szOsFile field is the size of the subclassed [sqlite3_file]
1432** structure used by this VFS.  mxPathname is the maximum length of
1433** a pathname in this VFS.
1434**
1435** Registered sqlite3_vfs objects are kept on a linked list formed by
1436** the pNext pointer.  The [sqlite3_vfs_register()]
1437** and [sqlite3_vfs_unregister()] interfaces manage this list
1438** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1439** searches the list.  Neither the application code nor the VFS
1440** implementation should use the pNext pointer.
1441**
1442** The pNext field is the only field in the sqlite3_vfs
1443** structure that SQLite will ever modify.  SQLite will only access
1444** or modify this field while holding a particular static mutex.
1445** The application should never modify anything within the sqlite3_vfs
1446** object once the object has been registered.
1447**
1448** The zName field holds the name of the VFS module.  The name must
1449** be unique across all VFS modules.
1450**
1451** [[sqlite3_vfs.xOpen]]
1452** ^SQLite guarantees that the zFilename parameter to xOpen
1453** is either a NULL pointer or string obtained
1454** from xFullPathname() with an optional suffix added.
1455** ^If a suffix is added to the zFilename parameter, it will
1456** consist of a single "-" character followed by no more than
1457** 11 alphanumeric and/or "-" characters.
1458** ^SQLite further guarantees that
1459** the string will be valid and unchanged until xClose() is
1460** called. Because of the previous sentence,
1461** the [sqlite3_file] can safely store a pointer to the
1462** filename if it needs to remember the filename for some reason.
1463** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1464** must invent its own temporary name for the file.  ^Whenever the
1465** xFilename parameter is NULL it will also be the case that the
1466** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1467**
1468** The flags argument to xOpen() includes all bits set in
1469** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1470** or [sqlite3_open16()] is used, then flags includes at least
1471** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1472** If xOpen() opens a file read-only then it sets *pOutFlags to
1473** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1474**
1475** ^(SQLite will also add one of the following flags to the xOpen()
1476** call, depending on the object being opened:
1477**
1478** <ul>
1479** <li>  [SQLITE_OPEN_MAIN_DB]
1480** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1481** <li>  [SQLITE_OPEN_TEMP_DB]
1482** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1483** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1484** <li>  [SQLITE_OPEN_SUBJOURNAL]
1485** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1486** <li>  [SQLITE_OPEN_WAL]
1487** </ul>)^
1488**
1489** The file I/O implementation can use the object type flags to
1490** change the way it deals with files.  For example, an application
1491** that does not care about crash recovery or rollback might make
1492** the open of a journal file a no-op.  Writes to this journal would
1493** also be no-ops, and any attempt to read the journal would return
1494** SQLITE_IOERR.  Or the implementation might recognize that a database
1495** file will be doing page-aligned sector reads and writes in a random
1496** order and set up its I/O subsystem accordingly.
1497**
1498** SQLite might also add one of the following flags to the xOpen method:
1499**
1500** <ul>
1501** <li> [SQLITE_OPEN_DELETEONCLOSE]
1502** <li> [SQLITE_OPEN_EXCLUSIVE]
1503** </ul>
1504**
1505** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1506** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1507** will be set for TEMP databases and their journals, transient
1508** databases, and subjournals.
1509**
1510** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1511** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1512** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1513** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1514** SQLITE_OPEN_CREATE, is used to indicate that file should always
1515** be created, and that it is an error if it already exists.
1516** It is <i>not</i> used to indicate the file should be opened
1517** for exclusive access.
1518**
1519** ^At least szOsFile bytes of memory are allocated by SQLite
1520** to hold the  [sqlite3_file] structure passed as the third
1521** argument to xOpen.  The xOpen method does not have to
1522** allocate the structure; it should just fill it in.  Note that
1523** the xOpen method must set the sqlite3_file.pMethods to either
1524** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1525** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1526** element will be valid after xOpen returns regardless of the success
1527** or failure of the xOpen call.
1528**
1529** [[sqlite3_vfs.xAccess]]
1530** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1531** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1532** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1533** to test whether a file is at least readable.   The file can be a
1534** directory.
1535**
1536** ^SQLite will always allocate at least mxPathname+1 bytes for the
1537** output buffer xFullPathname.  The exact size of the output buffer
1538** is also passed as a parameter to both  methods. If the output buffer
1539** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1540** handled as a fatal error by SQLite, vfs implementations should endeavor
1541** to prevent this by setting mxPathname to a sufficiently large value.
1542**
1543** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1544** interfaces are not strictly a part of the filesystem, but they are
1545** included in the VFS structure for completeness.
1546** The xRandomness() function attempts to return nBytes bytes
1547** of good-quality randomness into zOut.  The return value is
1548** the actual number of bytes of randomness obtained.
1549** The xSleep() method causes the calling thread to sleep for at
1550** least the number of microseconds given.  ^The xCurrentTime()
1551** method returns a Julian Day Number for the current date and time as
1552** a floating point value.
1553** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1554** Day Number multiplied by 86400000 (the number of milliseconds in
1555** a 24-hour day).
1556** ^SQLite will use the xCurrentTimeInt64() method to get the current
1557** date and time if that method is available (if iVersion is 2 or
1558** greater and the function pointer is not NULL) and will fall back
1559** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1560**
1561** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1562** are not used by the SQLite core.  These optional interfaces are provided
1563** by some VFSes to facilitate testing of the VFS code. By overriding
1564** system calls with functions under its control, a test program can
1565** simulate faults and error conditions that would otherwise be difficult
1566** or impossible to induce.  The set of system calls that can be overridden
1567** varies from one VFS to another, and from one version of the same VFS to the
1568** next.  Applications that use these interfaces must be prepared for any
1569** or all of these interfaces to be NULL or for their behavior to change
1570** from one release to the next.  Applications must not attempt to access
1571** any of these methods if the iVersion of the VFS is less than 3.
1572*/
1573typedef struct sqlite3_vfs sqlite3_vfs;
1574typedef void (*sqlite3_syscall_ptr)(void);
1575struct sqlite3_vfs {
1576  int iVersion;            /* Structure version number (currently 3) */
1577  int szOsFile;            /* Size of subclassed sqlite3_file */
1578  int mxPathname;          /* Maximum file pathname length */
1579  sqlite3_vfs *pNext;      /* Next registered VFS */
1580  const char *zName;       /* Name of this virtual file system */
1581  void *pAppData;          /* Pointer to application-specific data */
1582  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1583               int flags, int *pOutFlags);
1584  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1585  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1586  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1587  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1588  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1589  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1590  void (*xDlClose)(sqlite3_vfs*, void*);
1591  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1592  int (*xSleep)(sqlite3_vfs*, int microseconds);
1593  int (*xCurrentTime)(sqlite3_vfs*, double*);
1594  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1595  /*
1596  ** The methods above are in version 1 of the sqlite_vfs object
1597  ** definition.  Those that follow are added in version 2 or later
1598  */
1599  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1600  /*
1601  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1602  ** Those below are for version 3 and greater.
1603  */
1604  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1605  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1606  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1607  /*
1608  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1609  ** New fields may be appended in figure versions.  The iVersion
1610  ** value will increment whenever this happens.
1611  */
1612};
1613
1614/*
1615** CAPI3REF: Flags for the xAccess VFS method
1616**
1617** These integer constants can be used as the third parameter to
1618** the xAccess method of an [sqlite3_vfs] object.  They determine
1619** what kind of permissions the xAccess method is looking for.
1620** With SQLITE_ACCESS_EXISTS, the xAccess method
1621** simply checks whether the file exists.
1622** With SQLITE_ACCESS_READWRITE, the xAccess method
1623** checks whether the named directory is both readable and writable
1624** (in other words, if files can be added, removed, and renamed within
1625** the directory).
1626** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1627** [temp_store_directory pragma], though this could change in a future
1628** release of SQLite.
1629** With SQLITE_ACCESS_READ, the xAccess method
1630** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1631** currently unused, though it might be used in a future release of
1632** SQLite.
1633*/
1634#define SQLITE_ACCESS_EXISTS    0
1635#define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1636#define SQLITE_ACCESS_READ      2   /* Unused */
1637
1638/*
1639** CAPI3REF: Flags for the xShmLock VFS method
1640**
1641** These integer constants define the various locking operations
1642** allowed by the xShmLock method of [sqlite3_io_methods].  The
1643** following are the only legal combinations of flags to the
1644** xShmLock method:
1645**
1646** <ul>
1647** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1648** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1649** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1650** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1651** </ul>
1652**
1653** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1654** was given no the corresponding lock.
1655**
1656** The xShmLock method can transition between unlocked and SHARED or
1657** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1658** and EXCLUSIVE.
1659*/
1660#define SQLITE_SHM_UNLOCK       1
1661#define SQLITE_SHM_LOCK         2
1662#define SQLITE_SHM_SHARED       4
1663#define SQLITE_SHM_EXCLUSIVE    8
1664
1665/*
1666** CAPI3REF: Maximum xShmLock index
1667**
1668** The xShmLock method on [sqlite3_io_methods] may use values
1669** between 0 and this upper bound as its "offset" argument.
1670** The SQLite core will never attempt to acquire or release a
1671** lock outside of this range
1672*/
1673#define SQLITE_SHM_NLOCK        8
1674
1675
1676/*
1677** CAPI3REF: Initialize The SQLite Library
1678**
1679** ^The sqlite3_initialize() routine initializes the
1680** SQLite library.  ^The sqlite3_shutdown() routine
1681** deallocates any resources that were allocated by sqlite3_initialize().
1682** These routines are designed to aid in process initialization and
1683** shutdown on embedded systems.  Workstation applications using
1684** SQLite normally do not need to invoke either of these routines.
1685**
1686** A call to sqlite3_initialize() is an "effective" call if it is
1687** the first time sqlite3_initialize() is invoked during the lifetime of
1688** the process, or if it is the first time sqlite3_initialize() is invoked
1689** following a call to sqlite3_shutdown().  ^(Only an effective call
1690** of sqlite3_initialize() does any initialization.  All other calls
1691** are harmless no-ops.)^
1692**
1693** A call to sqlite3_shutdown() is an "effective" call if it is the first
1694** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1695** an effective call to sqlite3_shutdown() does any deinitialization.
1696** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1697**
1698** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1699** is not.  The sqlite3_shutdown() interface must only be called from a
1700** single thread.  All open [database connections] must be closed and all
1701** other SQLite resources must be deallocated prior to invoking
1702** sqlite3_shutdown().
1703**
1704** Among other things, ^sqlite3_initialize() will invoke
1705** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1706** will invoke sqlite3_os_end().
1707**
1708** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1709** ^If for some reason, sqlite3_initialize() is unable to initialize
1710** the library (perhaps it is unable to allocate a needed resource such
1711** as a mutex) it returns an [error code] other than [SQLITE_OK].
1712**
1713** ^The sqlite3_initialize() routine is called internally by many other
1714** SQLite interfaces so that an application usually does not need to
1715** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1716** calls sqlite3_initialize() so the SQLite library will be automatically
1717** initialized when [sqlite3_open()] is called if it has not be initialized
1718** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1719** compile-time option, then the automatic calls to sqlite3_initialize()
1720** are omitted and the application must call sqlite3_initialize() directly
1721** prior to using any other SQLite interface.  For maximum portability,
1722** it is recommended that applications always invoke sqlite3_initialize()
1723** directly prior to using any other SQLite interface.  Future releases
1724** of SQLite may require this.  In other words, the behavior exhibited
1725** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1726** default behavior in some future release of SQLite.
1727**
1728** The sqlite3_os_init() routine does operating-system specific
1729** initialization of the SQLite library.  The sqlite3_os_end()
1730** routine undoes the effect of sqlite3_os_init().  Typical tasks
1731** performed by these routines include allocation or deallocation
1732** of static resources, initialization of global variables,
1733** setting up a default [sqlite3_vfs] module, or setting up
1734** a default configuration using [sqlite3_config()].
1735**
1736** The application should never invoke either sqlite3_os_init()
1737** or sqlite3_os_end() directly.  The application should only invoke
1738** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1739** interface is called automatically by sqlite3_initialize() and
1740** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1741** implementations for sqlite3_os_init() and sqlite3_os_end()
1742** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1743** When [custom builds | built for other platforms]
1744** (using the [SQLITE_OS_OTHER=1] compile-time
1745** option) the application must supply a suitable implementation for
1746** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1747** implementation of sqlite3_os_init() or sqlite3_os_end()
1748** must return [SQLITE_OK] on success and some other [error code] upon
1749** failure.
1750*/
1751SQLITE_API int sqlite3_initialize(void);
1752SQLITE_API int sqlite3_shutdown(void);
1753SQLITE_API int sqlite3_os_init(void);
1754SQLITE_API int sqlite3_os_end(void);
1755
1756/*
1757** CAPI3REF: Configuring The SQLite Library
1758**
1759** The sqlite3_config() interface is used to make global configuration
1760** changes to SQLite in order to tune SQLite to the specific needs of
1761** the application.  The default configuration is recommended for most
1762** applications and so this routine is usually not necessary.  It is
1763** provided to support rare applications with unusual needs.
1764**
1765** The sqlite3_config() interface is not threadsafe.  The application
1766** must insure that no other SQLite interfaces are invoked by other
1767** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1768** may only be invoked prior to library initialization using
1769** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1770** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1771** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1772** Note, however, that ^sqlite3_config() can be called as part of the
1773** implementation of an application-defined [sqlite3_os_init()].
1774**
1775** The first argument to sqlite3_config() is an integer
1776** [configuration option] that determines
1777** what property of SQLite is to be configured.  Subsequent arguments
1778** vary depending on the [configuration option]
1779** in the first argument.
1780**
1781** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1782** ^If the option is unknown or SQLite is unable to set the option
1783** then this routine returns a non-zero [error code].
1784*/
1785SQLITE_API int sqlite3_config(int, ...);
1786
1787/*
1788** CAPI3REF: Configure database connections
1789**
1790** The sqlite3_db_config() interface is used to make configuration
1791** changes to a [database connection].  The interface is similar to
1792** [sqlite3_config()] except that the changes apply to a single
1793** [database connection] (specified in the first argument).
1794**
1795** The second argument to sqlite3_db_config(D,V,...)  is the
1796** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1797** that indicates what aspect of the [database connection] is being configured.
1798** Subsequent arguments vary depending on the configuration verb.
1799**
1800** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1801** the call is considered successful.
1802*/
1803SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1804
1805/*
1806** CAPI3REF: Memory Allocation Routines
1807**
1808** An instance of this object defines the interface between SQLite
1809** and low-level memory allocation routines.
1810**
1811** This object is used in only one place in the SQLite interface.
1812** A pointer to an instance of this object is the argument to
1813** [sqlite3_config()] when the configuration option is
1814** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1815** By creating an instance of this object
1816** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1817** during configuration, an application can specify an alternative
1818** memory allocation subsystem for SQLite to use for all of its
1819** dynamic memory needs.
1820**
1821** Note that SQLite comes with several [built-in memory allocators]
1822** that are perfectly adequate for the overwhelming majority of applications
1823** and that this object is only useful to a tiny minority of applications
1824** with specialized memory allocation requirements.  This object is
1825** also used during testing of SQLite in order to specify an alternative
1826** memory allocator that simulates memory out-of-memory conditions in
1827** order to verify that SQLite recovers gracefully from such
1828** conditions.
1829**
1830** The xMalloc, xRealloc, and xFree methods must work like the
1831** malloc(), realloc() and free() functions from the standard C library.
1832** ^SQLite guarantees that the second argument to
1833** xRealloc is always a value returned by a prior call to xRoundup.
1834**
1835** xSize should return the allocated size of a memory allocation
1836** previously obtained from xMalloc or xRealloc.  The allocated size
1837** is always at least as big as the requested size but may be larger.
1838**
1839** The xRoundup method returns what would be the allocated size of
1840** a memory allocation given a particular requested size.  Most memory
1841** allocators round up memory allocations at least to the next multiple
1842** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1843** Every memory allocation request coming in through [sqlite3_malloc()]
1844** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0,
1845** that causes the corresponding memory allocation to fail.
1846**
1847** The xInit method initializes the memory allocator.  (For example,
1848** it might allocate any require mutexes or initialize internal data
1849** structures.  The xShutdown method is invoked (indirectly) by
1850** [sqlite3_shutdown()] and should deallocate any resources acquired
1851** by xInit.  The pAppData pointer is used as the only parameter to
1852** xInit and xShutdown.
1853**
1854** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1855** the xInit method, so the xInit method need not be threadsafe.  The
1856** xShutdown method is only called from [sqlite3_shutdown()] so it does
1857** not need to be threadsafe either.  For all other methods, SQLite
1858** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1859** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1860** it is by default) and so the methods are automatically serialized.
1861** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1862** methods must be threadsafe or else make their own arrangements for
1863** serialization.
1864**
1865** SQLite will never invoke xInit() more than once without an intervening
1866** call to xShutdown().
1867*/
1868typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1869struct sqlite3_mem_methods {
1870  void *(*xMalloc)(int);         /* Memory allocation function */
1871  void (*xFree)(void*);          /* Free a prior allocation */
1872  void *(*xRealloc)(void*,int);  /* Resize an allocation */
1873  int (*xSize)(void*);           /* Return the size of an allocation */
1874  int (*xRoundup)(int);          /* Round up request size to allocation size */
1875  int (*xInit)(void*);           /* Initialize the memory allocator */
1876  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1877  void *pAppData;                /* Argument to xInit() and xShutdown() */
1878};
1879
1880/*
1881** CAPI3REF: Configuration Options
1882** KEYWORDS: {configuration option}
1883**
1884** These constants are the available integer configuration options that
1885** can be passed as the first argument to the [sqlite3_config()] interface.
1886**
1887** New configuration options may be added in future releases of SQLite.
1888** Existing configuration options might be discontinued.  Applications
1889** should check the return code from [sqlite3_config()] to make sure that
1890** the call worked.  The [sqlite3_config()] interface will return a
1891** non-zero [error code] if a discontinued or unsupported configuration option
1892** is invoked.
1893**
1894** <dl>
1895** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1896** <dd>There are no arguments to this option.  ^This option sets the
1897** [threading mode] to Single-thread.  In other words, it disables
1898** all mutexing and puts SQLite into a mode where it can only be used
1899** by a single thread.   ^If SQLite is compiled with
1900** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1901** it is not possible to change the [threading mode] from its default
1902** value of Single-thread and so [sqlite3_config()] will return
1903** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1904** configuration option.</dd>
1905**
1906** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1907** <dd>There are no arguments to this option.  ^This option sets the
1908** [threading mode] to Multi-thread.  In other words, it disables
1909** mutexing on [database connection] and [prepared statement] objects.
1910** The application is responsible for serializing access to
1911** [database connections] and [prepared statements].  But other mutexes
1912** are enabled so that SQLite will be safe to use in a multi-threaded
1913** environment as long as no two threads attempt to use the same
1914** [database connection] at the same time.  ^If SQLite is compiled with
1915** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1916** it is not possible to set the Multi-thread [threading mode] and
1917** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1918** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1919**
1920** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1921** <dd>There are no arguments to this option.  ^This option sets the
1922** [threading mode] to Serialized. In other words, this option enables
1923** all mutexes including the recursive
1924** mutexes on [database connection] and [prepared statement] objects.
1925** In this mode (which is the default when SQLite is compiled with
1926** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1927** to [database connections] and [prepared statements] so that the
1928** application is free to use the same [database connection] or the
1929** same [prepared statement] in different threads at the same time.
1930** ^If SQLite is compiled with
1931** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1932** it is not possible to set the Serialized [threading mode] and
1933** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1934** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1935**
1936** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1937** <dd> ^(This option takes a single argument which is a pointer to an
1938** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1939** alternative low-level memory allocation routines to be used in place of
1940** the memory allocation routines built into SQLite.)^ ^SQLite makes
1941** its own private copy of the content of the [sqlite3_mem_methods] structure
1942** before the [sqlite3_config()] call returns.</dd>
1943**
1944** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1945** <dd> ^(This option takes a single argument which is a pointer to an
1946** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1947** structure is filled with the currently defined memory allocation routines.)^
1948** This option can be used to overload the default memory allocation
1949** routines with a wrapper that simulations memory allocation failure or
1950** tracks memory usage, for example. </dd>
1951**
1952** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1953** <dd> ^This option takes single argument of type int, interpreted as a
1954** boolean, which enables or disables the collection of memory allocation
1955** statistics. ^(When memory allocation statistics are disabled, the
1956** following SQLite interfaces become non-operational:
1957**   <ul>
1958**   <li> [sqlite3_memory_used()]
1959**   <li> [sqlite3_memory_highwater()]
1960**   <li> [sqlite3_soft_heap_limit64()]
1961**   <li> [sqlite3_status()]
1962**   </ul>)^
1963** ^Memory allocation statistics are enabled by default unless SQLite is
1964** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1965** allocation statistics are disabled by default.
1966** </dd>
1967**
1968** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1969** <dd> ^This option specifies a static memory buffer that SQLite can use for
1970** scratch memory.  There are three arguments:  A pointer an 8-byte
1971** aligned memory buffer from which the scratch allocations will be
1972** drawn, the size of each scratch allocation (sz),
1973** and the maximum number of scratch allocations (N).  The sz
1974** argument must be a multiple of 16.
1975** The first argument must be a pointer to an 8-byte aligned buffer
1976** of at least sz*N bytes of memory.
1977** ^SQLite will use no more than two scratch buffers per thread.  So
1978** N should be set to twice the expected maximum number of threads.
1979** ^SQLite will never require a scratch buffer that is more than 6
1980** times the database page size. ^If SQLite needs needs additional
1981** scratch memory beyond what is provided by this configuration option, then
1982** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1983**
1984** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1985** <dd> ^This option specifies a static memory buffer that SQLite can use for
1986** the database page cache with the default page cache implementation.
1987** This configuration should not be used if an application-define page
1988** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
1989** There are three arguments to this option: A pointer to 8-byte aligned
1990** memory, the size of each page buffer (sz), and the number of pages (N).
1991** The sz argument should be the size of the largest database page
1992** (a power of two between 512 and 32768) plus a little extra for each
1993** page header.  ^The page header size is 20 to 40 bytes depending on
1994** the host architecture.  ^It is harmless, apart from the wasted memory,
1995** to make sz a little too large.  The first
1996** argument should point to an allocation of at least sz*N bytes of memory.
1997** ^SQLite will use the memory provided by the first argument to satisfy its
1998** memory needs for the first N pages that it adds to cache.  ^If additional
1999** page cache memory is needed beyond what is provided by this option, then
2000** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2001** The pointer in the first argument must
2002** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2003** will be undefined.</dd>
2004**
2005** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2006** <dd> ^This option specifies a static memory buffer that SQLite will use
2007** for all of its dynamic memory allocation needs beyond those provided
2008** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2009** There are three arguments: An 8-byte aligned pointer to the memory,
2010** the number of bytes in the memory buffer, and the minimum allocation size.
2011** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2012** to using its default memory allocator (the system malloc() implementation),
2013** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2014** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2015** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2016** allocator is engaged to handle all of SQLites memory allocation needs.
2017** The first pointer (the memory pointer) must be aligned to an 8-byte
2018** boundary or subsequent behavior of SQLite will be undefined.
2019** The minimum allocation size is capped at 2**12. Reasonable values
2020** for the minimum allocation size are 2**5 through 2**8.</dd>
2021**
2022** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2023** <dd> ^(This option takes a single argument which is a pointer to an
2024** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
2025** alternative low-level mutex routines to be used in place
2026** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
2027** content of the [sqlite3_mutex_methods] structure before the call to
2028** [sqlite3_config()] returns. ^If SQLite is compiled with
2029** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2030** the entire mutexing subsystem is omitted from the build and hence calls to
2031** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2032** return [SQLITE_ERROR].</dd>
2033**
2034** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2035** <dd> ^(This option takes a single argument which is a pointer to an
2036** instance of the [sqlite3_mutex_methods] structure.  The
2037** [sqlite3_mutex_methods]
2038** structure is filled with the currently defined mutex routines.)^
2039** This option can be used to overload the default mutex allocation
2040** routines with a wrapper used to track mutex usage for performance
2041** profiling or testing, for example.   ^If SQLite is compiled with
2042** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2043** the entire mutexing subsystem is omitted from the build and hence calls to
2044** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2045** return [SQLITE_ERROR].</dd>
2046**
2047** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2048** <dd> ^(This option takes two arguments that determine the default
2049** memory allocation for the lookaside memory allocator on each
2050** [database connection].  The first argument is the
2051** size of each lookaside buffer slot and the second is the number of
2052** slots allocated to each database connection.)^  ^(This option sets the
2053** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2054** verb to [sqlite3_db_config()] can be used to change the lookaside
2055** configuration on individual connections.)^ </dd>
2056**
2057** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2058** <dd> ^(This option takes a single argument which is a pointer to
2059** an [sqlite3_pcache_methods2] object.  This object specifies the interface
2060** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2061** object and uses it for page cache memory allocations.</dd>
2062**
2063** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2064** <dd> ^(This option takes a single argument which is a pointer to an
2065** [sqlite3_pcache_methods2] object.  SQLite copies of the current
2066** page cache implementation into that object.)^ </dd>
2067**
2068** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2069** <dd> ^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2070** function with a call signature of void(*)(void*,int,const char*),
2071** and a pointer to void. ^If the function pointer is not NULL, it is
2072** invoked by [sqlite3_log()] to process each logging event.  ^If the
2073** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2074** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2075** passed through as the first parameter to the application-defined logger
2076** function whenever that function is invoked.  ^The second parameter to
2077** the logger function is a copy of the first parameter to the corresponding
2078** [sqlite3_log()] call and is intended to be a [result code] or an
2079** [extended result code].  ^The third parameter passed to the logger is
2080** log message after formatting via [sqlite3_snprintf()].
2081** The SQLite logging interface is not reentrant; the logger function
2082** supplied by the application must not invoke any SQLite interface.
2083** In a multi-threaded application, the application-defined logger
2084** function must be threadsafe. </dd>
2085**
2086** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2087** <dd> This option takes a single argument of type int. If non-zero, then
2088** URI handling is globally enabled. If the parameter is zero, then URI handling
2089** is globally disabled. If URI handling is globally enabled, all filenames
2090** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2091** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2092** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2093** connection is opened. If it is globally disabled, filenames are
2094** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2095** database connection is opened. By default, URI handling is globally
2096** disabled. The default value may be changed by compiling with the
2097** [SQLITE_USE_URI] symbol defined.
2098**
2099** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2100** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFNIG_GETPCACHE
2101** <dd> These options are obsolete and should not be used by new code.
2102** They are retained for backwards compatibility but are now no-ops.
2103** </dl>
2104*/
2105#define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2106#define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2107#define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2108#define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2109#define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2110#define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2111#define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2112#define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2113#define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2114#define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2115#define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2116/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2117#define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2118#define SQLITE_CONFIG_PCACHE       14  /* no-op */
2119#define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2120#define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2121#define SQLITE_CONFIG_URI          17  /* int */
2122#define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2123#define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2124
2125/*
2126** CAPI3REF: Database Connection Configuration Options
2127**
2128** These constants are the available integer configuration options that
2129** can be passed as the second argument to the [sqlite3_db_config()] interface.
2130**
2131** New configuration options may be added in future releases of SQLite.
2132** Existing configuration options might be discontinued.  Applications
2133** should check the return code from [sqlite3_db_config()] to make sure that
2134** the call worked.  ^The [sqlite3_db_config()] interface will return a
2135** non-zero [error code] if a discontinued or unsupported configuration option
2136** is invoked.
2137**
2138** <dl>
2139** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2140** <dd> ^This option takes three additional arguments that determine the
2141** [lookaside memory allocator] configuration for the [database connection].
2142** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2143** pointer to a memory buffer to use for lookaside memory.
2144** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2145** may be NULL in which case SQLite will allocate the
2146** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2147** size of each lookaside buffer slot.  ^The third argument is the number of
2148** slots.  The size of the buffer in the first argument must be greater than
2149** or equal to the product of the second and third arguments.  The buffer
2150** must be aligned to an 8-byte boundary.  ^If the second argument to
2151** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2152** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2153** configuration for a database connection can only be changed when that
2154** connection is not currently using lookaside memory, or in other words
2155** when the "current value" returned by
2156** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2157** Any attempt to change the lookaside memory configuration when lookaside
2158** memory is in use leaves the configuration unchanged and returns
2159** [SQLITE_BUSY].)^</dd>
2160**
2161** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2162** <dd> ^This option is used to enable or disable the enforcement of
2163** [foreign key constraints].  There should be two additional arguments.
2164** The first argument is an integer which is 0 to disable FK enforcement,
2165** positive to enable FK enforcement or negative to leave FK enforcement
2166** unchanged.  The second parameter is a pointer to an integer into which
2167** is written 0 or 1 to indicate whether FK enforcement is off or on
2168** following this call.  The second parameter may be a NULL pointer, in
2169** which case the FK enforcement setting is not reported back. </dd>
2170**
2171** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2172** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2173** There should be two additional arguments.
2174** The first argument is an integer which is 0 to disable triggers,
2175** positive to enable triggers or negative to leave the setting unchanged.
2176** The second parameter is a pointer to an integer into which
2177** is written 0 or 1 to indicate whether triggers are disabled or enabled
2178** following this call.  The second parameter may be a NULL pointer, in
2179** which case the trigger setting is not reported back. </dd>
2180**
2181** </dl>
2182*/
2183#define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2184#define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2185#define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2186
2187
2188/*
2189** CAPI3REF: Enable Or Disable Extended Result Codes
2190**
2191** ^The sqlite3_extended_result_codes() routine enables or disables the
2192** [extended result codes] feature of SQLite. ^The extended result
2193** codes are disabled by default for historical compatibility.
2194*/
2195SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2196
2197/*
2198** CAPI3REF: Last Insert Rowid
2199**
2200** ^Each entry in an SQLite table has a unique 64-bit signed
2201** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2202** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2203** names are not also used by explicitly declared columns. ^If
2204** the table has a column of type [INTEGER PRIMARY KEY] then that column
2205** is another alias for the rowid.
2206**
2207** ^This routine returns the [rowid] of the most recent
2208** successful [INSERT] into the database from the [database connection]
2209** in the first argument.  ^As of SQLite version 3.7.7, this routines
2210** records the last insert rowid of both ordinary tables and [virtual tables].
2211** ^If no successful [INSERT]s
2212** have ever occurred on that database connection, zero is returned.
2213**
2214** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2215** method, then this routine will return the [rowid] of the inserted
2216** row as long as the trigger or virtual table method is running.
2217** But once the trigger or virtual table method ends, the value returned
2218** by this routine reverts to what it was before the trigger or virtual
2219** table method began.)^
2220**
2221** ^An [INSERT] that fails due to a constraint violation is not a
2222** successful [INSERT] and does not change the value returned by this
2223** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2224** and INSERT OR ABORT make no changes to the return value of this
2225** routine when their insertion fails.  ^(When INSERT OR REPLACE
2226** encounters a constraint violation, it does not fail.  The
2227** INSERT continues to completion after deleting rows that caused
2228** the constraint problem so INSERT OR REPLACE will always change
2229** the return value of this interface.)^
2230**
2231** ^For the purposes of this routine, an [INSERT] is considered to
2232** be successful even if it is subsequently rolled back.
2233**
2234** This function is accessible to SQL statements via the
2235** [last_insert_rowid() SQL function].
2236**
2237** If a separate thread performs a new [INSERT] on the same
2238** database connection while the [sqlite3_last_insert_rowid()]
2239** function is running and thus changes the last insert [rowid],
2240** then the value returned by [sqlite3_last_insert_rowid()] is
2241** unpredictable and might not equal either the old or the new
2242** last insert [rowid].
2243*/
2244SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2245
2246/*
2247** CAPI3REF: Count The Number Of Rows Modified
2248**
2249** ^This function returns the number of database rows that were changed
2250** or inserted or deleted by the most recently completed SQL statement
2251** on the [database connection] specified by the first parameter.
2252** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2253** or [DELETE] statement are counted.  Auxiliary changes caused by
2254** triggers or [foreign key actions] are not counted.)^ Use the
2255** [sqlite3_total_changes()] function to find the total number of changes
2256** including changes caused by triggers and foreign key actions.
2257**
2258** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2259** are not counted.  Only real table changes are counted.
2260**
2261** ^(A "row change" is a change to a single row of a single table
2262** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2263** are changed as side effects of [REPLACE] constraint resolution,
2264** rollback, ABORT processing, [DROP TABLE], or by any other
2265** mechanisms do not count as direct row changes.)^
2266**
2267** A "trigger context" is a scope of execution that begins and
2268** ends with the script of a [CREATE TRIGGER | trigger].
2269** Most SQL statements are
2270** evaluated outside of any trigger.  This is the "top level"
2271** trigger context.  If a trigger fires from the top level, a
2272** new trigger context is entered for the duration of that one
2273** trigger.  Subtriggers create subcontexts for their duration.
2274**
2275** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2276** not create a new trigger context.
2277**
2278** ^This function returns the number of direct row changes in the
2279** most recent INSERT, UPDATE, or DELETE statement within the same
2280** trigger context.
2281**
2282** ^Thus, when called from the top level, this function returns the
2283** number of changes in the most recent INSERT, UPDATE, or DELETE
2284** that also occurred at the top level.  ^(Within the body of a trigger,
2285** the sqlite3_changes() interface can be called to find the number of
2286** changes in the most recently completed INSERT, UPDATE, or DELETE
2287** statement within the body of the same trigger.
2288** However, the number returned does not include changes
2289** caused by subtriggers since those have their own context.)^
2290**
2291** See also the [sqlite3_total_changes()] interface, the
2292** [count_changes pragma], and the [changes() SQL function].
2293**
2294** If a separate thread makes changes on the same database connection
2295** while [sqlite3_changes()] is running then the value returned
2296** is unpredictable and not meaningful.
2297*/
2298SQLITE_API int sqlite3_changes(sqlite3*);
2299
2300/*
2301** CAPI3REF: Total Number Of Rows Modified
2302**
2303** ^This function returns the number of row changes caused by [INSERT],
2304** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2305** ^(The count returned by sqlite3_total_changes() includes all changes
2306** from all [CREATE TRIGGER | trigger] contexts and changes made by
2307** [foreign key actions]. However,
2308** the count does not include changes used to implement [REPLACE] constraints,
2309** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2310** count does not include rows of views that fire an [INSTEAD OF trigger],
2311** though if the INSTEAD OF trigger makes changes of its own, those changes
2312** are counted.)^
2313** ^The sqlite3_total_changes() function counts the changes as soon as
2314** the statement that makes them is completed (when the statement handle
2315** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2316**
2317** See also the [sqlite3_changes()] interface, the
2318** [count_changes pragma], and the [total_changes() SQL function].
2319**
2320** If a separate thread makes changes on the same database connection
2321** while [sqlite3_total_changes()] is running then the value
2322** returned is unpredictable and not meaningful.
2323*/
2324SQLITE_API int sqlite3_total_changes(sqlite3*);
2325
2326/*
2327** CAPI3REF: Interrupt A Long-Running Query
2328**
2329** ^This function causes any pending database operation to abort and
2330** return at its earliest opportunity. This routine is typically
2331** called in response to a user action such as pressing "Cancel"
2332** or Ctrl-C where the user wants a long query operation to halt
2333** immediately.
2334**
2335** ^It is safe to call this routine from a thread different from the
2336** thread that is currently running the database operation.  But it
2337** is not safe to call this routine with a [database connection] that
2338** is closed or might close before sqlite3_interrupt() returns.
2339**
2340** ^If an SQL operation is very nearly finished at the time when
2341** sqlite3_interrupt() is called, then it might not have an opportunity
2342** to be interrupted and might continue to completion.
2343**
2344** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2345** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2346** that is inside an explicit transaction, then the entire transaction
2347** will be rolled back automatically.
2348**
2349** ^The sqlite3_interrupt(D) call is in effect until all currently running
2350** SQL statements on [database connection] D complete.  ^Any new SQL statements
2351** that are started after the sqlite3_interrupt() call and before the
2352** running statements reaches zero are interrupted as if they had been
2353** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2354** that are started after the running statement count reaches zero are
2355** not effected by the sqlite3_interrupt().
2356** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2357** SQL statements is a no-op and has no effect on SQL statements
2358** that are started after the sqlite3_interrupt() call returns.
2359**
2360** If the database connection closes while [sqlite3_interrupt()]
2361** is running then bad things will likely happen.
2362*/
2363SQLITE_API void sqlite3_interrupt(sqlite3*);
2364
2365/*
2366** CAPI3REF: Determine If An SQL Statement Is Complete
2367**
2368** These routines are useful during command-line input to determine if the
2369** currently entered text seems to form a complete SQL statement or
2370** if additional input is needed before sending the text into
2371** SQLite for parsing.  ^These routines return 1 if the input string
2372** appears to be a complete SQL statement.  ^A statement is judged to be
2373** complete if it ends with a semicolon token and is not a prefix of a
2374** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2375** string literals or quoted identifier names or comments are not
2376** independent tokens (they are part of the token in which they are
2377** embedded) and thus do not count as a statement terminator.  ^Whitespace
2378** and comments that follow the final semicolon are ignored.
2379**
2380** ^These routines return 0 if the statement is incomplete.  ^If a
2381** memory allocation fails, then SQLITE_NOMEM is returned.
2382**
2383** ^These routines do not parse the SQL statements thus
2384** will not detect syntactically incorrect SQL.
2385**
2386** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2387** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2388** automatically by sqlite3_complete16().  If that initialization fails,
2389** then the return value from sqlite3_complete16() will be non-zero
2390** regardless of whether or not the input SQL is complete.)^
2391**
2392** The input to [sqlite3_complete()] must be a zero-terminated
2393** UTF-8 string.
2394**
2395** The input to [sqlite3_complete16()] must be a zero-terminated
2396** UTF-16 string in native byte order.
2397*/
2398SQLITE_API int sqlite3_complete(const char *sql);
2399SQLITE_API int sqlite3_complete16(const void *sql);
2400
2401/*
2402** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2403**
2404** ^This routine sets a callback function that might be invoked whenever
2405** an attempt is made to open a database table that another thread
2406** or process has locked.
2407**
2408** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2409** is returned immediately upon encountering the lock.  ^If the busy callback
2410** is not NULL, then the callback might be invoked with two arguments.
2411**
2412** ^The first argument to the busy handler is a copy of the void* pointer which
2413** is the third argument to sqlite3_busy_handler().  ^The second argument to
2414** the busy handler callback is the number of times that the busy handler has
2415** been invoked for this locking event.  ^If the
2416** busy callback returns 0, then no additional attempts are made to
2417** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2418** ^If the callback returns non-zero, then another attempt
2419** is made to open the database for reading and the cycle repeats.
2420**
2421** The presence of a busy handler does not guarantee that it will be invoked
2422** when there is lock contention. ^If SQLite determines that invoking the busy
2423** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2424** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2425** Consider a scenario where one process is holding a read lock that
2426** it is trying to promote to a reserved lock and
2427** a second process is holding a reserved lock that it is trying
2428** to promote to an exclusive lock.  The first process cannot proceed
2429** because it is blocked by the second and the second process cannot
2430** proceed because it is blocked by the first.  If both processes
2431** invoke the busy handlers, neither will make any progress.  Therefore,
2432** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2433** will induce the first process to release its read lock and allow
2434** the second process to proceed.
2435**
2436** ^The default busy callback is NULL.
2437**
2438** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2439** when SQLite is in the middle of a large transaction where all the
2440** changes will not fit into the in-memory cache.  SQLite will
2441** already hold a RESERVED lock on the database file, but it needs
2442** to promote this lock to EXCLUSIVE so that it can spill cache
2443** pages into the database file without harm to concurrent
2444** readers.  ^If it is unable to promote the lock, then the in-memory
2445** cache will be left in an inconsistent state and so the error
2446** code is promoted from the relatively benign [SQLITE_BUSY] to
2447** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2448** forces an automatic rollback of the changes.  See the
2449** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2450** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2451** this is important.
2452**
2453** ^(There can only be a single busy handler defined for each
2454** [database connection].  Setting a new busy handler clears any
2455** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2456** will also set or clear the busy handler.
2457**
2458** The busy callback should not take any actions which modify the
2459** database connection that invoked the busy handler.  Any such actions
2460** result in undefined behavior.
2461**
2462** A busy handler must not close the database connection
2463** or [prepared statement] that invoked the busy handler.
2464*/
2465SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2466
2467/*
2468** CAPI3REF: Set A Busy Timeout
2469**
2470** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2471** for a specified amount of time when a table is locked.  ^The handler
2472** will sleep multiple times until at least "ms" milliseconds of sleeping
2473** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2474** the handler returns 0 which causes [sqlite3_step()] to return
2475** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2476**
2477** ^Calling this routine with an argument less than or equal to zero
2478** turns off all busy handlers.
2479**
2480** ^(There can only be a single busy handler for a particular
2481** [database connection] any any given moment.  If another busy handler
2482** was defined  (using [sqlite3_busy_handler()]) prior to calling
2483** this routine, that other busy handler is cleared.)^
2484*/
2485SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2486
2487/*
2488** CAPI3REF: Convenience Routines For Running Queries
2489**
2490** This is a legacy interface that is preserved for backwards compatibility.
2491** Use of this interface is not recommended.
2492**
2493** Definition: A <b>result table</b> is memory data structure created by the
2494** [sqlite3_get_table()] interface.  A result table records the
2495** complete query results from one or more queries.
2496**
2497** The table conceptually has a number of rows and columns.  But
2498** these numbers are not part of the result table itself.  These
2499** numbers are obtained separately.  Let N be the number of rows
2500** and M be the number of columns.
2501**
2502** A result table is an array of pointers to zero-terminated UTF-8 strings.
2503** There are (N+1)*M elements in the array.  The first M pointers point
2504** to zero-terminated strings that  contain the names of the columns.
2505** The remaining entries all point to query results.  NULL values result
2506** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2507** string representation as returned by [sqlite3_column_text()].
2508**
2509** A result table might consist of one or more memory allocations.
2510** It is not safe to pass a result table directly to [sqlite3_free()].
2511** A result table should be deallocated using [sqlite3_free_table()].
2512**
2513** ^(As an example of the result table format, suppose a query result
2514** is as follows:
2515**
2516** <blockquote><pre>
2517**        Name        | Age
2518**        -----------------------
2519**        Alice       | 43
2520**        Bob         | 28
2521**        Cindy       | 21
2522** </pre></blockquote>
2523**
2524** There are two column (M==2) and three rows (N==3).  Thus the
2525** result table has 8 entries.  Suppose the result table is stored
2526** in an array names azResult.  Then azResult holds this content:
2527**
2528** <blockquote><pre>
2529**        azResult&#91;0] = "Name";
2530**        azResult&#91;1] = "Age";
2531**        azResult&#91;2] = "Alice";
2532**        azResult&#91;3] = "43";
2533**        azResult&#91;4] = "Bob";
2534**        azResult&#91;5] = "28";
2535**        azResult&#91;6] = "Cindy";
2536**        azResult&#91;7] = "21";
2537** </pre></blockquote>)^
2538**
2539** ^The sqlite3_get_table() function evaluates one or more
2540** semicolon-separated SQL statements in the zero-terminated UTF-8
2541** string of its 2nd parameter and returns a result table to the
2542** pointer given in its 3rd parameter.
2543**
2544** After the application has finished with the result from sqlite3_get_table(),
2545** it must pass the result table pointer to sqlite3_free_table() in order to
2546** release the memory that was malloced.  Because of the way the
2547** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2548** function must not try to call [sqlite3_free()] directly.  Only
2549** [sqlite3_free_table()] is able to release the memory properly and safely.
2550**
2551** The sqlite3_get_table() interface is implemented as a wrapper around
2552** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2553** to any internal data structures of SQLite.  It uses only the public
2554** interface defined here.  As a consequence, errors that occur in the
2555** wrapper layer outside of the internal [sqlite3_exec()] call are not
2556** reflected in subsequent calls to [sqlite3_errcode()] or
2557** [sqlite3_errmsg()].
2558*/
2559SQLITE_API int sqlite3_get_table(
2560  sqlite3 *db,          /* An open database */
2561  const char *zSql,     /* SQL to be evaluated */
2562  char ***pazResult,    /* Results of the query */
2563  int *pnRow,           /* Number of result rows written here */
2564  int *pnColumn,        /* Number of result columns written here */
2565  char **pzErrmsg       /* Error msg written here */
2566);
2567SQLITE_API void sqlite3_free_table(char **result);
2568
2569/*
2570** CAPI3REF: Formatted String Printing Functions
2571**
2572** These routines are work-alikes of the "printf()" family of functions
2573** from the standard C library.
2574**
2575** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2576** results into memory obtained from [sqlite3_malloc()].
2577** The strings returned by these two routines should be
2578** released by [sqlite3_free()].  ^Both routines return a
2579** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2580** memory to hold the resulting string.
2581**
2582** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2583** the standard C library.  The result is written into the
2584** buffer supplied as the second parameter whose size is given by
2585** the first parameter. Note that the order of the
2586** first two parameters is reversed from snprintf().)^  This is an
2587** historical accident that cannot be fixed without breaking
2588** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2589** returns a pointer to its buffer instead of the number of
2590** characters actually written into the buffer.)^  We admit that
2591** the number of characters written would be a more useful return
2592** value but we cannot change the implementation of sqlite3_snprintf()
2593** now without breaking compatibility.
2594**
2595** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2596** guarantees that the buffer is always zero-terminated.  ^The first
2597** parameter "n" is the total size of the buffer, including space for
2598** the zero terminator.  So the longest string that can be completely
2599** written will be n-1 characters.
2600**
2601** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2602**
2603** These routines all implement some additional formatting
2604** options that are useful for constructing SQL statements.
2605** All of the usual printf() formatting options apply.  In addition, there
2606** is are "%q", "%Q", and "%z" options.
2607**
2608** ^(The %q option works like %s in that it substitutes a nul-terminated
2609** string from the argument list.  But %q also doubles every '\'' character.
2610** %q is designed for use inside a string literal.)^  By doubling each '\''
2611** character it escapes that character and allows it to be inserted into
2612** the string.
2613**
2614** For example, assume the string variable zText contains text as follows:
2615**
2616** <blockquote><pre>
2617**  char *zText = "It's a happy day!";
2618** </pre></blockquote>
2619**
2620** One can use this text in an SQL statement as follows:
2621**
2622** <blockquote><pre>
2623**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2624**  sqlite3_exec(db, zSQL, 0, 0, 0);
2625**  sqlite3_free(zSQL);
2626** </pre></blockquote>
2627**
2628** Because the %q format string is used, the '\'' character in zText
2629** is escaped and the SQL generated is as follows:
2630**
2631** <blockquote><pre>
2632**  INSERT INTO table1 VALUES('It''s a happy day!')
2633** </pre></blockquote>
2634**
2635** This is correct.  Had we used %s instead of %q, the generated SQL
2636** would have looked like this:
2637**
2638** <blockquote><pre>
2639**  INSERT INTO table1 VALUES('It's a happy day!');
2640** </pre></blockquote>
2641**
2642** This second example is an SQL syntax error.  As a general rule you should
2643** always use %q instead of %s when inserting text into a string literal.
2644**
2645** ^(The %Q option works like %q except it also adds single quotes around
2646** the outside of the total string.  Additionally, if the parameter in the
2647** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2648** single quotes).)^  So, for example, one could say:
2649**
2650** <blockquote><pre>
2651**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2652**  sqlite3_exec(db, zSQL, 0, 0, 0);
2653**  sqlite3_free(zSQL);
2654** </pre></blockquote>
2655**
2656** The code above will render a correct SQL statement in the zSQL
2657** variable even if the zText variable is a NULL pointer.
2658**
2659** ^(The "%z" formatting option works like "%s" but with the
2660** addition that after the string has been read and copied into
2661** the result, [sqlite3_free()] is called on the input string.)^
2662*/
2663SQLITE_API char *sqlite3_mprintf(const char*,...);
2664SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2665SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2666SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2667
2668/*
2669** CAPI3REF: Memory Allocation Subsystem
2670**
2671** The SQLite core uses these three routines for all of its own
2672** internal memory allocation needs. "Core" in the previous sentence
2673** does not include operating-system specific VFS implementation.  The
2674** Windows VFS uses native malloc() and free() for some operations.
2675**
2676** ^The sqlite3_malloc() routine returns a pointer to a block
2677** of memory at least N bytes in length, where N is the parameter.
2678** ^If sqlite3_malloc() is unable to obtain sufficient free
2679** memory, it returns a NULL pointer.  ^If the parameter N to
2680** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2681** a NULL pointer.
2682**
2683** ^Calling sqlite3_free() with a pointer previously returned
2684** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2685** that it might be reused.  ^The sqlite3_free() routine is
2686** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2687** to sqlite3_free() is harmless.  After being freed, memory
2688** should neither be read nor written.  Even reading previously freed
2689** memory might result in a segmentation fault or other severe error.
2690** Memory corruption, a segmentation fault, or other severe error
2691** might result if sqlite3_free() is called with a non-NULL pointer that
2692** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2693**
2694** ^(The sqlite3_realloc() interface attempts to resize a
2695** prior memory allocation to be at least N bytes, where N is the
2696** second parameter.  The memory allocation to be resized is the first
2697** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2698** is a NULL pointer then its behavior is identical to calling
2699** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2700** ^If the second parameter to sqlite3_realloc() is zero or
2701** negative then the behavior is exactly the same as calling
2702** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2703** ^sqlite3_realloc() returns a pointer to a memory allocation
2704** of at least N bytes in size or NULL if sufficient memory is unavailable.
2705** ^If M is the size of the prior allocation, then min(N,M) bytes
2706** of the prior allocation are copied into the beginning of buffer returned
2707** by sqlite3_realloc() and the prior allocation is freed.
2708** ^If sqlite3_realloc() returns NULL, then the prior allocation
2709** is not freed.
2710**
2711** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2712** is always aligned to at least an 8 byte boundary, or to a
2713** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2714** option is used.
2715**
2716** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2717** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2718** implementation of these routines to be omitted.  That capability
2719** is no longer provided.  Only built-in memory allocators can be used.
2720**
2721** The Windows OS interface layer calls
2722** the system malloc() and free() directly when converting
2723** filenames between the UTF-8 encoding used by SQLite
2724** and whatever filename encoding is used by the particular Windows
2725** installation.  Memory allocation errors are detected, but
2726** they are reported back as [SQLITE_CANTOPEN] or
2727** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2728**
2729** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2730** must be either NULL or else pointers obtained from a prior
2731** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2732** not yet been released.
2733**
2734** The application must not read or write any part of
2735** a block of memory after it has been released using
2736** [sqlite3_free()] or [sqlite3_realloc()].
2737*/
2738SQLITE_API void *sqlite3_malloc(int);
2739SQLITE_API void *sqlite3_realloc(void*, int);
2740SQLITE_API void sqlite3_free(void*);
2741
2742/*
2743** CAPI3REF: Memory Allocator Statistics
2744**
2745** SQLite provides these two interfaces for reporting on the status
2746** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2747** routines, which form the built-in memory allocation subsystem.
2748**
2749** ^The [sqlite3_memory_used()] routine returns the number of bytes
2750** of memory currently outstanding (malloced but not freed).
2751** ^The [sqlite3_memory_highwater()] routine returns the maximum
2752** value of [sqlite3_memory_used()] since the high-water mark
2753** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2754** [sqlite3_memory_highwater()] include any overhead
2755** added by SQLite in its implementation of [sqlite3_malloc()],
2756** but not overhead added by the any underlying system library
2757** routines that [sqlite3_malloc()] may call.
2758**
2759** ^The memory high-water mark is reset to the current value of
2760** [sqlite3_memory_used()] if and only if the parameter to
2761** [sqlite3_memory_highwater()] is true.  ^The value returned
2762** by [sqlite3_memory_highwater(1)] is the high-water mark
2763** prior to the reset.
2764*/
2765SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2766SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2767
2768/*
2769** CAPI3REF: Pseudo-Random Number Generator
2770**
2771** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2772** select random [ROWID | ROWIDs] when inserting new records into a table that
2773** already uses the largest possible [ROWID].  The PRNG is also used for
2774** the build-in random() and randomblob() SQL functions.  This interface allows
2775** applications to access the same PRNG for other purposes.
2776**
2777** ^A call to this routine stores N bytes of randomness into buffer P.
2778**
2779** ^The first time this routine is invoked (either internally or by
2780** the application) the PRNG is seeded using randomness obtained
2781** from the xRandomness method of the default [sqlite3_vfs] object.
2782** ^On all subsequent invocations, the pseudo-randomness is generated
2783** internally and without recourse to the [sqlite3_vfs] xRandomness
2784** method.
2785*/
2786SQLITE_API void sqlite3_randomness(int N, void *P);
2787
2788/*
2789** CAPI3REF: Compile-Time Authorization Callbacks
2790**
2791** ^This routine registers an authorizer callback with a particular
2792** [database connection], supplied in the first argument.
2793** ^The authorizer callback is invoked as SQL statements are being compiled
2794** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2795** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2796** points during the compilation process, as logic is being created
2797** to perform various actions, the authorizer callback is invoked to
2798** see if those actions are allowed.  ^The authorizer callback should
2799** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2800** specific action but allow the SQL statement to continue to be
2801** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2802** rejected with an error.  ^If the authorizer callback returns
2803** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2804** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2805** the authorizer will fail with an error message.
2806**
2807** When the callback returns [SQLITE_OK], that means the operation
2808** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2809** [sqlite3_prepare_v2()] or equivalent call that triggered the
2810** authorizer will fail with an error message explaining that
2811** access is denied.
2812**
2813** ^The first parameter to the authorizer callback is a copy of the third
2814** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2815** to the callback is an integer [SQLITE_COPY | action code] that specifies
2816** the particular action to be authorized. ^The third through sixth parameters
2817** to the callback are zero-terminated strings that contain additional
2818** details about the action to be authorized.
2819**
2820** ^If the action code is [SQLITE_READ]
2821** and the callback returns [SQLITE_IGNORE] then the
2822** [prepared statement] statement is constructed to substitute
2823** a NULL value in place of the table column that would have
2824** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2825** return can be used to deny an untrusted user access to individual
2826** columns of a table.
2827** ^If the action code is [SQLITE_DELETE] and the callback returns
2828** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2829** [truncate optimization] is disabled and all rows are deleted individually.
2830**
2831** An authorizer is used when [sqlite3_prepare | preparing]
2832** SQL statements from an untrusted source, to ensure that the SQL statements
2833** do not try to access data they are not allowed to see, or that they do not
2834** try to execute malicious statements that damage the database.  For
2835** example, an application may allow a user to enter arbitrary
2836** SQL queries for evaluation by a database.  But the application does
2837** not want the user to be able to make arbitrary changes to the
2838** database.  An authorizer could then be put in place while the
2839** user-entered SQL is being [sqlite3_prepare | prepared] that
2840** disallows everything except [SELECT] statements.
2841**
2842** Applications that need to process SQL from untrusted sources
2843** might also consider lowering resource limits using [sqlite3_limit()]
2844** and limiting database size using the [max_page_count] [PRAGMA]
2845** in addition to using an authorizer.
2846**
2847** ^(Only a single authorizer can be in place on a database connection
2848** at a time.  Each call to sqlite3_set_authorizer overrides the
2849** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2850** The authorizer is disabled by default.
2851**
2852** The authorizer callback must not do anything that will modify
2853** the database connection that invoked the authorizer callback.
2854** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2855** database connections for the meaning of "modify" in this paragraph.
2856**
2857** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2858** statement might be re-prepared during [sqlite3_step()] due to a
2859** schema change.  Hence, the application should ensure that the
2860** correct authorizer callback remains in place during the [sqlite3_step()].
2861**
2862** ^Note that the authorizer callback is invoked only during
2863** [sqlite3_prepare()] or its variants.  Authorization is not
2864** performed during statement evaluation in [sqlite3_step()], unless
2865** as stated in the previous paragraph, sqlite3_step() invokes
2866** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2867*/
2868SQLITE_API int sqlite3_set_authorizer(
2869  sqlite3*,
2870  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2871  void *pUserData
2872);
2873
2874/*
2875** CAPI3REF: Authorizer Return Codes
2876**
2877** The [sqlite3_set_authorizer | authorizer callback function] must
2878** return either [SQLITE_OK] or one of these two constants in order
2879** to signal SQLite whether or not the action is permitted.  See the
2880** [sqlite3_set_authorizer | authorizer documentation] for additional
2881** information.
2882**
2883** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
2884** from the [sqlite3_vtab_on_conflict()] interface.
2885*/
2886#define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2887#define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2888
2889/*
2890** CAPI3REF: Authorizer Action Codes
2891**
2892** The [sqlite3_set_authorizer()] interface registers a callback function
2893** that is invoked to authorize certain SQL statement actions.  The
2894** second parameter to the callback is an integer code that specifies
2895** what action is being authorized.  These are the integer action codes that
2896** the authorizer callback may be passed.
2897**
2898** These action code values signify what kind of operation is to be
2899** authorized.  The 3rd and 4th parameters to the authorization
2900** callback function will be parameters or NULL depending on which of these
2901** codes is used as the second parameter.  ^(The 5th parameter to the
2902** authorizer callback is the name of the database ("main", "temp",
2903** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2904** is the name of the inner-most trigger or view that is responsible for
2905** the access attempt or NULL if this access attempt is directly from
2906** top-level SQL code.
2907*/
2908/******************************************* 3rd ************ 4th ***********/
2909#define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2910#define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2911#define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2912#define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2913#define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2914#define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2915#define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2916#define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2917#define SQLITE_DELETE                9   /* Table Name      NULL            */
2918#define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2919#define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2920#define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2921#define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2922#define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2923#define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2924#define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2925#define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2926#define SQLITE_INSERT               18   /* Table Name      NULL            */
2927#define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2928#define SQLITE_READ                 20   /* Table Name      Column Name     */
2929#define SQLITE_SELECT               21   /* NULL            NULL            */
2930#define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2931#define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2932#define SQLITE_ATTACH               24   /* Filename        NULL            */
2933#define SQLITE_DETACH               25   /* Database Name   NULL            */
2934#define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2935#define SQLITE_REINDEX              27   /* Index Name      NULL            */
2936#define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2937#define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2938#define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2939#define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2940#define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2941#define SQLITE_COPY                  0   /* No longer used */
2942
2943/*
2944** CAPI3REF: Tracing And Profiling Functions
2945**
2946** These routines register callback functions that can be used for
2947** tracing and profiling the execution of SQL statements.
2948**
2949** ^The callback function registered by sqlite3_trace() is invoked at
2950** various times when an SQL statement is being run by [sqlite3_step()].
2951** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2952** SQL statement text as the statement first begins executing.
2953** ^(Additional sqlite3_trace() callbacks might occur
2954** as each triggered subprogram is entered.  The callbacks for triggers
2955** contain a UTF-8 SQL comment that identifies the trigger.)^
2956**
2957** ^The callback function registered by sqlite3_profile() is invoked
2958** as each SQL statement finishes.  ^The profile callback contains
2959** the original statement text and an estimate of wall-clock time
2960** of how long that statement took to run.  ^The profile callback
2961** time is in units of nanoseconds, however the current implementation
2962** is only capable of millisecond resolution so the six least significant
2963** digits in the time are meaningless.  Future versions of SQLite
2964** might provide greater resolution on the profiler callback.  The
2965** sqlite3_profile() function is considered experimental and is
2966** subject to change in future versions of SQLite.
2967*/
2968SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2969SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2970   void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2971
2972/*
2973** CAPI3REF: Query Progress Callbacks
2974**
2975** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2976** function X to be invoked periodically during long running calls to
2977** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2978** database connection D.  An example use for this
2979** interface is to keep a GUI updated during a large query.
2980**
2981** ^The parameter P is passed through as the only parameter to the
2982** callback function X.  ^The parameter N is the number of
2983** [virtual machine instructions] that are evaluated between successive
2984** invocations of the callback X.
2985**
2986** ^Only a single progress handler may be defined at one time per
2987** [database connection]; setting a new progress handler cancels the
2988** old one.  ^Setting parameter X to NULL disables the progress handler.
2989** ^The progress handler is also disabled by setting N to a value less
2990** than 1.
2991**
2992** ^If the progress callback returns non-zero, the operation is
2993** interrupted.  This feature can be used to implement a
2994** "Cancel" button on a GUI progress dialog box.
2995**
2996** The progress handler callback must not do anything that will modify
2997** the database connection that invoked the progress handler.
2998** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2999** database connections for the meaning of "modify" in this paragraph.
3000**
3001*/
3002SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3003
3004/*
3005** CAPI3REF: Opening A New Database Connection
3006**
3007** ^These routines open an SQLite database file as specified by the
3008** filename argument. ^The filename argument is interpreted as UTF-8 for
3009** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3010** order for sqlite3_open16(). ^(A [database connection] handle is usually
3011** returned in *ppDb, even if an error occurs.  The only exception is that
3012** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3013** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3014** object.)^ ^(If the database is opened (and/or created) successfully, then
3015** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3016** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3017** an English language description of the error following a failure of any
3018** of the sqlite3_open() routines.
3019**
3020** ^The default encoding for the database will be UTF-8 if
3021** sqlite3_open() or sqlite3_open_v2() is called and
3022** UTF-16 in the native byte order if sqlite3_open16() is used.
3023**
3024** Whether or not an error occurs when it is opened, resources
3025** associated with the [database connection] handle should be released by
3026** passing it to [sqlite3_close()] when it is no longer required.
3027**
3028** The sqlite3_open_v2() interface works like sqlite3_open()
3029** except that it accepts two additional parameters for additional control
3030** over the new database connection.  ^(The flags parameter to
3031** sqlite3_open_v2() can take one of
3032** the following three values, optionally combined with the
3033** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3034** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3035**
3036** <dl>
3037** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3038** <dd>The database is opened in read-only mode.  If the database does not
3039** already exist, an error is returned.</dd>)^
3040**
3041** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3042** <dd>The database is opened for reading and writing if possible, or reading
3043** only if the file is write protected by the operating system.  In either
3044** case the database must already exist, otherwise an error is returned.</dd>)^
3045**
3046** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3047** <dd>The database is opened for reading and writing, and is created if
3048** it does not already exist. This is the behavior that is always used for
3049** sqlite3_open() and sqlite3_open16().</dd>)^
3050** </dl>
3051**
3052** If the 3rd parameter to sqlite3_open_v2() is not one of the
3053** combinations shown above optionally combined with other
3054** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3055** then the behavior is undefined.
3056**
3057** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3058** opens in the multi-thread [threading mode] as long as the single-thread
3059** mode has not been set at compile-time or start-time.  ^If the
3060** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3061** in the serialized [threading mode] unless single-thread was
3062** previously selected at compile-time or start-time.
3063** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3064** eligible to use [shared cache mode], regardless of whether or not shared
3065** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3066** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3067** participate in [shared cache mode] even if it is enabled.
3068**
3069** ^The fourth parameter to sqlite3_open_v2() is the name of the
3070** [sqlite3_vfs] object that defines the operating system interface that
3071** the new database connection should use.  ^If the fourth parameter is
3072** a NULL pointer then the default [sqlite3_vfs] object is used.
3073**
3074** ^If the filename is ":memory:", then a private, temporary in-memory database
3075** is created for the connection.  ^This in-memory database will vanish when
3076** the database connection is closed.  Future versions of SQLite might
3077** make use of additional special filenames that begin with the ":" character.
3078** It is recommended that when a database filename actually does begin with
3079** a ":" character you should prefix the filename with a pathname such as
3080** "./" to avoid ambiguity.
3081**
3082** ^If the filename is an empty string, then a private, temporary
3083** on-disk database will be created.  ^This private database will be
3084** automatically deleted as soon as the database connection is closed.
3085**
3086** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3087**
3088** ^If [URI filename] interpretation is enabled, and the filename argument
3089** begins with "file:", then the filename is interpreted as a URI. ^URI
3090** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3091** set in the fourth argument to sqlite3_open_v2(), or if it has
3092** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3093** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3094** As of SQLite version 3.7.7, URI filename interpretation is turned off
3095** by default, but future releases of SQLite might enable URI filename
3096** interpretation by default.  See "[URI filenames]" for additional
3097** information.
3098**
3099** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3100** authority, then it must be either an empty string or the string
3101** "localhost". ^If the authority is not an empty string or "localhost", an
3102** error is returned to the caller. ^The fragment component of a URI, if
3103** present, is ignored.
3104**
3105** ^SQLite uses the path component of the URI as the name of the disk file
3106** which contains the database. ^If the path begins with a '/' character,
3107** then it is interpreted as an absolute path. ^If the path does not begin
3108** with a '/' (meaning that the authority section is omitted from the URI)
3109** then the path is interpreted as a relative path.
3110** ^On windows, the first component of an absolute path
3111** is a drive specification (e.g. "C:").
3112**
3113** [[core URI query parameters]]
3114** The query component of a URI may contain parameters that are interpreted
3115** either by SQLite itself, or by a [VFS | custom VFS implementation].
3116** SQLite interprets the following three query parameters:
3117**
3118** <ul>
3119**   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3120**     a VFS object that provides the operating system interface that should
3121**     be used to access the database file on disk. ^If this option is set to
3122**     an empty string the default VFS object is used. ^Specifying an unknown
3123**     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3124**     present, then the VFS specified by the option takes precedence over
3125**     the value passed as the fourth parameter to sqlite3_open_v2().
3126**
3127**   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw" or
3128**     "rwc". Attempting to set it to any other value is an error)^.
3129**     ^If "ro" is specified, then the database is opened for read-only
3130**     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3131**     third argument to sqlite3_prepare_v2(). ^If the mode option is set to
3132**     "rw", then the database is opened for read-write (but not create)
3133**     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3134**     been set. ^Value "rwc" is equivalent to setting both
3135**     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If sqlite3_open_v2() is
3136**     used, it is an error to specify a value for the mode parameter that is
3137**     less restrictive than that specified by the flags passed as the third
3138**     parameter.
3139**
3140**   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3141**     "private". ^Setting it to "shared" is equivalent to setting the
3142**     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3143**     sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3144**     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3145**     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3146**     a URI filename, its value overrides any behaviour requested by setting
3147**     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3148** </ul>
3149**
3150** ^Specifying an unknown parameter in the query component of a URI is not an
3151** error.  Future versions of SQLite might understand additional query
3152** parameters.  See "[query parameters with special meaning to SQLite]" for
3153** additional information.
3154**
3155** [[URI filename examples]] <h3>URI filename examples</h3>
3156**
3157** <table border="1" align=center cellpadding=5>
3158** <tr><th> URI filenames <th> Results
3159** <tr><td> file:data.db <td>
3160**          Open the file "data.db" in the current directory.
3161** <tr><td> file:/home/fred/data.db<br>
3162**          file:///home/fred/data.db <br>
3163**          file://localhost/home/fred/data.db <br> <td>
3164**          Open the database file "/home/fred/data.db".
3165** <tr><td> file://darkstar/home/fred/data.db <td>
3166**          An error. "darkstar" is not a recognized authority.
3167** <tr><td style="white-space:nowrap">
3168**          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3169**     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3170**          C:. Note that the %20 escaping in this example is not strictly
3171**          necessary - space characters can be used literally
3172**          in URI filenames.
3173** <tr><td> file:data.db?mode=ro&cache=private <td>
3174**          Open file "data.db" in the current directory for read-only access.
3175**          Regardless of whether or not shared-cache mode is enabled by
3176**          default, use a private cache.
3177** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3178**          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3179** <tr><td> file:data.db?mode=readonly <td>
3180**          An error. "readonly" is not a valid option for the "mode" parameter.
3181** </table>
3182**
3183** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3184** query components of a URI. A hexadecimal escape sequence consists of a
3185** percent sign - "%" - followed by exactly two hexadecimal digits
3186** specifying an octet value. ^Before the path or query components of a
3187** URI filename are interpreted, they are encoded using UTF-8 and all
3188** hexadecimal escape sequences replaced by a single byte containing the
3189** corresponding octet. If this process generates an invalid UTF-8 encoding,
3190** the results are undefined.
3191**
3192** <b>Note to Windows users:</b>  The encoding used for the filename argument
3193** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3194** codepage is currently defined.  Filenames containing international
3195** characters must be converted to UTF-8 prior to passing them into
3196** sqlite3_open() or sqlite3_open_v2().
3197*/
3198SQLITE_API int sqlite3_open(
3199  const char *filename,   /* Database filename (UTF-8) */
3200  sqlite3 **ppDb          /* OUT: SQLite db handle */
3201);
3202SQLITE_API int sqlite3_open16(
3203  const void *filename,   /* Database filename (UTF-16) */
3204  sqlite3 **ppDb          /* OUT: SQLite db handle */
3205);
3206SQLITE_API int sqlite3_open_v2(
3207  const char *filename,   /* Database filename (UTF-8) */
3208  sqlite3 **ppDb,         /* OUT: SQLite db handle */
3209  int flags,              /* Flags */
3210  const char *zVfs        /* Name of VFS module to use */
3211);
3212
3213/*
3214** CAPI3REF: Obtain Values For URI Parameters
3215**
3216** These are utility routines, useful to VFS implementations, that check
3217** to see if a database file was a URI that contained a specific query
3218** parameter, and if so obtains the value of that query parameter.
3219**
3220** If F is the database filename pointer passed into the xOpen() method of
3221** a VFS implementation when the flags parameter to xOpen() has one or
3222** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3223** P is the name of the query parameter, then
3224** sqlite3_uri_parameter(F,P) returns the value of the P
3225** parameter if it exists or a NULL pointer if P does not appear as a
3226** query parameter on F.  If P is a query parameter of F
3227** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3228** a pointer to an empty string.
3229**
3230** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3231** parameter and returns true (1) or false (0) according to the value
3232** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3233** value of query parameter P is one of "yes", "true", or "on" in any
3234** case or if the value begins with a non-zero number.  The
3235** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3236** query parameter P is one of "no", "false", or "off" in any case or
3237** if the value begins with a numeric zero.  If P is not a query
3238** parameter on F or if the value of P is does not match any of the
3239** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3240**
3241** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3242** 64-bit signed integer and returns that integer, or D if P does not
3243** exist.  If the value of P is something other than an integer, then
3244** zero is returned.
3245**
3246** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3247** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3248** is not a database file pathname pointer that SQLite passed into the xOpen
3249** VFS method, then the behavior of this routine is undefined and probably
3250** undesirable.
3251*/
3252SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3253SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3254SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3255
3256
3257/*
3258** CAPI3REF: Error Codes And Messages
3259**
3260** ^The sqlite3_errcode() interface returns the numeric [result code] or
3261** [extended result code] for the most recent failed sqlite3_* API call
3262** associated with a [database connection]. If a prior API call failed
3263** but the most recent API call succeeded, the return value from
3264** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3265** interface is the same except that it always returns the
3266** [extended result code] even when extended result codes are
3267** disabled.
3268**
3269** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3270** text that describes the error, as either UTF-8 or UTF-16 respectively.
3271** ^(Memory to hold the error message string is managed internally.
3272** The application does not need to worry about freeing the result.
3273** However, the error string might be overwritten or deallocated by
3274** subsequent calls to other SQLite interface functions.)^
3275**
3276** When the serialized [threading mode] is in use, it might be the
3277** case that a second error occurs on a separate thread in between
3278** the time of the first error and the call to these interfaces.
3279** When that happens, the second error will be reported since these
3280** interfaces always report the most recent result.  To avoid
3281** this, each thread can obtain exclusive use of the [database connection] D
3282** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3283** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3284** all calls to the interfaces listed here are completed.
3285**
3286** If an interface fails with SQLITE_MISUSE, that means the interface
3287** was invoked incorrectly by the application.  In that case, the
3288** error code and message may or may not be set.
3289*/
3290SQLITE_API int sqlite3_errcode(sqlite3 *db);
3291SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3292SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3293SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3294
3295/*
3296** CAPI3REF: SQL Statement Object
3297** KEYWORDS: {prepared statement} {prepared statements}
3298**
3299** An instance of this object represents a single SQL statement.
3300** This object is variously known as a "prepared statement" or a
3301** "compiled SQL statement" or simply as a "statement".
3302**
3303** The life of a statement object goes something like this:
3304**
3305** <ol>
3306** <li> Create the object using [sqlite3_prepare_v2()] or a related
3307**      function.
3308** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3309**      interfaces.
3310** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3311** <li> Reset the statement using [sqlite3_reset()] then go back
3312**      to step 2.  Do this zero or more times.
3313** <li> Destroy the object using [sqlite3_finalize()].
3314** </ol>
3315**
3316** Refer to documentation on individual methods above for additional
3317** information.
3318*/
3319typedef struct sqlite3_stmt sqlite3_stmt;
3320
3321/*
3322** CAPI3REF: Run-time Limits
3323**
3324** ^(This interface allows the size of various constructs to be limited
3325** on a connection by connection basis.  The first parameter is the
3326** [database connection] whose limit is to be set or queried.  The
3327** second parameter is one of the [limit categories] that define a
3328** class of constructs to be size limited.  The third parameter is the
3329** new limit for that construct.)^
3330**
3331** ^If the new limit is a negative number, the limit is unchanged.
3332** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3333** [limits | hard upper bound]
3334** set at compile-time by a C preprocessor macro called
3335** [limits | SQLITE_MAX_<i>NAME</i>].
3336** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3337** ^Attempts to increase a limit above its hard upper bound are
3338** silently truncated to the hard upper bound.
3339**
3340** ^Regardless of whether or not the limit was changed, the
3341** [sqlite3_limit()] interface returns the prior value of the limit.
3342** ^Hence, to find the current value of a limit without changing it,
3343** simply invoke this interface with the third parameter set to -1.
3344**
3345** Run-time limits are intended for use in applications that manage
3346** both their own internal database and also databases that are controlled
3347** by untrusted external sources.  An example application might be a
3348** web browser that has its own databases for storing history and
3349** separate databases controlled by JavaScript applications downloaded
3350** off the Internet.  The internal databases can be given the
3351** large, default limits.  Databases managed by external sources can
3352** be given much smaller limits designed to prevent a denial of service
3353** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3354** interface to further control untrusted SQL.  The size of the database
3355** created by an untrusted script can be contained using the
3356** [max_page_count] [PRAGMA].
3357**
3358** New run-time limit categories may be added in future releases.
3359*/
3360SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3361
3362/*
3363** CAPI3REF: Run-Time Limit Categories
3364** KEYWORDS: {limit category} {*limit categories}
3365**
3366** These constants define various performance limits
3367** that can be lowered at run-time using [sqlite3_limit()].
3368** The synopsis of the meanings of the various limits is shown below.
3369** Additional information is available at [limits | Limits in SQLite].
3370**
3371** <dl>
3372** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3373** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3374**
3375** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3376** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3377**
3378** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3379** <dd>The maximum number of columns in a table definition or in the
3380** result set of a [SELECT] or the maximum number of columns in an index
3381** or in an ORDER BY or GROUP BY clause.</dd>)^
3382**
3383** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3384** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3385**
3386** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3387** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3388**
3389** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3390** <dd>The maximum number of instructions in a virtual machine program
3391** used to implement an SQL statement.  This limit is not currently
3392** enforced, though that might be added in some future release of
3393** SQLite.</dd>)^
3394**
3395** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3396** <dd>The maximum number of arguments on a function.</dd>)^
3397**
3398** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3399** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3400**
3401** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3402** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3403** <dd>The maximum length of the pattern argument to the [LIKE] or
3404** [GLOB] operators.</dd>)^
3405**
3406** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3407** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3408** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3409**
3410** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3411** <dd>The maximum depth of recursion for triggers.</dd>)^
3412** </dl>
3413*/
3414#define SQLITE_LIMIT_LENGTH                    0
3415#define SQLITE_LIMIT_SQL_LENGTH                1
3416#define SQLITE_LIMIT_COLUMN                    2
3417#define SQLITE_LIMIT_EXPR_DEPTH                3
3418#define SQLITE_LIMIT_COMPOUND_SELECT           4
3419#define SQLITE_LIMIT_VDBE_OP                   5
3420#define SQLITE_LIMIT_FUNCTION_ARG              6
3421#define SQLITE_LIMIT_ATTACHED                  7
3422#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3423#define SQLITE_LIMIT_VARIABLE_NUMBER           9
3424#define SQLITE_LIMIT_TRIGGER_DEPTH            10
3425
3426/*
3427** CAPI3REF: Compiling An SQL Statement
3428** KEYWORDS: {SQL statement compiler}
3429**
3430** To execute an SQL query, it must first be compiled into a byte-code
3431** program using one of these routines.
3432**
3433** The first argument, "db", is a [database connection] obtained from a
3434** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3435** [sqlite3_open16()].  The database connection must not have been closed.
3436**
3437** The second argument, "zSql", is the statement to be compiled, encoded
3438** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3439** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3440** use UTF-16.
3441**
3442** ^If the nByte argument is less than zero, then zSql is read up to the
3443** first zero terminator. ^If nByte is non-negative, then it is the maximum
3444** number of  bytes read from zSql.  ^When nByte is non-negative, the
3445** zSql string ends at either the first '\000' or '\u0000' character or
3446** the nByte-th byte, whichever comes first. If the caller knows
3447** that the supplied string is nul-terminated, then there is a small
3448** performance advantage to be gained by passing an nByte parameter that
3449** is equal to the number of bytes in the input string <i>including</i>
3450** the nul-terminator bytes as this saves SQLite from having to
3451** make a copy of the input string.
3452**
3453** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3454** past the end of the first SQL statement in zSql.  These routines only
3455** compile the first statement in zSql, so *pzTail is left pointing to
3456** what remains uncompiled.
3457**
3458** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3459** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3460** to NULL.  ^If the input text contains no SQL (if the input is an empty
3461** string or a comment) then *ppStmt is set to NULL.
3462** The calling procedure is responsible for deleting the compiled
3463** SQL statement using [sqlite3_finalize()] after it has finished with it.
3464** ppStmt may not be NULL.
3465**
3466** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3467** otherwise an [error code] is returned.
3468**
3469** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3470** recommended for all new programs. The two older interfaces are retained
3471** for backwards compatibility, but their use is discouraged.
3472** ^In the "v2" interfaces, the prepared statement
3473** that is returned (the [sqlite3_stmt] object) contains a copy of the
3474** original SQL text. This causes the [sqlite3_step()] interface to
3475** behave differently in three ways:
3476**
3477** <ol>
3478** <li>
3479** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3480** always used to do, [sqlite3_step()] will automatically recompile the SQL
3481** statement and try to run it again.
3482** </li>
3483**
3484** <li>
3485** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3486** [error codes] or [extended error codes].  ^The legacy behavior was that
3487** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3488** and the application would have to make a second call to [sqlite3_reset()]
3489** in order to find the underlying cause of the problem. With the "v2" prepare
3490** interfaces, the underlying reason for the error is returned immediately.
3491** </li>
3492**
3493** <li>
3494** ^If the specific value bound to [parameter | host parameter] in the
3495** WHERE clause might influence the choice of query plan for a statement,
3496** then the statement will be automatically recompiled, as if there had been
3497** a schema change, on the first  [sqlite3_step()] call following any change
3498** to the [sqlite3_bind_text | bindings] of that [parameter].
3499** ^The specific value of WHERE-clause [parameter] might influence the
3500** choice of query plan if the parameter is the left-hand side of a [LIKE]
3501** or [GLOB] operator or if the parameter is compared to an indexed column
3502** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3503** the
3504** </li>
3505** </ol>
3506*/
3507SQLITE_API int sqlite3_prepare(
3508  sqlite3 *db,            /* Database handle */
3509  const char *zSql,       /* SQL statement, UTF-8 encoded */
3510  int nByte,              /* Maximum length of zSql in bytes. */
3511  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3512  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3513);
3514SQLITE_API int sqlite3_prepare_v2(
3515  sqlite3 *db,            /* Database handle */
3516  const char *zSql,       /* SQL statement, UTF-8 encoded */
3517  int nByte,              /* Maximum length of zSql in bytes. */
3518  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3519  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3520);
3521SQLITE_API int sqlite3_prepare16(
3522  sqlite3 *db,            /* Database handle */
3523  const void *zSql,       /* SQL statement, UTF-16 encoded */
3524  int nByte,              /* Maximum length of zSql in bytes. */
3525  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3526  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3527);
3528SQLITE_API int sqlite3_prepare16_v2(
3529  sqlite3 *db,            /* Database handle */
3530  const void *zSql,       /* SQL statement, UTF-16 encoded */
3531  int nByte,              /* Maximum length of zSql in bytes. */
3532  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3533  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3534);
3535
3536/*
3537** CAPI3REF: Retrieving Statement SQL
3538**
3539** ^This interface can be used to retrieve a saved copy of the original
3540** SQL text used to create a [prepared statement] if that statement was
3541** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3542*/
3543SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3544
3545/*
3546** CAPI3REF: Determine If An SQL Statement Writes The Database
3547**
3548** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3549** and only if the [prepared statement] X makes no direct changes to
3550** the content of the database file.
3551**
3552** Note that [application-defined SQL functions] or
3553** [virtual tables] might change the database indirectly as a side effect.
3554** ^(For example, if an application defines a function "eval()" that
3555** calls [sqlite3_exec()], then the following SQL statement would
3556** change the database file through side-effects:
3557**
3558** <blockquote><pre>
3559**    SELECT eval('DELETE FROM t1') FROM t2;
3560** </pre></blockquote>
3561**
3562** But because the [SELECT] statement does not change the database file
3563** directly, sqlite3_stmt_readonly() would still return true.)^
3564**
3565** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3566** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3567** since the statements themselves do not actually modify the database but
3568** rather they control the timing of when other statements modify the
3569** database.  ^The [ATTACH] and [DETACH] statements also cause
3570** sqlite3_stmt_readonly() to return true since, while those statements
3571** change the configuration of a database connection, they do not make
3572** changes to the content of the database files on disk.
3573*/
3574SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3575
3576/*
3577** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3578**
3579** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3580** [prepared statement] S has been stepped at least once using
3581** [sqlite3_step(S)] but has not run to completion and/or has not
3582** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3583** interface returns false if S is a NULL pointer.  If S is not a
3584** NULL pointer and is not a pointer to a valid [prepared statement]
3585** object, then the behavior is undefined and probably undesirable.
3586**
3587** This interface can be used in combination [sqlite3_next_stmt()]
3588** to locate all prepared statements associated with a database
3589** connection that are in need of being reset.  This can be used,
3590** for example, in diagnostic routines to search for prepared
3591** statements that are holding a transaction open.
3592*/
3593SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3594
3595/*
3596** CAPI3REF: Dynamically Typed Value Object
3597** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3598**
3599** SQLite uses the sqlite3_value object to represent all values
3600** that can be stored in a database table. SQLite uses dynamic typing
3601** for the values it stores.  ^Values stored in sqlite3_value objects
3602** can be integers, floating point values, strings, BLOBs, or NULL.
3603**
3604** An sqlite3_value object may be either "protected" or "unprotected".
3605** Some interfaces require a protected sqlite3_value.  Other interfaces
3606** will accept either a protected or an unprotected sqlite3_value.
3607** Every interface that accepts sqlite3_value arguments specifies
3608** whether or not it requires a protected sqlite3_value.
3609**
3610** The terms "protected" and "unprotected" refer to whether or not
3611** a mutex is held.  An internal mutex is held for a protected
3612** sqlite3_value object but no mutex is held for an unprotected
3613** sqlite3_value object.  If SQLite is compiled to be single-threaded
3614** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3615** or if SQLite is run in one of reduced mutex modes
3616** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3617** then there is no distinction between protected and unprotected
3618** sqlite3_value objects and they can be used interchangeably.  However,
3619** for maximum code portability it is recommended that applications
3620** still make the distinction between protected and unprotected
3621** sqlite3_value objects even when not strictly required.
3622**
3623** ^The sqlite3_value objects that are passed as parameters into the
3624** implementation of [application-defined SQL functions] are protected.
3625** ^The sqlite3_value object returned by
3626** [sqlite3_column_value()] is unprotected.
3627** Unprotected sqlite3_value objects may only be used with
3628** [sqlite3_result_value()] and [sqlite3_bind_value()].
3629** The [sqlite3_value_blob | sqlite3_value_type()] family of
3630** interfaces require protected sqlite3_value objects.
3631*/
3632typedef struct Mem sqlite3_value;
3633
3634/*
3635** CAPI3REF: SQL Function Context Object
3636**
3637** The context in which an SQL function executes is stored in an
3638** sqlite3_context object.  ^A pointer to an sqlite3_context object
3639** is always first parameter to [application-defined SQL functions].
3640** The application-defined SQL function implementation will pass this
3641** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3642** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3643** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3644** and/or [sqlite3_set_auxdata()].
3645*/
3646typedef struct sqlite3_context sqlite3_context;
3647
3648/*
3649** CAPI3REF: Binding Values To Prepared Statements
3650** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3651** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3652**
3653** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3654** literals may be replaced by a [parameter] that matches one of following
3655** templates:
3656**
3657** <ul>
3658** <li>  ?
3659** <li>  ?NNN
3660** <li>  :VVV
3661** <li>  @VVV
3662** <li>  $VVV
3663** </ul>
3664**
3665** In the templates above, NNN represents an integer literal,
3666** and VVV represents an alphanumeric identifier.)^  ^The values of these
3667** parameters (also called "host parameter names" or "SQL parameters")
3668** can be set using the sqlite3_bind_*() routines defined here.
3669**
3670** ^The first argument to the sqlite3_bind_*() routines is always
3671** a pointer to the [sqlite3_stmt] object returned from
3672** [sqlite3_prepare_v2()] or its variants.
3673**
3674** ^The second argument is the index of the SQL parameter to be set.
3675** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3676** SQL parameter is used more than once, second and subsequent
3677** occurrences have the same index as the first occurrence.
3678** ^The index for named parameters can be looked up using the
3679** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3680** for "?NNN" parameters is the value of NNN.
3681** ^The NNN value must be between 1 and the [sqlite3_limit()]
3682** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3683**
3684** ^The third argument is the value to bind to the parameter.
3685**
3686** ^(In those routines that have a fourth argument, its value is the
3687** number of bytes in the parameter.  To be clear: the value is the
3688** number of <u>bytes</u> in the value, not the number of characters.)^
3689** ^If the fourth parameter is negative, the length of the string is
3690** the number of bytes up to the first zero terminator.
3691** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3692** or sqlite3_bind_text16() then that parameter must be the byte offset
3693** where the NUL terminator would occur assuming the string were NUL
3694** terminated.  If any NUL characters occur at byte offsets less than
3695** the value of the fourth parameter then the resulting string value will
3696** contain embedded NULs.  The result of expressions involving strings
3697** with embedded NULs is undefined.
3698**
3699** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3700** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3701** string after SQLite has finished with it.  ^The destructor is called
3702** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3703** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
3704** ^If the fifth argument is
3705** the special value [SQLITE_STATIC], then SQLite assumes that the
3706** information is in static, unmanaged space and does not need to be freed.
3707** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3708** SQLite makes its own private copy of the data immediately, before
3709** the sqlite3_bind_*() routine returns.
3710**
3711** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3712** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3713** (just an integer to hold its size) while it is being processed.
3714** Zeroblobs are intended to serve as placeholders for BLOBs whose
3715** content is later written using
3716** [sqlite3_blob_open | incremental BLOB I/O] routines.
3717** ^A negative value for the zeroblob results in a zero-length BLOB.
3718**
3719** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3720** for the [prepared statement] or with a prepared statement for which
3721** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3722** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3723** routine is passed a [prepared statement] that has been finalized, the
3724** result is undefined and probably harmful.
3725**
3726** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3727** ^Unbound parameters are interpreted as NULL.
3728**
3729** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3730** [error code] if anything goes wrong.
3731** ^[SQLITE_RANGE] is returned if the parameter
3732** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3733**
3734** See also: [sqlite3_bind_parameter_count()],
3735** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3736*/
3737SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3738SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3739SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3740SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3741SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3742SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3743SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3744SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3745SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3746
3747/*
3748** CAPI3REF: Number Of SQL Parameters
3749**
3750** ^This routine can be used to find the number of [SQL parameters]
3751** in a [prepared statement].  SQL parameters are tokens of the
3752** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3753** placeholders for values that are [sqlite3_bind_blob | bound]
3754** to the parameters at a later time.
3755**
3756** ^(This routine actually returns the index of the largest (rightmost)
3757** parameter. For all forms except ?NNN, this will correspond to the
3758** number of unique parameters.  If parameters of the ?NNN form are used,
3759** there may be gaps in the list.)^
3760**
3761** See also: [sqlite3_bind_blob|sqlite3_bind()],
3762** [sqlite3_bind_parameter_name()], and
3763** [sqlite3_bind_parameter_index()].
3764*/
3765SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3766
3767/*
3768** CAPI3REF: Name Of A Host Parameter
3769**
3770** ^The sqlite3_bind_parameter_name(P,N) interface returns
3771** the name of the N-th [SQL parameter] in the [prepared statement] P.
3772** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3773** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3774** respectively.
3775** In other words, the initial ":" or "$" or "@" or "?"
3776** is included as part of the name.)^
3777** ^Parameters of the form "?" without a following integer have no name
3778** and are referred to as "nameless" or "anonymous parameters".
3779**
3780** ^The first host parameter has an index of 1, not 0.
3781**
3782** ^If the value N is out of range or if the N-th parameter is
3783** nameless, then NULL is returned.  ^The returned string is
3784** always in UTF-8 encoding even if the named parameter was
3785** originally specified as UTF-16 in [sqlite3_prepare16()] or
3786** [sqlite3_prepare16_v2()].
3787**
3788** See also: [sqlite3_bind_blob|sqlite3_bind()],
3789** [sqlite3_bind_parameter_count()], and
3790** [sqlite3_bind_parameter_index()].
3791*/
3792SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3793
3794/*
3795** CAPI3REF: Index Of A Parameter With A Given Name
3796**
3797** ^Return the index of an SQL parameter given its name.  ^The
3798** index value returned is suitable for use as the second
3799** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3800** is returned if no matching parameter is found.  ^The parameter
3801** name must be given in UTF-8 even if the original statement
3802** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3803**
3804** See also: [sqlite3_bind_blob|sqlite3_bind()],
3805** [sqlite3_bind_parameter_count()], and
3806** [sqlite3_bind_parameter_index()].
3807*/
3808SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3809
3810/*
3811** CAPI3REF: Reset All Bindings On A Prepared Statement
3812**
3813** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3814** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3815** ^Use this routine to reset all host parameters to NULL.
3816*/
3817SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3818
3819/*
3820** CAPI3REF: Number Of Columns In A Result Set
3821**
3822** ^Return the number of columns in the result set returned by the
3823** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3824** statement that does not return data (for example an [UPDATE]).
3825**
3826** See also: [sqlite3_data_count()]
3827*/
3828SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3829
3830/*
3831** CAPI3REF: Column Names In A Result Set
3832**
3833** ^These routines return the name assigned to a particular column
3834** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3835** interface returns a pointer to a zero-terminated UTF-8 string
3836** and sqlite3_column_name16() returns a pointer to a zero-terminated
3837** UTF-16 string.  ^The first parameter is the [prepared statement]
3838** that implements the [SELECT] statement. ^The second parameter is the
3839** column number.  ^The leftmost column is number 0.
3840**
3841** ^The returned string pointer is valid until either the [prepared statement]
3842** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3843** reprepared by the first call to [sqlite3_step()] for a particular run
3844** or until the next call to
3845** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3846**
3847** ^If sqlite3_malloc() fails during the processing of either routine
3848** (for example during a conversion from UTF-8 to UTF-16) then a
3849** NULL pointer is returned.
3850**
3851** ^The name of a result column is the value of the "AS" clause for
3852** that column, if there is an AS clause.  If there is no AS clause
3853** then the name of the column is unspecified and may change from
3854** one release of SQLite to the next.
3855*/
3856SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3857SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3858
3859/*
3860** CAPI3REF: Source Of Data In A Query Result
3861**
3862** ^These routines provide a means to determine the database, table, and
3863** table column that is the origin of a particular result column in
3864** [SELECT] statement.
3865** ^The name of the database or table or column can be returned as
3866** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3867** the database name, the _table_ routines return the table name, and
3868** the origin_ routines return the column name.
3869** ^The returned string is valid until the [prepared statement] is destroyed
3870** using [sqlite3_finalize()] or until the statement is automatically
3871** reprepared by the first call to [sqlite3_step()] for a particular run
3872** or until the same information is requested
3873** again in a different encoding.
3874**
3875** ^The names returned are the original un-aliased names of the
3876** database, table, and column.
3877**
3878** ^The first argument to these interfaces is a [prepared statement].
3879** ^These functions return information about the Nth result column returned by
3880** the statement, where N is the second function argument.
3881** ^The left-most column is column 0 for these routines.
3882**
3883** ^If the Nth column returned by the statement is an expression or
3884** subquery and is not a column value, then all of these functions return
3885** NULL.  ^These routine might also return NULL if a memory allocation error
3886** occurs.  ^Otherwise, they return the name of the attached database, table,
3887** or column that query result column was extracted from.
3888**
3889** ^As with all other SQLite APIs, those whose names end with "16" return
3890** UTF-16 encoded strings and the other functions return UTF-8.
3891**
3892** ^These APIs are only available if the library was compiled with the
3893** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3894**
3895** If two or more threads call one or more of these routines against the same
3896** prepared statement and column at the same time then the results are
3897** undefined.
3898**
3899** If two or more threads call one or more
3900** [sqlite3_column_database_name | column metadata interfaces]
3901** for the same [prepared statement] and result column
3902** at the same time then the results are undefined.
3903*/
3904SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3905SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3906SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3907SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3908SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3909SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3910
3911/*
3912** CAPI3REF: Declared Datatype Of A Query Result
3913**
3914** ^(The first parameter is a [prepared statement].
3915** If this statement is a [SELECT] statement and the Nth column of the
3916** returned result set of that [SELECT] is a table column (not an
3917** expression or subquery) then the declared type of the table
3918** column is returned.)^  ^If the Nth column of the result set is an
3919** expression or subquery, then a NULL pointer is returned.
3920** ^The returned string is always UTF-8 encoded.
3921**
3922** ^(For example, given the database schema:
3923**
3924** CREATE TABLE t1(c1 VARIANT);
3925**
3926** and the following statement to be compiled:
3927**
3928** SELECT c1 + 1, c1 FROM t1;
3929**
3930** this routine would return the string "VARIANT" for the second result
3931** column (i==1), and a NULL pointer for the first result column (i==0).)^
3932**
3933** ^SQLite uses dynamic run-time typing.  ^So just because a column
3934** is declared to contain a particular type does not mean that the
3935** data stored in that column is of the declared type.  SQLite is
3936** strongly typed, but the typing is dynamic not static.  ^Type
3937** is associated with individual values, not with the containers
3938** used to hold those values.
3939*/
3940SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3941SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3942
3943/*
3944** CAPI3REF: Evaluate An SQL Statement
3945**
3946** After a [prepared statement] has been prepared using either
3947** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3948** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3949** must be called one or more times to evaluate the statement.
3950**
3951** The details of the behavior of the sqlite3_step() interface depend
3952** on whether the statement was prepared using the newer "v2" interface
3953** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3954** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3955** new "v2" interface is recommended for new applications but the legacy
3956** interface will continue to be supported.
3957**
3958** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3959** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3960** ^With the "v2" interface, any of the other [result codes] or
3961** [extended result codes] might be returned as well.
3962**
3963** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3964** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3965** or occurs outside of an explicit transaction, then you can retry the
3966** statement.  If the statement is not a [COMMIT] and occurs within an
3967** explicit transaction then you should rollback the transaction before
3968** continuing.
3969**
3970** ^[SQLITE_DONE] means that the statement has finished executing
3971** successfully.  sqlite3_step() should not be called again on this virtual
3972** machine without first calling [sqlite3_reset()] to reset the virtual
3973** machine back to its initial state.
3974**
3975** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3976** is returned each time a new row of data is ready for processing by the
3977** caller. The values may be accessed using the [column access functions].
3978** sqlite3_step() is called again to retrieve the next row of data.
3979**
3980** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3981** violation) has occurred.  sqlite3_step() should not be called again on
3982** the VM. More information may be found by calling [sqlite3_errmsg()].
3983** ^With the legacy interface, a more specific error code (for example,
3984** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3985** can be obtained by calling [sqlite3_reset()] on the
3986** [prepared statement].  ^In the "v2" interface,
3987** the more specific error code is returned directly by sqlite3_step().
3988**
3989** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3990** Perhaps it was called on a [prepared statement] that has
3991** already been [sqlite3_finalize | finalized] or on one that had
3992** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3993** be the case that the same database connection is being used by two or
3994** more threads at the same moment in time.
3995**
3996** For all versions of SQLite up to and including 3.6.23.1, a call to
3997** [sqlite3_reset()] was required after sqlite3_step() returned anything
3998** other than [SQLITE_ROW] before any subsequent invocation of
3999** sqlite3_step().  Failure to reset the prepared statement using
4000** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4001** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4002** calling [sqlite3_reset()] automatically in this circumstance rather
4003** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4004** break because any application that ever receives an SQLITE_MISUSE error
4005** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4006** can be used to restore the legacy behavior.
4007**
4008** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4009** API always returns a generic error code, [SQLITE_ERROR], following any
4010** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4011** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4012** specific [error codes] that better describes the error.
4013** We admit that this is a goofy design.  The problem has been fixed
4014** with the "v2" interface.  If you prepare all of your SQL statements
4015** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4016** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4017** then the more specific [error codes] are returned directly
4018** by sqlite3_step().  The use of the "v2" interface is recommended.
4019*/
4020SQLITE_API int sqlite3_step(sqlite3_stmt*);
4021
4022/*
4023** CAPI3REF: Number of columns in a result set
4024**
4025** ^The sqlite3_data_count(P) interface returns the number of columns in the
4026** current row of the result set of [prepared statement] P.
4027** ^If prepared statement P does not have results ready to return
4028** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4029** interfaces) then sqlite3_data_count(P) returns 0.
4030** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4031** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4032** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4033** will return non-zero if previous call to [sqlite3_step](P) returned
4034** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4035** where it always returns zero since each step of that multi-step
4036** pragma returns 0 columns of data.
4037**
4038** See also: [sqlite3_column_count()]
4039*/
4040SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4041
4042/*
4043** CAPI3REF: Fundamental Datatypes
4044** KEYWORDS: SQLITE_TEXT
4045**
4046** ^(Every value in SQLite has one of five fundamental datatypes:
4047**
4048** <ul>
4049** <li> 64-bit signed integer
4050** <li> 64-bit IEEE floating point number
4051** <li> string
4052** <li> BLOB
4053** <li> NULL
4054** </ul>)^
4055**
4056** These constants are codes for each of those types.
4057**
4058** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4059** for a completely different meaning.  Software that links against both
4060** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4061** SQLITE_TEXT.
4062*/
4063#define SQLITE_INTEGER  1
4064#define SQLITE_FLOAT    2
4065#define SQLITE_BLOB     4
4066#define SQLITE_NULL     5
4067#ifdef SQLITE_TEXT
4068# undef SQLITE_TEXT
4069#else
4070# define SQLITE_TEXT     3
4071#endif
4072#define SQLITE3_TEXT     3
4073
4074/*
4075** CAPI3REF: Result Values From A Query
4076** KEYWORDS: {column access functions}
4077**
4078** These routines form the "result set" interface.
4079**
4080** ^These routines return information about a single column of the current
4081** result row of a query.  ^In every case the first argument is a pointer
4082** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4083** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4084** and the second argument is the index of the column for which information
4085** should be returned. ^The leftmost column of the result set has the index 0.
4086** ^The number of columns in the result can be determined using
4087** [sqlite3_column_count()].
4088**
4089** If the SQL statement does not currently point to a valid row, or if the
4090** column index is out of range, the result is undefined.
4091** These routines may only be called when the most recent call to
4092** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4093** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4094** If any of these routines are called after [sqlite3_reset()] or
4095** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4096** something other than [SQLITE_ROW], the results are undefined.
4097** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4098** are called from a different thread while any of these routines
4099** are pending, then the results are undefined.
4100**
4101** ^The sqlite3_column_type() routine returns the
4102** [SQLITE_INTEGER | datatype code] for the initial data type
4103** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4104** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4105** returned by sqlite3_column_type() is only meaningful if no type
4106** conversions have occurred as described below.  After a type conversion,
4107** the value returned by sqlite3_column_type() is undefined.  Future
4108** versions of SQLite may change the behavior of sqlite3_column_type()
4109** following a type conversion.
4110**
4111** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4112** routine returns the number of bytes in that BLOB or string.
4113** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4114** the string to UTF-8 and then returns the number of bytes.
4115** ^If the result is a numeric value then sqlite3_column_bytes() uses
4116** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4117** the number of bytes in that string.
4118** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4119**
4120** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4121** routine returns the number of bytes in that BLOB or string.
4122** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4123** the string to UTF-16 and then returns the number of bytes.
4124** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4125** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4126** the number of bytes in that string.
4127** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4128**
4129** ^The values returned by [sqlite3_column_bytes()] and
4130** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4131** of the string.  ^For clarity: the values returned by
4132** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4133** bytes in the string, not the number of characters.
4134**
4135** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4136** even empty strings, are always zero-terminated.  ^The return
4137** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4138**
4139** ^The object returned by [sqlite3_column_value()] is an
4140** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4141** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4142** If the [unprotected sqlite3_value] object returned by
4143** [sqlite3_column_value()] is used in any other way, including calls
4144** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4145** or [sqlite3_value_bytes()], then the behavior is undefined.
4146**
4147** These routines attempt to convert the value where appropriate.  ^For
4148** example, if the internal representation is FLOAT and a text result
4149** is requested, [sqlite3_snprintf()] is used internally to perform the
4150** conversion automatically.  ^(The following table details the conversions
4151** that are applied:
4152**
4153** <blockquote>
4154** <table border="1">
4155** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4156**
4157** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4158** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4159** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4160** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4161** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4162** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4163** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4164** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4165** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4166** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4167** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4168** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4169** <tr><td>  TEXT    <td>   BLOB    <td> No change
4170** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4171** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4172** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4173** </table>
4174** </blockquote>)^
4175**
4176** The table above makes reference to standard C library functions atoi()
4177** and atof().  SQLite does not really use these functions.  It has its
4178** own equivalent internal routines.  The atoi() and atof() names are
4179** used in the table for brevity and because they are familiar to most
4180** C programmers.
4181**
4182** Note that when type conversions occur, pointers returned by prior
4183** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4184** sqlite3_column_text16() may be invalidated.
4185** Type conversions and pointer invalidations might occur
4186** in the following cases:
4187**
4188** <ul>
4189** <li> The initial content is a BLOB and sqlite3_column_text() or
4190**      sqlite3_column_text16() is called.  A zero-terminator might
4191**      need to be added to the string.</li>
4192** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4193**      sqlite3_column_text16() is called.  The content must be converted
4194**      to UTF-16.</li>
4195** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4196**      sqlite3_column_text() is called.  The content must be converted
4197**      to UTF-8.</li>
4198** </ul>
4199**
4200** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4201** not invalidate a prior pointer, though of course the content of the buffer
4202** that the prior pointer references will have been modified.  Other kinds
4203** of conversion are done in place when it is possible, but sometimes they
4204** are not possible and in those cases prior pointers are invalidated.
4205**
4206** The safest and easiest to remember policy is to invoke these routines
4207** in one of the following ways:
4208**
4209** <ul>
4210**  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4211**  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4212**  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4213** </ul>
4214**
4215** In other words, you should call sqlite3_column_text(),
4216** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4217** into the desired format, then invoke sqlite3_column_bytes() or
4218** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4219** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4220** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4221** with calls to sqlite3_column_bytes().
4222**
4223** ^The pointers returned are valid until a type conversion occurs as
4224** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4225** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4226** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4227** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4228** [sqlite3_free()].
4229**
4230** ^(If a memory allocation error occurs during the evaluation of any
4231** of these routines, a default value is returned.  The default value
4232** is either the integer 0, the floating point number 0.0, or a NULL
4233** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4234** [SQLITE_NOMEM].)^
4235*/
4236SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4237SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4238SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4239SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4240SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4241SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4242SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4243SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4244SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4245SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4246
4247/*
4248** CAPI3REF: Destroy A Prepared Statement Object
4249**
4250** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4251** ^If the most recent evaluation of the statement encountered no errors
4252** or if the statement is never been evaluated, then sqlite3_finalize() returns
4253** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4254** sqlite3_finalize(S) returns the appropriate [error code] or
4255** [extended error code].
4256**
4257** ^The sqlite3_finalize(S) routine can be called at any point during
4258** the life cycle of [prepared statement] S:
4259** before statement S is ever evaluated, after
4260** one or more calls to [sqlite3_reset()], or after any call
4261** to [sqlite3_step()] regardless of whether or not the statement has
4262** completed execution.
4263**
4264** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4265**
4266** The application must finalize every [prepared statement] in order to avoid
4267** resource leaks.  It is a grievous error for the application to try to use
4268** a prepared statement after it has been finalized.  Any use of a prepared
4269** statement after it has been finalized can result in undefined and
4270** undesirable behavior such as segfaults and heap corruption.
4271*/
4272SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4273
4274/*
4275** CAPI3REF: Reset A Prepared Statement Object
4276**
4277** The sqlite3_reset() function is called to reset a [prepared statement]
4278** object back to its initial state, ready to be re-executed.
4279** ^Any SQL statement variables that had values bound to them using
4280** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4281** Use [sqlite3_clear_bindings()] to reset the bindings.
4282**
4283** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4284** back to the beginning of its program.
4285**
4286** ^If the most recent call to [sqlite3_step(S)] for the
4287** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4288** or if [sqlite3_step(S)] has never before been called on S,
4289** then [sqlite3_reset(S)] returns [SQLITE_OK].
4290**
4291** ^If the most recent call to [sqlite3_step(S)] for the
4292** [prepared statement] S indicated an error, then
4293** [sqlite3_reset(S)] returns an appropriate [error code].
4294**
4295** ^The [sqlite3_reset(S)] interface does not change the values
4296** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4297*/
4298SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4299
4300/*
4301** CAPI3REF: Create Or Redefine SQL Functions
4302** KEYWORDS: {function creation routines}
4303** KEYWORDS: {application-defined SQL function}
4304** KEYWORDS: {application-defined SQL functions}
4305**
4306** ^These functions (collectively known as "function creation routines")
4307** are used to add SQL functions or aggregates or to redefine the behavior
4308** of existing SQL functions or aggregates.  The only differences between
4309** these routines are the text encoding expected for
4310** the second parameter (the name of the function being created)
4311** and the presence or absence of a destructor callback for
4312** the application data pointer.
4313**
4314** ^The first parameter is the [database connection] to which the SQL
4315** function is to be added.  ^If an application uses more than one database
4316** connection then application-defined SQL functions must be added
4317** to each database connection separately.
4318**
4319** ^The second parameter is the name of the SQL function to be created or
4320** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4321** representation, exclusive of the zero-terminator.  ^Note that the name
4322** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4323** ^Any attempt to create a function with a longer name
4324** will result in [SQLITE_MISUSE] being returned.
4325**
4326** ^The third parameter (nArg)
4327** is the number of arguments that the SQL function or
4328** aggregate takes. ^If this parameter is -1, then the SQL function or
4329** aggregate may take any number of arguments between 0 and the limit
4330** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4331** parameter is less than -1 or greater than 127 then the behavior is
4332** undefined.
4333**
4334** ^The fourth parameter, eTextRep, specifies what
4335** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4336** its parameters.  Every SQL function implementation must be able to work
4337** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4338** more efficient with one encoding than another.  ^An application may
4339** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4340** times with the same function but with different values of eTextRep.
4341** ^When multiple implementations of the same function are available, SQLite
4342** will pick the one that involves the least amount of data conversion.
4343** If there is only a single implementation which does not care what text
4344** encoding is used, then the fourth argument should be [SQLITE_ANY].
4345**
4346** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4347** function can gain access to this pointer using [sqlite3_user_data()].)^
4348**
4349** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4350** pointers to C-language functions that implement the SQL function or
4351** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4352** callback only; NULL pointers must be passed as the xStep and xFinal
4353** parameters. ^An aggregate SQL function requires an implementation of xStep
4354** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4355** SQL function or aggregate, pass NULL pointers for all three function
4356** callbacks.
4357**
4358** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4359** then it is destructor for the application data pointer.
4360** The destructor is invoked when the function is deleted, either by being
4361** overloaded or when the database connection closes.)^
4362** ^The destructor is also invoked if the call to
4363** sqlite3_create_function_v2() fails.
4364** ^When the destructor callback of the tenth parameter is invoked, it
4365** is passed a single argument which is a copy of the application data
4366** pointer which was the fifth parameter to sqlite3_create_function_v2().
4367**
4368** ^It is permitted to register multiple implementations of the same
4369** functions with the same name but with either differing numbers of
4370** arguments or differing preferred text encodings.  ^SQLite will use
4371** the implementation that most closely matches the way in which the
4372** SQL function is used.  ^A function implementation with a non-negative
4373** nArg parameter is a better match than a function implementation with
4374** a negative nArg.  ^A function where the preferred text encoding
4375** matches the database encoding is a better
4376** match than a function where the encoding is different.
4377** ^A function where the encoding difference is between UTF16le and UTF16be
4378** is a closer match than a function where the encoding difference is
4379** between UTF8 and UTF16.
4380**
4381** ^Built-in functions may be overloaded by new application-defined functions.
4382**
4383** ^An application-defined function is permitted to call other
4384** SQLite interfaces.  However, such calls must not
4385** close the database connection nor finalize or reset the prepared
4386** statement in which the function is running.
4387*/
4388SQLITE_API int sqlite3_create_function(
4389  sqlite3 *db,
4390  const char *zFunctionName,
4391  int nArg,
4392  int eTextRep,
4393  void *pApp,
4394  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4395  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4396  void (*xFinal)(sqlite3_context*)
4397);
4398SQLITE_API int sqlite3_create_function16(
4399  sqlite3 *db,
4400  const void *zFunctionName,
4401  int nArg,
4402  int eTextRep,
4403  void *pApp,
4404  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4405  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4406  void (*xFinal)(sqlite3_context*)
4407);
4408SQLITE_API int sqlite3_create_function_v2(
4409  sqlite3 *db,
4410  const char *zFunctionName,
4411  int nArg,
4412  int eTextRep,
4413  void *pApp,
4414  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4415  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4416  void (*xFinal)(sqlite3_context*),
4417  void(*xDestroy)(void*)
4418);
4419
4420/*
4421** CAPI3REF: Text Encodings
4422**
4423** These constant define integer codes that represent the various
4424** text encodings supported by SQLite.
4425*/
4426#define SQLITE_UTF8           1
4427#define SQLITE_UTF16LE        2
4428#define SQLITE_UTF16BE        3
4429#define SQLITE_UTF16          4    /* Use native byte order */
4430#define SQLITE_ANY            5    /* sqlite3_create_function only */
4431#define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4432
4433/*
4434** CAPI3REF: Deprecated Functions
4435** DEPRECATED
4436**
4437** These functions are [deprecated].  In order to maintain
4438** backwards compatibility with older code, these functions continue
4439** to be supported.  However, new applications should avoid
4440** the use of these functions.  To help encourage people to avoid
4441** using these functions, we are not going to tell you what they do.
4442*/
4443#ifndef SQLITE_OMIT_DEPRECATED
4444SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4445SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4446SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4447SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4448SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4449SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
4450#endif
4451
4452/*
4453** CAPI3REF: Obtaining SQL Function Parameter Values
4454**
4455** The C-language implementation of SQL functions and aggregates uses
4456** this set of interface routines to access the parameter values on
4457** the function or aggregate.
4458**
4459** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4460** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4461** define callbacks that implement the SQL functions and aggregates.
4462** The 3rd parameter to these callbacks is an array of pointers to
4463** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4464** each parameter to the SQL function.  These routines are used to
4465** extract values from the [sqlite3_value] objects.
4466**
4467** These routines work only with [protected sqlite3_value] objects.
4468** Any attempt to use these routines on an [unprotected sqlite3_value]
4469** object results in undefined behavior.
4470**
4471** ^These routines work just like the corresponding [column access functions]
4472** except that  these routines take a single [protected sqlite3_value] object
4473** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4474**
4475** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4476** in the native byte-order of the host machine.  ^The
4477** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4478** extract UTF-16 strings as big-endian and little-endian respectively.
4479**
4480** ^(The sqlite3_value_numeric_type() interface attempts to apply
4481** numeric affinity to the value.  This means that an attempt is
4482** made to convert the value to an integer or floating point.  If
4483** such a conversion is possible without loss of information (in other
4484** words, if the value is a string that looks like a number)
4485** then the conversion is performed.  Otherwise no conversion occurs.
4486** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4487**
4488** Please pay particular attention to the fact that the pointer returned
4489** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4490** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4491** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4492** or [sqlite3_value_text16()].
4493**
4494** These routines must be called from the same thread as
4495** the SQL function that supplied the [sqlite3_value*] parameters.
4496*/
4497SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4498SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4499SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4500SQLITE_API double sqlite3_value_double(sqlite3_value*);
4501SQLITE_API int sqlite3_value_int(sqlite3_value*);
4502SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4503SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4504SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4505SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4506SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4507SQLITE_API int sqlite3_value_type(sqlite3_value*);
4508SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4509
4510/*
4511** CAPI3REF: Obtain Aggregate Function Context
4512**
4513** Implementations of aggregate SQL functions use this
4514** routine to allocate memory for storing their state.
4515**
4516** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4517** for a particular aggregate function, SQLite
4518** allocates N of memory, zeroes out that memory, and returns a pointer
4519** to the new memory. ^On second and subsequent calls to
4520** sqlite3_aggregate_context() for the same aggregate function instance,
4521** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4522** called once for each invocation of the xStep callback and then one
4523** last time when the xFinal callback is invoked.  ^(When no rows match
4524** an aggregate query, the xStep() callback of the aggregate function
4525** implementation is never called and xFinal() is called exactly once.
4526** In those cases, sqlite3_aggregate_context() might be called for the
4527** first time from within xFinal().)^
4528**
4529** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
4530** less than or equal to zero or if a memory allocate error occurs.
4531**
4532** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4533** determined by the N parameter on first successful call.  Changing the
4534** value of N in subsequent call to sqlite3_aggregate_context() within
4535** the same aggregate function instance will not resize the memory
4536** allocation.)^
4537**
4538** ^SQLite automatically frees the memory allocated by
4539** sqlite3_aggregate_context() when the aggregate query concludes.
4540**
4541** The first parameter must be a copy of the
4542** [sqlite3_context | SQL function context] that is the first parameter
4543** to the xStep or xFinal callback routine that implements the aggregate
4544** function.
4545**
4546** This routine must be called from the same thread in which
4547** the aggregate SQL function is running.
4548*/
4549SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4550
4551/*
4552** CAPI3REF: User Data For Functions
4553**
4554** ^The sqlite3_user_data() interface returns a copy of
4555** the pointer that was the pUserData parameter (the 5th parameter)
4556** of the [sqlite3_create_function()]
4557** and [sqlite3_create_function16()] routines that originally
4558** registered the application defined function.
4559**
4560** This routine must be called from the same thread in which
4561** the application-defined function is running.
4562*/
4563SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4564
4565/*
4566** CAPI3REF: Database Connection For Functions
4567**
4568** ^The sqlite3_context_db_handle() interface returns a copy of
4569** the pointer to the [database connection] (the 1st parameter)
4570** of the [sqlite3_create_function()]
4571** and [sqlite3_create_function16()] routines that originally
4572** registered the application defined function.
4573*/
4574SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4575
4576/*
4577** CAPI3REF: Function Auxiliary Data
4578**
4579** The following two functions may be used by scalar SQL functions to
4580** associate metadata with argument values. If the same value is passed to
4581** multiple invocations of the same SQL function during query execution, under
4582** some circumstances the associated metadata may be preserved. This may
4583** be used, for example, to add a regular-expression matching scalar
4584** function. The compiled version of the regular expression is stored as
4585** metadata associated with the SQL value passed as the regular expression
4586** pattern.  The compiled regular expression can be reused on multiple
4587** invocations of the same function so that the original pattern string
4588** does not need to be recompiled on each invocation.
4589**
4590** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4591** associated by the sqlite3_set_auxdata() function with the Nth argument
4592** value to the application-defined function. ^If no metadata has been ever
4593** been set for the Nth argument of the function, or if the corresponding
4594** function parameter has changed since the meta-data was set,
4595** then sqlite3_get_auxdata() returns a NULL pointer.
4596**
4597** ^The sqlite3_set_auxdata() interface saves the metadata
4598** pointed to by its 3rd parameter as the metadata for the N-th
4599** argument of the application-defined function.  Subsequent
4600** calls to sqlite3_get_auxdata() might return this data, if it has
4601** not been destroyed.
4602** ^If it is not NULL, SQLite will invoke the destructor
4603** function given by the 4th parameter to sqlite3_set_auxdata() on
4604** the metadata when the corresponding function parameter changes
4605** or when the SQL statement completes, whichever comes first.
4606**
4607** SQLite is free to call the destructor and drop metadata on any
4608** parameter of any function at any time.  ^The only guarantee is that
4609** the destructor will be called before the metadata is dropped.
4610**
4611** ^(In practice, metadata is preserved between function calls for
4612** expressions that are constant at compile time. This includes literal
4613** values and [parameters].)^
4614**
4615** These routines must be called from the same thread in which
4616** the SQL function is running.
4617*/
4618SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4619SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4620
4621
4622/*
4623** CAPI3REF: Constants Defining Special Destructor Behavior
4624**
4625** These are special values for the destructor that is passed in as the
4626** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4627** argument is SQLITE_STATIC, it means that the content pointer is constant
4628** and will never change.  It does not need to be destroyed.  ^The
4629** SQLITE_TRANSIENT value means that the content will likely change in
4630** the near future and that SQLite should make its own private copy of
4631** the content before returning.
4632**
4633** The typedef is necessary to work around problems in certain
4634** C++ compilers.  See ticket #2191.
4635*/
4636typedef void (*sqlite3_destructor_type)(void*);
4637#define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4638#define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4639
4640/*
4641** CAPI3REF: Setting The Result Of An SQL Function
4642**
4643** These routines are used by the xFunc or xFinal callbacks that
4644** implement SQL functions and aggregates.  See
4645** [sqlite3_create_function()] and [sqlite3_create_function16()]
4646** for additional information.
4647**
4648** These functions work very much like the [parameter binding] family of
4649** functions used to bind values to host parameters in prepared statements.
4650** Refer to the [SQL parameter] documentation for additional information.
4651**
4652** ^The sqlite3_result_blob() interface sets the result from
4653** an application-defined function to be the BLOB whose content is pointed
4654** to by the second parameter and which is N bytes long where N is the
4655** third parameter.
4656**
4657** ^The sqlite3_result_zeroblob() interfaces set the result of
4658** the application-defined function to be a BLOB containing all zero
4659** bytes and N bytes in size, where N is the value of the 2nd parameter.
4660**
4661** ^The sqlite3_result_double() interface sets the result from
4662** an application-defined function to be a floating point value specified
4663** by its 2nd argument.
4664**
4665** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4666** cause the implemented SQL function to throw an exception.
4667** ^SQLite uses the string pointed to by the
4668** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4669** as the text of an error message.  ^SQLite interprets the error
4670** message string from sqlite3_result_error() as UTF-8. ^SQLite
4671** interprets the string from sqlite3_result_error16() as UTF-16 in native
4672** byte order.  ^If the third parameter to sqlite3_result_error()
4673** or sqlite3_result_error16() is negative then SQLite takes as the error
4674** message all text up through the first zero character.
4675** ^If the third parameter to sqlite3_result_error() or
4676** sqlite3_result_error16() is non-negative then SQLite takes that many
4677** bytes (not characters) from the 2nd parameter as the error message.
4678** ^The sqlite3_result_error() and sqlite3_result_error16()
4679** routines make a private copy of the error message text before
4680** they return.  Hence, the calling function can deallocate or
4681** modify the text after they return without harm.
4682** ^The sqlite3_result_error_code() function changes the error code
4683** returned by SQLite as a result of an error in a function.  ^By default,
4684** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4685** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4686**
4687** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4688** indicating that a string or BLOB is too long to represent.
4689**
4690** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4691** indicating that a memory allocation failed.
4692**
4693** ^The sqlite3_result_int() interface sets the return value
4694** of the application-defined function to be the 32-bit signed integer
4695** value given in the 2nd argument.
4696** ^The sqlite3_result_int64() interface sets the return value
4697** of the application-defined function to be the 64-bit signed integer
4698** value given in the 2nd argument.
4699**
4700** ^The sqlite3_result_null() interface sets the return value
4701** of the application-defined function to be NULL.
4702**
4703** ^The sqlite3_result_text(), sqlite3_result_text16(),
4704** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4705** set the return value of the application-defined function to be
4706** a text string which is represented as UTF-8, UTF-16 native byte order,
4707** UTF-16 little endian, or UTF-16 big endian, respectively.
4708** ^SQLite takes the text result from the application from
4709** the 2nd parameter of the sqlite3_result_text* interfaces.
4710** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4711** is negative, then SQLite takes result text from the 2nd parameter
4712** through the first zero character.
4713** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4714** is non-negative, then as many bytes (not characters) of the text
4715** pointed to by the 2nd parameter are taken as the application-defined
4716** function result.  If the 3rd parameter is non-negative, then it
4717** must be the byte offset into the string where the NUL terminator would
4718** appear if the string where NUL terminated.  If any NUL characters occur
4719** in the string at a byte offset that is less than the value of the 3rd
4720** parameter, then the resulting string will contain embedded NULs and the
4721** result of expressions operating on strings with embedded NULs is undefined.
4722** ^If the 4th parameter to the sqlite3_result_text* interfaces
4723** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4724** function as the destructor on the text or BLOB result when it has
4725** finished using that result.
4726** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4727** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4728** assumes that the text or BLOB result is in constant space and does not
4729** copy the content of the parameter nor call a destructor on the content
4730** when it has finished using that result.
4731** ^If the 4th parameter to the sqlite3_result_text* interfaces
4732** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4733** then SQLite makes a copy of the result into space obtained from
4734** from [sqlite3_malloc()] before it returns.
4735**
4736** ^The sqlite3_result_value() interface sets the result of
4737** the application-defined function to be a copy the
4738** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4739** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4740** so that the [sqlite3_value] specified in the parameter may change or
4741** be deallocated after sqlite3_result_value() returns without harm.
4742** ^A [protected sqlite3_value] object may always be used where an
4743** [unprotected sqlite3_value] object is required, so either
4744** kind of [sqlite3_value] object can be used with this interface.
4745**
4746** If these routines are called from within the different thread
4747** than the one containing the application-defined function that received
4748** the [sqlite3_context] pointer, the results are undefined.
4749*/
4750SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4751SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4752SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4753SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4754SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4755SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4756SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4757SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4758SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4759SQLITE_API void sqlite3_result_null(sqlite3_context*);
4760SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4761SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4762SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4763SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4764SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4765SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4766
4767/*
4768** CAPI3REF: Define New Collating Sequences
4769**
4770** ^These functions add, remove, or modify a [collation] associated
4771** with the [database connection] specified as the first argument.
4772**
4773** ^The name of the collation is a UTF-8 string
4774** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4775** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4776** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4777** considered to be the same name.
4778**
4779** ^(The third argument (eTextRep) must be one of the constants:
4780** <ul>
4781** <li> [SQLITE_UTF8],
4782** <li> [SQLITE_UTF16LE],
4783** <li> [SQLITE_UTF16BE],
4784** <li> [SQLITE_UTF16], or
4785** <li> [SQLITE_UTF16_ALIGNED].
4786** </ul>)^
4787** ^The eTextRep argument determines the encoding of strings passed
4788** to the collating function callback, xCallback.
4789** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4790** force strings to be UTF16 with native byte order.
4791** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4792** on an even byte address.
4793**
4794** ^The fourth argument, pArg, is an application data pointer that is passed
4795** through as the first argument to the collating function callback.
4796**
4797** ^The fifth argument, xCallback, is a pointer to the collating function.
4798** ^Multiple collating functions can be registered using the same name but
4799** with different eTextRep parameters and SQLite will use whichever
4800** function requires the least amount of data transformation.
4801** ^If the xCallback argument is NULL then the collating function is
4802** deleted.  ^When all collating functions having the same name are deleted,
4803** that collation is no longer usable.
4804**
4805** ^The collating function callback is invoked with a copy of the pArg
4806** application data pointer and with two strings in the encoding specified
4807** by the eTextRep argument.  The collating function must return an
4808** integer that is negative, zero, or positive
4809** if the first string is less than, equal to, or greater than the second,
4810** respectively.  A collating function must always return the same answer
4811** given the same inputs.  If two or more collating functions are registered
4812** to the same collation name (using different eTextRep values) then all
4813** must give an equivalent answer when invoked with equivalent strings.
4814** The collating function must obey the following properties for all
4815** strings A, B, and C:
4816**
4817** <ol>
4818** <li> If A==B then B==A.
4819** <li> If A==B and B==C then A==C.
4820** <li> If A&lt;B THEN B&gt;A.
4821** <li> If A&lt;B and B&lt;C then A&lt;C.
4822** </ol>
4823**
4824** If a collating function fails any of the above constraints and that
4825** collating function is  registered and used, then the behavior of SQLite
4826** is undefined.
4827**
4828** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4829** with the addition that the xDestroy callback is invoked on pArg when
4830** the collating function is deleted.
4831** ^Collating functions are deleted when they are overridden by later
4832** calls to the collation creation functions or when the
4833** [database connection] is closed using [sqlite3_close()].
4834**
4835** ^The xDestroy callback is <u>not</u> called if the
4836** sqlite3_create_collation_v2() function fails.  Applications that invoke
4837** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
4838** check the return code and dispose of the application data pointer
4839** themselves rather than expecting SQLite to deal with it for them.
4840** This is different from every other SQLite interface.  The inconsistency
4841** is unfortunate but cannot be changed without breaking backwards
4842** compatibility.
4843**
4844** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4845*/
4846SQLITE_API int sqlite3_create_collation(
4847  sqlite3*,
4848  const char *zName,
4849  int eTextRep,
4850  void *pArg,
4851  int(*xCompare)(void*,int,const void*,int,const void*)
4852);
4853SQLITE_API int sqlite3_create_collation_v2(
4854  sqlite3*,
4855  const char *zName,
4856  int eTextRep,
4857  void *pArg,
4858  int(*xCompare)(void*,int,const void*,int,const void*),
4859  void(*xDestroy)(void*)
4860);
4861SQLITE_API int sqlite3_create_collation16(
4862  sqlite3*,
4863  const void *zName,
4864  int eTextRep,
4865  void *pArg,
4866  int(*xCompare)(void*,int,const void*,int,const void*)
4867);
4868
4869/*
4870** CAPI3REF: Collation Needed Callbacks
4871**
4872** ^To avoid having to register all collation sequences before a database
4873** can be used, a single callback function may be registered with the
4874** [database connection] to be invoked whenever an undefined collation
4875** sequence is required.
4876**
4877** ^If the function is registered using the sqlite3_collation_needed() API,
4878** then it is passed the names of undefined collation sequences as strings
4879** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4880** the names are passed as UTF-16 in machine native byte order.
4881** ^A call to either function replaces the existing collation-needed callback.
4882**
4883** ^(When the callback is invoked, the first argument passed is a copy
4884** of the second argument to sqlite3_collation_needed() or
4885** sqlite3_collation_needed16().  The second argument is the database
4886** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4887** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4888** sequence function required.  The fourth parameter is the name of the
4889** required collation sequence.)^
4890**
4891** The callback function should register the desired collation using
4892** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4893** [sqlite3_create_collation_v2()].
4894*/
4895SQLITE_API int sqlite3_collation_needed(
4896  sqlite3*,
4897  void*,
4898  void(*)(void*,sqlite3*,int eTextRep,const char*)
4899);
4900SQLITE_API int sqlite3_collation_needed16(
4901  sqlite3*,
4902  void*,
4903  void(*)(void*,sqlite3*,int eTextRep,const void*)
4904);
4905
4906#ifdef SQLITE_HAS_CODEC
4907/*
4908** Specify the key for an encrypted database.  This routine should be
4909** called right after sqlite3_open().
4910**
4911** The code to implement this API is not available in the public release
4912** of SQLite.
4913*/
4914SQLITE_API int sqlite3_key(
4915  sqlite3 *db,                   /* Database to be rekeyed */
4916  const void *pKey, int nKey     /* The key */
4917);
4918
4919/*
4920** Change the key on an open database.  If the current database is not
4921** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4922** database is decrypted.
4923**
4924** The code to implement this API is not available in the public release
4925** of SQLite.
4926*/
4927SQLITE_API int sqlite3_rekey(
4928  sqlite3 *db,                   /* Database to be rekeyed */
4929  const void *pKey, int nKey     /* The new key */
4930);
4931
4932/*
4933** Specify the activation key for a SEE database.  Unless
4934** activated, none of the SEE routines will work.
4935*/
4936SQLITE_API void sqlite3_activate_see(
4937  const char *zPassPhrase        /* Activation phrase */
4938);
4939#endif
4940
4941#ifdef SQLITE_ENABLE_CEROD
4942/*
4943** Specify the activation key for a CEROD database.  Unless
4944** activated, none of the CEROD routines will work.
4945*/
4946SQLITE_API void sqlite3_activate_cerod(
4947  const char *zPassPhrase        /* Activation phrase */
4948);
4949#endif
4950
4951/*
4952** CAPI3REF: Suspend Execution For A Short Time
4953**
4954** The sqlite3_sleep() function causes the current thread to suspend execution
4955** for at least a number of milliseconds specified in its parameter.
4956**
4957** If the operating system does not support sleep requests with
4958** millisecond time resolution, then the time will be rounded up to
4959** the nearest second. The number of milliseconds of sleep actually
4960** requested from the operating system is returned.
4961**
4962** ^SQLite implements this interface by calling the xSleep()
4963** method of the default [sqlite3_vfs] object.  If the xSleep() method
4964** of the default VFS is not implemented correctly, or not implemented at
4965** all, then the behavior of sqlite3_sleep() may deviate from the description
4966** in the previous paragraphs.
4967*/
4968SQLITE_API int sqlite3_sleep(int);
4969
4970/*
4971** CAPI3REF: Name Of The Folder Holding Temporary Files
4972**
4973** ^(If this global variable is made to point to a string which is
4974** the name of a folder (a.k.a. directory), then all temporary files
4975** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4976** will be placed in that directory.)^  ^If this variable
4977** is a NULL pointer, then SQLite performs a search for an appropriate
4978** temporary file directory.
4979**
4980** It is not safe to read or modify this variable in more than one
4981** thread at a time.  It is not safe to read or modify this variable
4982** if a [database connection] is being used at the same time in a separate
4983** thread.
4984** It is intended that this variable be set once
4985** as part of process initialization and before any SQLite interface
4986** routines have been called and that this variable remain unchanged
4987** thereafter.
4988**
4989** ^The [temp_store_directory pragma] may modify this variable and cause
4990** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4991** the [temp_store_directory pragma] always assumes that any string
4992** that this variable points to is held in memory obtained from
4993** [sqlite3_malloc] and the pragma may attempt to free that memory
4994** using [sqlite3_free].
4995** Hence, if this variable is modified directly, either it should be
4996** made NULL or made to point to memory obtained from [sqlite3_malloc]
4997** or else the use of the [temp_store_directory pragma] should be avoided.
4998*/
4999SQLITE_API char *sqlite3_temp_directory;
5000
5001/*
5002** CAPI3REF: Test For Auto-Commit Mode
5003** KEYWORDS: {autocommit mode}
5004**
5005** ^The sqlite3_get_autocommit() interface returns non-zero or
5006** zero if the given database connection is or is not in autocommit mode,
5007** respectively.  ^Autocommit mode is on by default.
5008** ^Autocommit mode is disabled by a [BEGIN] statement.
5009** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5010**
5011** If certain kinds of errors occur on a statement within a multi-statement
5012** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5013** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5014** transaction might be rolled back automatically.  The only way to
5015** find out whether SQLite automatically rolled back the transaction after
5016** an error is to use this function.
5017**
5018** If another thread changes the autocommit status of the database
5019** connection while this routine is running, then the return value
5020** is undefined.
5021*/
5022SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5023
5024/*
5025** CAPI3REF: Find The Database Handle Of A Prepared Statement
5026**
5027** ^The sqlite3_db_handle interface returns the [database connection] handle
5028** to which a [prepared statement] belongs.  ^The [database connection]
5029** returned by sqlite3_db_handle is the same [database connection]
5030** that was the first argument
5031** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5032** create the statement in the first place.
5033*/
5034SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5035
5036/*
5037** CAPI3REF: Return The Filename For A Database Connection
5038**
5039** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5040** associated with database N of connection D.  ^The main database file
5041** has the name "main".  If there is no attached database N on the database
5042** connection D, or if database N is a temporary or in-memory database, then
5043** a NULL pointer is returned.
5044**
5045** ^The filename returned by this function is the output of the
5046** xFullPathname method of the [VFS].  ^In other words, the filename
5047** will be an absolute pathname, even if the filename used
5048** to open the database originally was a URI or relative pathname.
5049*/
5050SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5051
5052/*
5053** CAPI3REF: Determine if a database is read-only
5054**
5055** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5056** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5057** the name of a database on connection D.
5058*/
5059SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5060
5061/*
5062** CAPI3REF: Find the next prepared statement
5063**
5064** ^This interface returns a pointer to the next [prepared statement] after
5065** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5066** then this interface returns a pointer to the first prepared statement
5067** associated with the database connection pDb.  ^If no prepared statement
5068** satisfies the conditions of this routine, it returns NULL.
5069**
5070** The [database connection] pointer D in a call to
5071** [sqlite3_next_stmt(D,S)] must refer to an open database
5072** connection and in particular must not be a NULL pointer.
5073*/
5074SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5075
5076/*
5077** CAPI3REF: Commit And Rollback Notification Callbacks
5078**
5079** ^The sqlite3_commit_hook() interface registers a callback
5080** function to be invoked whenever a transaction is [COMMIT | committed].
5081** ^Any callback set by a previous call to sqlite3_commit_hook()
5082** for the same database connection is overridden.
5083** ^The sqlite3_rollback_hook() interface registers a callback
5084** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5085** ^Any callback set by a previous call to sqlite3_rollback_hook()
5086** for the same database connection is overridden.
5087** ^The pArg argument is passed through to the callback.
5088** ^If the callback on a commit hook function returns non-zero,
5089** then the commit is converted into a rollback.
5090**
5091** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5092** return the P argument from the previous call of the same function
5093** on the same [database connection] D, or NULL for
5094** the first call for each function on D.
5095**
5096** The commit and rollback hook callbacks are not reentrant.
5097** The callback implementation must not do anything that will modify
5098** the database connection that invoked the callback.  Any actions
5099** to modify the database connection must be deferred until after the
5100** completion of the [sqlite3_step()] call that triggered the commit
5101** or rollback hook in the first place.
5102** Note that running any other SQL statements, including SELECT statements,
5103** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5104** the database connections for the meaning of "modify" in this paragraph.
5105**
5106** ^Registering a NULL function disables the callback.
5107**
5108** ^When the commit hook callback routine returns zero, the [COMMIT]
5109** operation is allowed to continue normally.  ^If the commit hook
5110** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5111** ^The rollback hook is invoked on a rollback that results from a commit
5112** hook returning non-zero, just as it would be with any other rollback.
5113**
5114** ^For the purposes of this API, a transaction is said to have been
5115** rolled back if an explicit "ROLLBACK" statement is executed, or
5116** an error or constraint causes an implicit rollback to occur.
5117** ^The rollback callback is not invoked if a transaction is
5118** automatically rolled back because the database connection is closed.
5119**
5120** See also the [sqlite3_update_hook()] interface.
5121*/
5122SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5123SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5124
5125/*
5126** CAPI3REF: Data Change Notification Callbacks
5127**
5128** ^The sqlite3_update_hook() interface registers a callback function
5129** with the [database connection] identified by the first argument
5130** to be invoked whenever a row is updated, inserted or deleted.
5131** ^Any callback set by a previous call to this function
5132** for the same database connection is overridden.
5133**
5134** ^The second argument is a pointer to the function to invoke when a
5135** row is updated, inserted or deleted.
5136** ^The first argument to the callback is a copy of the third argument
5137** to sqlite3_update_hook().
5138** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5139** or [SQLITE_UPDATE], depending on the operation that caused the callback
5140** to be invoked.
5141** ^The third and fourth arguments to the callback contain pointers to the
5142** database and table name containing the affected row.
5143** ^The final callback parameter is the [rowid] of the row.
5144** ^In the case of an update, this is the [rowid] after the update takes place.
5145**
5146** ^(The update hook is not invoked when internal system tables are
5147** modified (i.e. sqlite_master and sqlite_sequence).)^
5148**
5149** ^In the current implementation, the update hook
5150** is not invoked when duplication rows are deleted because of an
5151** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5152** invoked when rows are deleted using the [truncate optimization].
5153** The exceptions defined in this paragraph might change in a future
5154** release of SQLite.
5155**
5156** The update hook implementation must not do anything that will modify
5157** the database connection that invoked the update hook.  Any actions
5158** to modify the database connection must be deferred until after the
5159** completion of the [sqlite3_step()] call that triggered the update hook.
5160** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5161** database connections for the meaning of "modify" in this paragraph.
5162**
5163** ^The sqlite3_update_hook(D,C,P) function
5164** returns the P argument from the previous call
5165** on the same [database connection] D, or NULL for
5166** the first call on D.
5167**
5168** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5169** interfaces.
5170*/
5171SQLITE_API void *sqlite3_update_hook(
5172  sqlite3*,
5173  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5174  void*
5175);
5176
5177/*
5178** CAPI3REF: Enable Or Disable Shared Pager Cache
5179** KEYWORDS: {shared cache}
5180**
5181** ^(This routine enables or disables the sharing of the database cache
5182** and schema data structures between [database connection | connections]
5183** to the same database. Sharing is enabled if the argument is true
5184** and disabled if the argument is false.)^
5185**
5186** ^Cache sharing is enabled and disabled for an entire process.
5187** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5188** sharing was enabled or disabled for each thread separately.
5189**
5190** ^(The cache sharing mode set by this interface effects all subsequent
5191** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5192** Existing database connections continue use the sharing mode
5193** that was in effect at the time they were opened.)^
5194**
5195** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5196** successfully.  An [error code] is returned otherwise.)^
5197**
5198** ^Shared cache is disabled by default. But this might change in
5199** future releases of SQLite.  Applications that care about shared
5200** cache setting should set it explicitly.
5201**
5202** See Also:  [SQLite Shared-Cache Mode]
5203*/
5204SQLITE_API int sqlite3_enable_shared_cache(int);
5205
5206/*
5207** CAPI3REF: Attempt To Free Heap Memory
5208**
5209** ^The sqlite3_release_memory() interface attempts to free N bytes
5210** of heap memory by deallocating non-essential memory allocations
5211** held by the database library.   Memory used to cache database
5212** pages to improve performance is an example of non-essential memory.
5213** ^sqlite3_release_memory() returns the number of bytes actually freed,
5214** which might be more or less than the amount requested.
5215** ^The sqlite3_release_memory() routine is a no-op returning zero
5216** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5217**
5218** See also: [sqlite3_db_release_memory()]
5219*/
5220SQLITE_API int sqlite3_release_memory(int);
5221
5222/*
5223** CAPI3REF: Free Memory Used By A Database Connection
5224**
5225** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5226** memory as possible from database connection D. Unlike the
5227** [sqlite3_release_memory()] interface, this interface is effect even
5228** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5229** omitted.
5230**
5231** See also: [sqlite3_release_memory()]
5232*/
5233SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5234
5235/*
5236** CAPI3REF: Impose A Limit On Heap Size
5237**
5238** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5239** soft limit on the amount of heap memory that may be allocated by SQLite.
5240** ^SQLite strives to keep heap memory utilization below the soft heap
5241** limit by reducing the number of pages held in the page cache
5242** as heap memory usages approaches the limit.
5243** ^The soft heap limit is "soft" because even though SQLite strives to stay
5244** below the limit, it will exceed the limit rather than generate
5245** an [SQLITE_NOMEM] error.  In other words, the soft heap limit
5246** is advisory only.
5247**
5248** ^The return value from sqlite3_soft_heap_limit64() is the size of
5249** the soft heap limit prior to the call, or negative in the case of an
5250** error.  ^If the argument N is negative
5251** then no change is made to the soft heap limit.  Hence, the current
5252** size of the soft heap limit can be determined by invoking
5253** sqlite3_soft_heap_limit64() with a negative argument.
5254**
5255** ^If the argument N is zero then the soft heap limit is disabled.
5256**
5257** ^(The soft heap limit is not enforced in the current implementation
5258** if one or more of following conditions are true:
5259**
5260** <ul>
5261** <li> The soft heap limit is set to zero.
5262** <li> Memory accounting is disabled using a combination of the
5263**      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5264**      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5265** <li> An alternative page cache implementation is specified using
5266**      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5267** <li> The page cache allocates from its own memory pool supplied
5268**      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5269**      from the heap.
5270** </ul>)^
5271**
5272** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5273** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5274** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5275** the soft heap limit is enforced on every memory allocation.  Without
5276** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5277** when memory is allocated by the page cache.  Testing suggests that because
5278** the page cache is the predominate memory user in SQLite, most
5279** applications will achieve adequate soft heap limit enforcement without
5280** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5281**
5282** The circumstances under which SQLite will enforce the soft heap limit may
5283** changes in future releases of SQLite.
5284*/
5285SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5286
5287/*
5288** CAPI3REF: Deprecated Soft Heap Limit Interface
5289** DEPRECATED
5290**
5291** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5292** interface.  This routine is provided for historical compatibility
5293** only.  All new applications should use the
5294** [sqlite3_soft_heap_limit64()] interface rather than this one.
5295*/
5296SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5297
5298
5299/*
5300** CAPI3REF: Extract Metadata About A Column Of A Table
5301**
5302** ^This routine returns metadata about a specific column of a specific
5303** database table accessible using the [database connection] handle
5304** passed as the first function argument.
5305**
5306** ^The column is identified by the second, third and fourth parameters to
5307** this function. ^The second parameter is either the name of the database
5308** (i.e. "main", "temp", or an attached database) containing the specified
5309** table or NULL. ^If it is NULL, then all attached databases are searched
5310** for the table using the same algorithm used by the database engine to
5311** resolve unqualified table references.
5312**
5313** ^The third and fourth parameters to this function are the table and column
5314** name of the desired column, respectively. Neither of these parameters
5315** may be NULL.
5316**
5317** ^Metadata is returned by writing to the memory locations passed as the 5th
5318** and subsequent parameters to this function. ^Any of these arguments may be
5319** NULL, in which case the corresponding element of metadata is omitted.
5320**
5321** ^(<blockquote>
5322** <table border="1">
5323** <tr><th> Parameter <th> Output<br>Type <th>  Description
5324**
5325** <tr><td> 5th <td> const char* <td> Data type
5326** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5327** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5328** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5329** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5330** </table>
5331** </blockquote>)^
5332**
5333** ^The memory pointed to by the character pointers returned for the
5334** declaration type and collation sequence is valid only until the next
5335** call to any SQLite API function.
5336**
5337** ^If the specified table is actually a view, an [error code] is returned.
5338**
5339** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5340** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5341** parameters are set for the explicitly declared column. ^(If there is no
5342** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5343** parameters are set as follows:
5344**
5345** <pre>
5346**     data type: "INTEGER"
5347**     collation sequence: "BINARY"
5348**     not null: 0
5349**     primary key: 1
5350**     auto increment: 0
5351** </pre>)^
5352**
5353** ^(This function may load one or more schemas from database files. If an
5354** error occurs during this process, or if the requested table or column
5355** cannot be found, an [error code] is returned and an error message left
5356** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5357**
5358** ^This API is only available if the library was compiled with the
5359** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5360*/
5361SQLITE_API int sqlite3_table_column_metadata(
5362  sqlite3 *db,                /* Connection handle */
5363  const char *zDbName,        /* Database name or NULL */
5364  const char *zTableName,     /* Table name */
5365  const char *zColumnName,    /* Column name */
5366  char const **pzDataType,    /* OUTPUT: Declared data type */
5367  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5368  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5369  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5370  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5371);
5372
5373/*
5374** CAPI3REF: Load An Extension
5375**
5376** ^This interface loads an SQLite extension library from the named file.
5377**
5378** ^The sqlite3_load_extension() interface attempts to load an
5379** SQLite extension library contained in the file zFile.
5380**
5381** ^The entry point is zProc.
5382** ^zProc may be 0, in which case the name of the entry point
5383** defaults to "sqlite3_extension_init".
5384** ^The sqlite3_load_extension() interface returns
5385** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5386** ^If an error occurs and pzErrMsg is not 0, then the
5387** [sqlite3_load_extension()] interface shall attempt to
5388** fill *pzErrMsg with error message text stored in memory
5389** obtained from [sqlite3_malloc()]. The calling function
5390** should free this memory by calling [sqlite3_free()].
5391**
5392** ^Extension loading must be enabled using
5393** [sqlite3_enable_load_extension()] prior to calling this API,
5394** otherwise an error will be returned.
5395**
5396** See also the [load_extension() SQL function].
5397*/
5398SQLITE_API int sqlite3_load_extension(
5399  sqlite3 *db,          /* Load the extension into this database connection */
5400  const char *zFile,    /* Name of the shared library containing extension */
5401  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5402  char **pzErrMsg       /* Put error message here if not 0 */
5403);
5404
5405/*
5406** CAPI3REF: Enable Or Disable Extension Loading
5407**
5408** ^So as not to open security holes in older applications that are
5409** unprepared to deal with extension loading, and as a means of disabling
5410** extension loading while evaluating user-entered SQL, the following API
5411** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5412**
5413** ^Extension loading is off by default. See ticket #1863.
5414** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5415** to turn extension loading on and call it with onoff==0 to turn
5416** it back off again.
5417*/
5418SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5419
5420/*
5421** CAPI3REF: Automatically Load Statically Linked Extensions
5422**
5423** ^This interface causes the xEntryPoint() function to be invoked for
5424** each new [database connection] that is created.  The idea here is that
5425** xEntryPoint() is the entry point for a statically linked SQLite extension
5426** that is to be automatically loaded into all new database connections.
5427**
5428** ^(Even though the function prototype shows that xEntryPoint() takes
5429** no arguments and returns void, SQLite invokes xEntryPoint() with three
5430** arguments and expects and integer result as if the signature of the
5431** entry point where as follows:
5432**
5433** <blockquote><pre>
5434** &nbsp;  int xEntryPoint(
5435** &nbsp;    sqlite3 *db,
5436** &nbsp;    const char **pzErrMsg,
5437** &nbsp;    const struct sqlite3_api_routines *pThunk
5438** &nbsp;  );
5439** </pre></blockquote>)^
5440**
5441** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5442** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5443** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5444** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5445** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5446** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5447** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5448**
5449** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5450** on the list of automatic extensions is a harmless no-op. ^No entry point
5451** will be called more than once for each database connection that is opened.
5452**
5453** See also: [sqlite3_reset_auto_extension()].
5454*/
5455SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5456
5457/*
5458** CAPI3REF: Reset Automatic Extension Loading
5459**
5460** ^This interface disables all automatic extensions previously
5461** registered using [sqlite3_auto_extension()].
5462*/
5463SQLITE_API void sqlite3_reset_auto_extension(void);
5464
5465/*
5466** The interface to the virtual-table mechanism is currently considered
5467** to be experimental.  The interface might change in incompatible ways.
5468** If this is a problem for you, do not use the interface at this time.
5469**
5470** When the virtual-table mechanism stabilizes, we will declare the
5471** interface fixed, support it indefinitely, and remove this comment.
5472*/
5473
5474/*
5475** Structures used by the virtual table interface
5476*/
5477typedef struct sqlite3_vtab sqlite3_vtab;
5478typedef struct sqlite3_index_info sqlite3_index_info;
5479typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5480typedef struct sqlite3_module sqlite3_module;
5481
5482/*
5483** CAPI3REF: Virtual Table Object
5484** KEYWORDS: sqlite3_module {virtual table module}
5485**
5486** This structure, sometimes called a "virtual table module",
5487** defines the implementation of a [virtual tables].
5488** This structure consists mostly of methods for the module.
5489**
5490** ^A virtual table module is created by filling in a persistent
5491** instance of this structure and passing a pointer to that instance
5492** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5493** ^The registration remains valid until it is replaced by a different
5494** module or until the [database connection] closes.  The content
5495** of this structure must not change while it is registered with
5496** any database connection.
5497*/
5498struct sqlite3_module {
5499  int iVersion;
5500  int (*xCreate)(sqlite3*, void *pAux,
5501               int argc, const char *const*argv,
5502               sqlite3_vtab **ppVTab, char**);
5503  int (*xConnect)(sqlite3*, void *pAux,
5504               int argc, const char *const*argv,
5505               sqlite3_vtab **ppVTab, char**);
5506  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5507  int (*xDisconnect)(sqlite3_vtab *pVTab);
5508  int (*xDestroy)(sqlite3_vtab *pVTab);
5509  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5510  int (*xClose)(sqlite3_vtab_cursor*);
5511  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5512                int argc, sqlite3_value **argv);
5513  int (*xNext)(sqlite3_vtab_cursor*);
5514  int (*xEof)(sqlite3_vtab_cursor*);
5515  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5516  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5517  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5518  int (*xBegin)(sqlite3_vtab *pVTab);
5519  int (*xSync)(sqlite3_vtab *pVTab);
5520  int (*xCommit)(sqlite3_vtab *pVTab);
5521  int (*xRollback)(sqlite3_vtab *pVTab);
5522  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5523                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5524                       void **ppArg);
5525  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5526  /* The methods above are in version 1 of the sqlite_module object. Those
5527  ** below are for version 2 and greater. */
5528  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5529  int (*xRelease)(sqlite3_vtab *pVTab, int);
5530  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5531};
5532
5533/*
5534** CAPI3REF: Virtual Table Indexing Information
5535** KEYWORDS: sqlite3_index_info
5536**
5537** The sqlite3_index_info structure and its substructures is used as part
5538** of the [virtual table] interface to
5539** pass information into and receive the reply from the [xBestIndex]
5540** method of a [virtual table module].  The fields under **Inputs** are the
5541** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5542** results into the **Outputs** fields.
5543**
5544** ^(The aConstraint[] array records WHERE clause constraints of the form:
5545**
5546** <blockquote>column OP expr</blockquote>
5547**
5548** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5549** stored in aConstraint[].op using one of the
5550** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5551** ^(The index of the column is stored in
5552** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5553** expr on the right-hand side can be evaluated (and thus the constraint
5554** is usable) and false if it cannot.)^
5555**
5556** ^The optimizer automatically inverts terms of the form "expr OP column"
5557** and makes other simplifications to the WHERE clause in an attempt to
5558** get as many WHERE clause terms into the form shown above as possible.
5559** ^The aConstraint[] array only reports WHERE clause terms that are
5560** relevant to the particular virtual table being queried.
5561**
5562** ^Information about the ORDER BY clause is stored in aOrderBy[].
5563** ^Each term of aOrderBy records a column of the ORDER BY clause.
5564**
5565** The [xBestIndex] method must fill aConstraintUsage[] with information
5566** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5567** the right-hand side of the corresponding aConstraint[] is evaluated
5568** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5569** is true, then the constraint is assumed to be fully handled by the
5570** virtual table and is not checked again by SQLite.)^
5571**
5572** ^The idxNum and idxPtr values are recorded and passed into the
5573** [xFilter] method.
5574** ^[sqlite3_free()] is used to free idxPtr if and only if
5575** needToFreeIdxPtr is true.
5576**
5577** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5578** the correct order to satisfy the ORDER BY clause so that no separate
5579** sorting step is required.
5580**
5581** ^The estimatedCost value is an estimate of the cost of doing the
5582** particular lookup.  A full scan of a table with N entries should have
5583** a cost of N.  A binary search of a table of N entries should have a
5584** cost of approximately log(N).
5585*/
5586struct sqlite3_index_info {
5587  /* Inputs */
5588  int nConstraint;           /* Number of entries in aConstraint */
5589  struct sqlite3_index_constraint {
5590     int iColumn;              /* Column on left-hand side of constraint */
5591     unsigned char op;         /* Constraint operator */
5592     unsigned char usable;     /* True if this constraint is usable */
5593     int iTermOffset;          /* Used internally - xBestIndex should ignore */
5594  } *aConstraint;            /* Table of WHERE clause constraints */
5595  int nOrderBy;              /* Number of terms in the ORDER BY clause */
5596  struct sqlite3_index_orderby {
5597     int iColumn;              /* Column number */
5598     unsigned char desc;       /* True for DESC.  False for ASC. */
5599  } *aOrderBy;               /* The ORDER BY clause */
5600  /* Outputs */
5601  struct sqlite3_index_constraint_usage {
5602    int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5603    unsigned char omit;      /* Do not code a test for this constraint */
5604  } *aConstraintUsage;
5605  int idxNum;                /* Number used to identify the index */
5606  char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5607  int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5608  int orderByConsumed;       /* True if output is already ordered */
5609  double estimatedCost;      /* Estimated cost of using this index */
5610};
5611
5612/*
5613** CAPI3REF: Virtual Table Constraint Operator Codes
5614**
5615** These macros defined the allowed values for the
5616** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5617** an operator that is part of a constraint term in the wHERE clause of
5618** a query that uses a [virtual table].
5619*/
5620#define SQLITE_INDEX_CONSTRAINT_EQ    2
5621#define SQLITE_INDEX_CONSTRAINT_GT    4
5622#define SQLITE_INDEX_CONSTRAINT_LE    8
5623#define SQLITE_INDEX_CONSTRAINT_LT    16
5624#define SQLITE_INDEX_CONSTRAINT_GE    32
5625#define SQLITE_INDEX_CONSTRAINT_MATCH 64
5626
5627/*
5628** CAPI3REF: Register A Virtual Table Implementation
5629**
5630** ^These routines are used to register a new [virtual table module] name.
5631** ^Module names must be registered before
5632** creating a new [virtual table] using the module and before using a
5633** preexisting [virtual table] for the module.
5634**
5635** ^The module name is registered on the [database connection] specified
5636** by the first parameter.  ^The name of the module is given by the
5637** second parameter.  ^The third parameter is a pointer to
5638** the implementation of the [virtual table module].   ^The fourth
5639** parameter is an arbitrary client data pointer that is passed through
5640** into the [xCreate] and [xConnect] methods of the virtual table module
5641** when a new virtual table is be being created or reinitialized.
5642**
5643** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5644** is a pointer to a destructor for the pClientData.  ^SQLite will
5645** invoke the destructor function (if it is not NULL) when SQLite
5646** no longer needs the pClientData pointer.  ^The destructor will also
5647** be invoked if the call to sqlite3_create_module_v2() fails.
5648** ^The sqlite3_create_module()
5649** interface is equivalent to sqlite3_create_module_v2() with a NULL
5650** destructor.
5651*/
5652SQLITE_API int sqlite3_create_module(
5653  sqlite3 *db,               /* SQLite connection to register module with */
5654  const char *zName,         /* Name of the module */
5655  const sqlite3_module *p,   /* Methods for the module */
5656  void *pClientData          /* Client data for xCreate/xConnect */
5657);
5658SQLITE_API int sqlite3_create_module_v2(
5659  sqlite3 *db,               /* SQLite connection to register module with */
5660  const char *zName,         /* Name of the module */
5661  const sqlite3_module *p,   /* Methods for the module */
5662  void *pClientData,         /* Client data for xCreate/xConnect */
5663  void(*xDestroy)(void*)     /* Module destructor function */
5664);
5665
5666/*
5667** CAPI3REF: Virtual Table Instance Object
5668** KEYWORDS: sqlite3_vtab
5669**
5670** Every [virtual table module] implementation uses a subclass
5671** of this object to describe a particular instance
5672** of the [virtual table].  Each subclass will
5673** be tailored to the specific needs of the module implementation.
5674** The purpose of this superclass is to define certain fields that are
5675** common to all module implementations.
5676**
5677** ^Virtual tables methods can set an error message by assigning a
5678** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5679** take care that any prior string is freed by a call to [sqlite3_free()]
5680** prior to assigning a new string to zErrMsg.  ^After the error message
5681** is delivered up to the client application, the string will be automatically
5682** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5683*/
5684struct sqlite3_vtab {
5685  const sqlite3_module *pModule;  /* The module for this virtual table */
5686  int nRef;                       /* NO LONGER USED */
5687  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5688  /* Virtual table implementations will typically add additional fields */
5689};
5690
5691/*
5692** CAPI3REF: Virtual Table Cursor Object
5693** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5694**
5695** Every [virtual table module] implementation uses a subclass of the
5696** following structure to describe cursors that point into the
5697** [virtual table] and are used
5698** to loop through the virtual table.  Cursors are created using the
5699** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5700** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5701** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5702** of the module.  Each module implementation will define
5703** the content of a cursor structure to suit its own needs.
5704**
5705** This superclass exists in order to define fields of the cursor that
5706** are common to all implementations.
5707*/
5708struct sqlite3_vtab_cursor {
5709  sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5710  /* Virtual table implementations will typically add additional fields */
5711};
5712
5713/*
5714** CAPI3REF: Declare The Schema Of A Virtual Table
5715**
5716** ^The [xCreate] and [xConnect] methods of a
5717** [virtual table module] call this interface
5718** to declare the format (the names and datatypes of the columns) of
5719** the virtual tables they implement.
5720*/
5721SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5722
5723/*
5724** CAPI3REF: Overload A Function For A Virtual Table
5725**
5726** ^(Virtual tables can provide alternative implementations of functions
5727** using the [xFindFunction] method of the [virtual table module].
5728** But global versions of those functions
5729** must exist in order to be overloaded.)^
5730**
5731** ^(This API makes sure a global version of a function with a particular
5732** name and number of parameters exists.  If no such function exists
5733** before this API is called, a new function is created.)^  ^The implementation
5734** of the new function always causes an exception to be thrown.  So
5735** the new function is not good for anything by itself.  Its only
5736** purpose is to be a placeholder function that can be overloaded
5737** by a [virtual table].
5738*/
5739SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5740
5741/*
5742** The interface to the virtual-table mechanism defined above (back up
5743** to a comment remarkably similar to this one) is currently considered
5744** to be experimental.  The interface might change in incompatible ways.
5745** If this is a problem for you, do not use the interface at this time.
5746**
5747** When the virtual-table mechanism stabilizes, we will declare the
5748** interface fixed, support it indefinitely, and remove this comment.
5749*/
5750
5751/*
5752** CAPI3REF: A Handle To An Open BLOB
5753** KEYWORDS: {BLOB handle} {BLOB handles}
5754**
5755** An instance of this object represents an open BLOB on which
5756** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5757** ^Objects of this type are created by [sqlite3_blob_open()]
5758** and destroyed by [sqlite3_blob_close()].
5759** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5760** can be used to read or write small subsections of the BLOB.
5761** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5762*/
5763typedef struct sqlite3_blob sqlite3_blob;
5764
5765/*
5766** CAPI3REF: Open A BLOB For Incremental I/O
5767**
5768** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5769** in row iRow, column zColumn, table zTable in database zDb;
5770** in other words, the same BLOB that would be selected by:
5771**
5772** <pre>
5773**     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5774** </pre>)^
5775**
5776** ^If the flags parameter is non-zero, then the BLOB is opened for read
5777** and write access. ^If it is zero, the BLOB is opened for read access.
5778** ^It is not possible to open a column that is part of an index or primary
5779** key for writing. ^If [foreign key constraints] are enabled, it is
5780** not possible to open a column that is part of a [child key] for writing.
5781**
5782** ^Note that the database name is not the filename that contains
5783** the database but rather the symbolic name of the database that
5784** appears after the AS keyword when the database is connected using [ATTACH].
5785** ^For the main database file, the database name is "main".
5786** ^For TEMP tables, the database name is "temp".
5787**
5788** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
5789** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
5790** to be a null pointer.)^
5791** ^This function sets the [database connection] error code and message
5792** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5793** functions. ^Note that the *ppBlob variable is always initialized in a
5794** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5795** regardless of the success or failure of this routine.
5796**
5797** ^(If the row that a BLOB handle points to is modified by an
5798** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5799** then the BLOB handle is marked as "expired".
5800** This is true if any column of the row is changed, even a column
5801** other than the one the BLOB handle is open on.)^
5802** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5803** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5804** ^(Changes written into a BLOB prior to the BLOB expiring are not
5805** rolled back by the expiration of the BLOB.  Such changes will eventually
5806** commit if the transaction continues to completion.)^
5807**
5808** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5809** the opened blob.  ^The size of a blob may not be changed by this
5810** interface.  Use the [UPDATE] SQL command to change the size of a
5811** blob.
5812**
5813** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5814** and the built-in [zeroblob] SQL function can be used, if desired,
5815** to create an empty, zero-filled blob in which to read or write using
5816** this interface.
5817**
5818** To avoid a resource leak, every open [BLOB handle] should eventually
5819** be released by a call to [sqlite3_blob_close()].
5820*/
5821SQLITE_API int sqlite3_blob_open(
5822  sqlite3*,
5823  const char *zDb,
5824  const char *zTable,
5825  const char *zColumn,
5826  sqlite3_int64 iRow,
5827  int flags,
5828  sqlite3_blob **ppBlob
5829);
5830
5831/*
5832** CAPI3REF: Move a BLOB Handle to a New Row
5833**
5834** ^This function is used to move an existing blob handle so that it points
5835** to a different row of the same database table. ^The new row is identified
5836** by the rowid value passed as the second argument. Only the row can be
5837** changed. ^The database, table and column on which the blob handle is open
5838** remain the same. Moving an existing blob handle to a new row can be
5839** faster than closing the existing handle and opening a new one.
5840**
5841** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
5842** it must exist and there must be either a blob or text value stored in
5843** the nominated column.)^ ^If the new row is not present in the table, or if
5844** it does not contain a blob or text value, or if another error occurs, an
5845** SQLite error code is returned and the blob handle is considered aborted.
5846** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
5847** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
5848** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
5849** always returns zero.
5850**
5851** ^This function sets the database handle error code and message.
5852*/
5853SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
5854
5855/*
5856** CAPI3REF: Close A BLOB Handle
5857**
5858** ^Closes an open [BLOB handle].
5859**
5860** ^Closing a BLOB shall cause the current transaction to commit
5861** if there are no other BLOBs, no pending prepared statements, and the
5862** database connection is in [autocommit mode].
5863** ^If any writes were made to the BLOB, they might be held in cache
5864** until the close operation if they will fit.
5865**
5866** ^(Closing the BLOB often forces the changes
5867** out to disk and so if any I/O errors occur, they will likely occur
5868** at the time when the BLOB is closed.  Any errors that occur during
5869** closing are reported as a non-zero return value.)^
5870**
5871** ^(The BLOB is closed unconditionally.  Even if this routine returns
5872** an error code, the BLOB is still closed.)^
5873**
5874** ^Calling this routine with a null pointer (such as would be returned
5875** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5876*/
5877SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5878
5879/*
5880** CAPI3REF: Return The Size Of An Open BLOB
5881**
5882** ^Returns the size in bytes of the BLOB accessible via the
5883** successfully opened [BLOB handle] in its only argument.  ^The
5884** incremental blob I/O routines can only read or overwriting existing
5885** blob content; they cannot change the size of a blob.
5886**
5887** This routine only works on a [BLOB handle] which has been created
5888** by a prior successful call to [sqlite3_blob_open()] and which has not
5889** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5890** to this routine results in undefined and probably undesirable behavior.
5891*/
5892SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5893
5894/*
5895** CAPI3REF: Read Data From A BLOB Incrementally
5896**
5897** ^(This function is used to read data from an open [BLOB handle] into a
5898** caller-supplied buffer. N bytes of data are copied into buffer Z
5899** from the open BLOB, starting at offset iOffset.)^
5900**
5901** ^If offset iOffset is less than N bytes from the end of the BLOB,
5902** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5903** less than zero, [SQLITE_ERROR] is returned and no data is read.
5904** ^The size of the blob (and hence the maximum value of N+iOffset)
5905** can be determined using the [sqlite3_blob_bytes()] interface.
5906**
5907** ^An attempt to read from an expired [BLOB handle] fails with an
5908** error code of [SQLITE_ABORT].
5909**
5910** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5911** Otherwise, an [error code] or an [extended error code] is returned.)^
5912**
5913** This routine only works on a [BLOB handle] which has been created
5914** by a prior successful call to [sqlite3_blob_open()] and which has not
5915** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5916** to this routine results in undefined and probably undesirable behavior.
5917**
5918** See also: [sqlite3_blob_write()].
5919*/
5920SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5921
5922/*
5923** CAPI3REF: Write Data Into A BLOB Incrementally
5924**
5925** ^This function is used to write data into an open [BLOB handle] from a
5926** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5927** into the open BLOB, starting at offset iOffset.
5928**
5929** ^If the [BLOB handle] passed as the first argument was not opened for
5930** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5931** this function returns [SQLITE_READONLY].
5932**
5933** ^This function may only modify the contents of the BLOB; it is
5934** not possible to increase the size of a BLOB using this API.
5935** ^If offset iOffset is less than N bytes from the end of the BLOB,
5936** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5937** less than zero [SQLITE_ERROR] is returned and no data is written.
5938** The size of the BLOB (and hence the maximum value of N+iOffset)
5939** can be determined using the [sqlite3_blob_bytes()] interface.
5940**
5941** ^An attempt to write to an expired [BLOB handle] fails with an
5942** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5943** before the [BLOB handle] expired are not rolled back by the
5944** expiration of the handle, though of course those changes might
5945** have been overwritten by the statement that expired the BLOB handle
5946** or by other independent statements.
5947**
5948** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5949** Otherwise, an  [error code] or an [extended error code] is returned.)^
5950**
5951** This routine only works on a [BLOB handle] which has been created
5952** by a prior successful call to [sqlite3_blob_open()] and which has not
5953** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5954** to this routine results in undefined and probably undesirable behavior.
5955**
5956** See also: [sqlite3_blob_read()].
5957*/
5958SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5959
5960/*
5961** CAPI3REF: Virtual File System Objects
5962**
5963** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5964** that SQLite uses to interact
5965** with the underlying operating system.  Most SQLite builds come with a
5966** single default VFS that is appropriate for the host computer.
5967** New VFSes can be registered and existing VFSes can be unregistered.
5968** The following interfaces are provided.
5969**
5970** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5971** ^Names are case sensitive.
5972** ^Names are zero-terminated UTF-8 strings.
5973** ^If there is no match, a NULL pointer is returned.
5974** ^If zVfsName is NULL then the default VFS is returned.
5975**
5976** ^New VFSes are registered with sqlite3_vfs_register().
5977** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5978** ^The same VFS can be registered multiple times without injury.
5979** ^To make an existing VFS into the default VFS, register it again
5980** with the makeDflt flag set.  If two different VFSes with the
5981** same name are registered, the behavior is undefined.  If a
5982** VFS is registered with a name that is NULL or an empty string,
5983** then the behavior is undefined.
5984**
5985** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5986** ^(If the default VFS is unregistered, another VFS is chosen as
5987** the default.  The choice for the new VFS is arbitrary.)^
5988*/
5989SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5990SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5991SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5992
5993/*
5994** CAPI3REF: Mutexes
5995**
5996** The SQLite core uses these routines for thread
5997** synchronization. Though they are intended for internal
5998** use by SQLite, code that links against SQLite is
5999** permitted to use any of these routines.
6000**
6001** The SQLite source code contains multiple implementations
6002** of these mutex routines.  An appropriate implementation
6003** is selected automatically at compile-time.  ^(The following
6004** implementations are available in the SQLite core:
6005**
6006** <ul>
6007** <li>   SQLITE_MUTEX_OS2
6008** <li>   SQLITE_MUTEX_PTHREADS
6009** <li>   SQLITE_MUTEX_W32
6010** <li>   SQLITE_MUTEX_NOOP
6011** </ul>)^
6012**
6013** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6014** that does no real locking and is appropriate for use in
6015** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
6016** SQLITE_MUTEX_PTHREADS, and SQLITE_MUTEX_W32 implementations
6017** are appropriate for use on OS/2, Unix, and Windows.
6018**
6019** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6020** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6021** implementation is included with the library. In this case the
6022** application must supply a custom mutex implementation using the
6023** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6024** before calling sqlite3_initialize() or any other public sqlite3_
6025** function that calls sqlite3_initialize().)^
6026**
6027** ^The sqlite3_mutex_alloc() routine allocates a new
6028** mutex and returns a pointer to it. ^If it returns NULL
6029** that means that a mutex could not be allocated.  ^SQLite
6030** will unwind its stack and return an error.  ^(The argument
6031** to sqlite3_mutex_alloc() is one of these integer constants:
6032**
6033** <ul>
6034** <li>  SQLITE_MUTEX_FAST
6035** <li>  SQLITE_MUTEX_RECURSIVE
6036** <li>  SQLITE_MUTEX_STATIC_MASTER
6037** <li>  SQLITE_MUTEX_STATIC_MEM
6038** <li>  SQLITE_MUTEX_STATIC_MEM2
6039** <li>  SQLITE_MUTEX_STATIC_PRNG
6040** <li>  SQLITE_MUTEX_STATIC_LRU
6041** <li>  SQLITE_MUTEX_STATIC_LRU2
6042** </ul>)^
6043**
6044** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6045** cause sqlite3_mutex_alloc() to create
6046** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6047** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6048** The mutex implementation does not need to make a distinction
6049** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6050** not want to.  ^SQLite will only request a recursive mutex in
6051** cases where it really needs one.  ^If a faster non-recursive mutex
6052** implementation is available on the host platform, the mutex subsystem
6053** might return such a mutex in response to SQLITE_MUTEX_FAST.
6054**
6055** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6056** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6057** a pointer to a static preexisting mutex.  ^Six static mutexes are
6058** used by the current version of SQLite.  Future versions of SQLite
6059** may add additional static mutexes.  Static mutexes are for internal
6060** use by SQLite only.  Applications that use SQLite mutexes should
6061** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6062** SQLITE_MUTEX_RECURSIVE.
6063**
6064** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6065** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6066** returns a different mutex on every call.  ^But for the static
6067** mutex types, the same mutex is returned on every call that has
6068** the same type number.
6069**
6070** ^The sqlite3_mutex_free() routine deallocates a previously
6071** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6072** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6073** use when they are deallocated.  Attempting to deallocate a static
6074** mutex results in undefined behavior.  ^SQLite never deallocates
6075** a static mutex.
6076**
6077** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6078** to enter a mutex.  ^If another thread is already within the mutex,
6079** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6080** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6081** upon successful entry.  ^(Mutexes created using
6082** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6083** In such cases the,
6084** mutex must be exited an equal number of times before another thread
6085** can enter.)^  ^(If the same thread tries to enter any other
6086** kind of mutex more than once, the behavior is undefined.
6087** SQLite will never exhibit
6088** such behavior in its own use of mutexes.)^
6089**
6090** ^(Some systems (for example, Windows 95) do not support the operation
6091** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6092** will always return SQLITE_BUSY.  The SQLite core only ever uses
6093** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6094**
6095** ^The sqlite3_mutex_leave() routine exits a mutex that was
6096** previously entered by the same thread.   ^(The behavior
6097** is undefined if the mutex is not currently entered by the
6098** calling thread or is not currently allocated.  SQLite will
6099** never do either.)^
6100**
6101** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6102** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6103** behave as no-ops.
6104**
6105** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6106*/
6107SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6108SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6109SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6110SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6111SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6112
6113/*
6114** CAPI3REF: Mutex Methods Object
6115**
6116** An instance of this structure defines the low-level routines
6117** used to allocate and use mutexes.
6118**
6119** Usually, the default mutex implementations provided by SQLite are
6120** sufficient, however the user has the option of substituting a custom
6121** implementation for specialized deployments or systems for which SQLite
6122** does not provide a suitable implementation. In this case, the user
6123** creates and populates an instance of this structure to pass
6124** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6125** Additionally, an instance of this structure can be used as an
6126** output variable when querying the system for the current mutex
6127** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6128**
6129** ^The xMutexInit method defined by this structure is invoked as
6130** part of system initialization by the sqlite3_initialize() function.
6131** ^The xMutexInit routine is called by SQLite exactly once for each
6132** effective call to [sqlite3_initialize()].
6133**
6134** ^The xMutexEnd method defined by this structure is invoked as
6135** part of system shutdown by the sqlite3_shutdown() function. The
6136** implementation of this method is expected to release all outstanding
6137** resources obtained by the mutex methods implementation, especially
6138** those obtained by the xMutexInit method.  ^The xMutexEnd()
6139** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6140**
6141** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6142** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6143** xMutexNotheld) implement the following interfaces (respectively):
6144**
6145** <ul>
6146**   <li>  [sqlite3_mutex_alloc()] </li>
6147**   <li>  [sqlite3_mutex_free()] </li>
6148**   <li>  [sqlite3_mutex_enter()] </li>
6149**   <li>  [sqlite3_mutex_try()] </li>
6150**   <li>  [sqlite3_mutex_leave()] </li>
6151**   <li>  [sqlite3_mutex_held()] </li>
6152**   <li>  [sqlite3_mutex_notheld()] </li>
6153** </ul>)^
6154**
6155** The only difference is that the public sqlite3_XXX functions enumerated
6156** above silently ignore any invocations that pass a NULL pointer instead
6157** of a valid mutex handle. The implementations of the methods defined
6158** by this structure are not required to handle this case, the results
6159** of passing a NULL pointer instead of a valid mutex handle are undefined
6160** (i.e. it is acceptable to provide an implementation that segfaults if
6161** it is passed a NULL pointer).
6162**
6163** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6164** invoke xMutexInit() multiple times within the same process and without
6165** intervening calls to xMutexEnd().  Second and subsequent calls to
6166** xMutexInit() must be no-ops.
6167**
6168** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6169** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6170** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6171** memory allocation for a fast or recursive mutex.
6172**
6173** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6174** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6175** If xMutexInit fails in any way, it is expected to clean up after itself
6176** prior to returning.
6177*/
6178typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6179struct sqlite3_mutex_methods {
6180  int (*xMutexInit)(void);
6181  int (*xMutexEnd)(void);
6182  sqlite3_mutex *(*xMutexAlloc)(int);
6183  void (*xMutexFree)(sqlite3_mutex *);
6184  void (*xMutexEnter)(sqlite3_mutex *);
6185  int (*xMutexTry)(sqlite3_mutex *);
6186  void (*xMutexLeave)(sqlite3_mutex *);
6187  int (*xMutexHeld)(sqlite3_mutex *);
6188  int (*xMutexNotheld)(sqlite3_mutex *);
6189};
6190
6191/*
6192** CAPI3REF: Mutex Verification Routines
6193**
6194** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6195** are intended for use inside assert() statements.  ^The SQLite core
6196** never uses these routines except inside an assert() and applications
6197** are advised to follow the lead of the core.  ^The SQLite core only
6198** provides implementations for these routines when it is compiled
6199** with the SQLITE_DEBUG flag.  ^External mutex implementations
6200** are only required to provide these routines if SQLITE_DEBUG is
6201** defined and if NDEBUG is not defined.
6202**
6203** ^These routines should return true if the mutex in their argument
6204** is held or not held, respectively, by the calling thread.
6205**
6206** ^The implementation is not required to provide versions of these
6207** routines that actually work. If the implementation does not provide working
6208** versions of these routines, it should at least provide stubs that always
6209** return true so that one does not get spurious assertion failures.
6210**
6211** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6212** the routine should return 1.   This seems counter-intuitive since
6213** clearly the mutex cannot be held if it does not exist.  But
6214** the reason the mutex does not exist is because the build is not
6215** using mutexes.  And we do not want the assert() containing the
6216** call to sqlite3_mutex_held() to fail, so a non-zero return is
6217** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6218** interface should also return 1 when given a NULL pointer.
6219*/
6220#ifndef NDEBUG
6221SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6222SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6223#endif
6224
6225/*
6226** CAPI3REF: Mutex Types
6227**
6228** The [sqlite3_mutex_alloc()] interface takes a single argument
6229** which is one of these integer constants.
6230**
6231** The set of static mutexes may change from one SQLite release to the
6232** next.  Applications that override the built-in mutex logic must be
6233** prepared to accommodate additional static mutexes.
6234*/
6235#define SQLITE_MUTEX_FAST             0
6236#define SQLITE_MUTEX_RECURSIVE        1
6237#define SQLITE_MUTEX_STATIC_MASTER    2
6238#define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6239#define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6240#define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6241#define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6242#define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6243#define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6244#define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6245
6246/*
6247** CAPI3REF: Retrieve the mutex for a database connection
6248**
6249** ^This interface returns a pointer the [sqlite3_mutex] object that
6250** serializes access to the [database connection] given in the argument
6251** when the [threading mode] is Serialized.
6252** ^If the [threading mode] is Single-thread or Multi-thread then this
6253** routine returns a NULL pointer.
6254*/
6255SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6256
6257/*
6258** CAPI3REF: Low-Level Control Of Database Files
6259**
6260** ^The [sqlite3_file_control()] interface makes a direct call to the
6261** xFileControl method for the [sqlite3_io_methods] object associated
6262** with a particular database identified by the second argument. ^The
6263** name of the database is "main" for the main database or "temp" for the
6264** TEMP database, or the name that appears after the AS keyword for
6265** databases that are added using the [ATTACH] SQL command.
6266** ^A NULL pointer can be used in place of "main" to refer to the
6267** main database file.
6268** ^The third and fourth parameters to this routine
6269** are passed directly through to the second and third parameters of
6270** the xFileControl method.  ^The return value of the xFileControl
6271** method becomes the return value of this routine.
6272**
6273** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6274** a pointer to the underlying [sqlite3_file] object to be written into
6275** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6276** case is a short-circuit path which does not actually invoke the
6277** underlying sqlite3_io_methods.xFileControl method.
6278**
6279** ^If the second parameter (zDbName) does not match the name of any
6280** open database file, then SQLITE_ERROR is returned.  ^This error
6281** code is not remembered and will not be recalled by [sqlite3_errcode()]
6282** or [sqlite3_errmsg()].  The underlying xFileControl method might
6283** also return SQLITE_ERROR.  There is no way to distinguish between
6284** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6285** xFileControl method.
6286**
6287** See also: [SQLITE_FCNTL_LOCKSTATE]
6288*/
6289SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6290
6291/*
6292** CAPI3REF: Testing Interface
6293**
6294** ^The sqlite3_test_control() interface is used to read out internal
6295** state of SQLite and to inject faults into SQLite for testing
6296** purposes.  ^The first parameter is an operation code that determines
6297** the number, meaning, and operation of all subsequent parameters.
6298**
6299** This interface is not for use by applications.  It exists solely
6300** for verifying the correct operation of the SQLite library.  Depending
6301** on how the SQLite library is compiled, this interface might not exist.
6302**
6303** The details of the operation codes, their meanings, the parameters
6304** they take, and what they do are all subject to change without notice.
6305** Unlike most of the SQLite API, this function is not guaranteed to
6306** operate consistently from one release to the next.
6307*/
6308SQLITE_API int sqlite3_test_control(int op, ...);
6309
6310/*
6311** CAPI3REF: Testing Interface Operation Codes
6312**
6313** These constants are the valid operation code parameters used
6314** as the first argument to [sqlite3_test_control()].
6315**
6316** These parameters and their meanings are subject to change
6317** without notice.  These values are for testing purposes only.
6318** Applications should not use any of these parameters or the
6319** [sqlite3_test_control()] interface.
6320*/
6321#define SQLITE_TESTCTRL_FIRST                    5
6322#define SQLITE_TESTCTRL_PRNG_SAVE                5
6323#define SQLITE_TESTCTRL_PRNG_RESTORE             6
6324#define SQLITE_TESTCTRL_PRNG_RESET               7
6325#define SQLITE_TESTCTRL_BITVEC_TEST              8
6326#define SQLITE_TESTCTRL_FAULT_INSTALL            9
6327#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6328#define SQLITE_TESTCTRL_PENDING_BYTE            11
6329#define SQLITE_TESTCTRL_ASSERT                  12
6330#define SQLITE_TESTCTRL_ALWAYS                  13
6331#define SQLITE_TESTCTRL_RESERVE                 14
6332#define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6333#define SQLITE_TESTCTRL_ISKEYWORD               16
6334#define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6335#define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6336#define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6337#define SQLITE_TESTCTRL_LAST                    19
6338
6339/*
6340** CAPI3REF: SQLite Runtime Status
6341**
6342** ^This interface is used to retrieve runtime status information
6343** about the performance of SQLite, and optionally to reset various
6344** highwater marks.  ^The first argument is an integer code for
6345** the specific parameter to measure.  ^(Recognized integer codes
6346** are of the form [status parameters | SQLITE_STATUS_...].)^
6347** ^The current value of the parameter is returned into *pCurrent.
6348** ^The highest recorded value is returned in *pHighwater.  ^If the
6349** resetFlag is true, then the highest record value is reset after
6350** *pHighwater is written.  ^(Some parameters do not record the highest
6351** value.  For those parameters
6352** nothing is written into *pHighwater and the resetFlag is ignored.)^
6353** ^(Other parameters record only the highwater mark and not the current
6354** value.  For these latter parameters nothing is written into *pCurrent.)^
6355**
6356** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6357** non-zero [error code] on failure.
6358**
6359** This routine is threadsafe but is not atomic.  This routine can be
6360** called while other threads are running the same or different SQLite
6361** interfaces.  However the values returned in *pCurrent and
6362** *pHighwater reflect the status of SQLite at different points in time
6363** and it is possible that another thread might change the parameter
6364** in between the times when *pCurrent and *pHighwater are written.
6365**
6366** See also: [sqlite3_db_status()]
6367*/
6368SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6369
6370
6371/*
6372** CAPI3REF: Status Parameters
6373** KEYWORDS: {status parameters}
6374**
6375** These integer constants designate various run-time status parameters
6376** that can be returned by [sqlite3_status()].
6377**
6378** <dl>
6379** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6380** <dd>This parameter is the current amount of memory checked out
6381** using [sqlite3_malloc()], either directly or indirectly.  The
6382** figure includes calls made to [sqlite3_malloc()] by the application
6383** and internal memory usage by the SQLite library.  Scratch memory
6384** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6385** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6386** this parameter.  The amount returned is the sum of the allocation
6387** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6388**
6389** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6390** <dd>This parameter records the largest memory allocation request
6391** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6392** internal equivalents).  Only the value returned in the
6393** *pHighwater parameter to [sqlite3_status()] is of interest.
6394** The value written into the *pCurrent parameter is undefined.</dd>)^
6395**
6396** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6397** <dd>This parameter records the number of separate memory allocations
6398** currently checked out.</dd>)^
6399**
6400** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6401** <dd>This parameter returns the number of pages used out of the
6402** [pagecache memory allocator] that was configured using
6403** [SQLITE_CONFIG_PAGECACHE].  The
6404** value returned is in pages, not in bytes.</dd>)^
6405**
6406** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6407** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6408** <dd>This parameter returns the number of bytes of page cache
6409** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6410** buffer and where forced to overflow to [sqlite3_malloc()].  The
6411** returned value includes allocations that overflowed because they
6412** where too large (they were larger than the "sz" parameter to
6413** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6414** no space was left in the page cache.</dd>)^
6415**
6416** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6417** <dd>This parameter records the largest memory allocation request
6418** handed to [pagecache memory allocator].  Only the value returned in the
6419** *pHighwater parameter to [sqlite3_status()] is of interest.
6420** The value written into the *pCurrent parameter is undefined.</dd>)^
6421**
6422** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6423** <dd>This parameter returns the number of allocations used out of the
6424** [scratch memory allocator] configured using
6425** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6426** in bytes.  Since a single thread may only have one scratch allocation
6427** outstanding at time, this parameter also reports the number of threads
6428** using scratch memory at the same time.</dd>)^
6429**
6430** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6431** <dd>This parameter returns the number of bytes of scratch memory
6432** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6433** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6434** returned include overflows because the requested allocation was too
6435** larger (that is, because the requested allocation was larger than the
6436** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6437** slots were available.
6438** </dd>)^
6439**
6440** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6441** <dd>This parameter records the largest memory allocation request
6442** handed to [scratch memory allocator].  Only the value returned in the
6443** *pHighwater parameter to [sqlite3_status()] is of interest.
6444** The value written into the *pCurrent parameter is undefined.</dd>)^
6445**
6446** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6447** <dd>This parameter records the deepest parser stack.  It is only
6448** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6449** </dl>
6450**
6451** New status parameters may be added from time to time.
6452*/
6453#define SQLITE_STATUS_MEMORY_USED          0
6454#define SQLITE_STATUS_PAGECACHE_USED       1
6455#define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6456#define SQLITE_STATUS_SCRATCH_USED         3
6457#define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6458#define SQLITE_STATUS_MALLOC_SIZE          5
6459#define SQLITE_STATUS_PARSER_STACK         6
6460#define SQLITE_STATUS_PAGECACHE_SIZE       7
6461#define SQLITE_STATUS_SCRATCH_SIZE         8
6462#define SQLITE_STATUS_MALLOC_COUNT         9
6463
6464/*
6465** CAPI3REF: Database Connection Status
6466**
6467** ^This interface is used to retrieve runtime status information
6468** about a single [database connection].  ^The first argument is the
6469** database connection object to be interrogated.  ^The second argument
6470** is an integer constant, taken from the set of
6471** [SQLITE_DBSTATUS options], that
6472** determines the parameter to interrogate.  The set of
6473** [SQLITE_DBSTATUS options] is likely
6474** to grow in future releases of SQLite.
6475**
6476** ^The current value of the requested parameter is written into *pCur
6477** and the highest instantaneous value is written into *pHiwtr.  ^If
6478** the resetFlg is true, then the highest instantaneous value is
6479** reset back down to the current value.
6480**
6481** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6482** non-zero [error code] on failure.
6483**
6484** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6485*/
6486SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6487
6488/*
6489** CAPI3REF: Status Parameters for database connections
6490** KEYWORDS: {SQLITE_DBSTATUS options}
6491**
6492** These constants are the available integer "verbs" that can be passed as
6493** the second argument to the [sqlite3_db_status()] interface.
6494**
6495** New verbs may be added in future releases of SQLite. Existing verbs
6496** might be discontinued. Applications should check the return code from
6497** [sqlite3_db_status()] to make sure that the call worked.
6498** The [sqlite3_db_status()] interface will return a non-zero error code
6499** if a discontinued or unsupported verb is invoked.
6500**
6501** <dl>
6502** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6503** <dd>This parameter returns the number of lookaside memory slots currently
6504** checked out.</dd>)^
6505**
6506** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6507** <dd>This parameter returns the number malloc attempts that were
6508** satisfied using lookaside memory. Only the high-water value is meaningful;
6509** the current value is always zero.)^
6510**
6511** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6512** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6513** <dd>This parameter returns the number malloc attempts that might have
6514** been satisfied using lookaside memory but failed due to the amount of
6515** memory requested being larger than the lookaside slot size.
6516** Only the high-water value is meaningful;
6517** the current value is always zero.)^
6518**
6519** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6520** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6521** <dd>This parameter returns the number malloc attempts that might have
6522** been satisfied using lookaside memory but failed due to all lookaside
6523** memory already being in use.
6524** Only the high-water value is meaningful;
6525** the current value is always zero.)^
6526**
6527** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6528** <dd>This parameter returns the approximate number of of bytes of heap
6529** memory used by all pager caches associated with the database connection.)^
6530** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6531**
6532** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6533** <dd>This parameter returns the approximate number of of bytes of heap
6534** memory used to store the schema for all databases associated
6535** with the connection - main, temp, and any [ATTACH]-ed databases.)^
6536** ^The full amount of memory used by the schemas is reported, even if the
6537** schema memory is shared with other database connections due to
6538** [shared cache mode] being enabled.
6539** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6540**
6541** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6542** <dd>This parameter returns the approximate number of of bytes of heap
6543** and lookaside memory used by all prepared statements associated with
6544** the database connection.)^
6545** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6546** </dd>
6547**
6548** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6549** <dd>This parameter returns the number of pager cache hits that have
6550** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
6551** is always 0.
6552** </dd>
6553**
6554** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6555** <dd>This parameter returns the number of pager cache misses that have
6556** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
6557** is always 0.
6558** </dd>
6559** </dl>
6560*/
6561#define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6562#define SQLITE_DBSTATUS_CACHE_USED           1
6563#define SQLITE_DBSTATUS_SCHEMA_USED          2
6564#define SQLITE_DBSTATUS_STMT_USED            3
6565#define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6566#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6567#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6568#define SQLITE_DBSTATUS_CACHE_HIT            7
6569#define SQLITE_DBSTATUS_CACHE_MISS           8
6570#define SQLITE_DBSTATUS_MAX                  8   /* Largest defined DBSTATUS */
6571
6572
6573/*
6574** CAPI3REF: Prepared Statement Status
6575**
6576** ^(Each prepared statement maintains various
6577** [SQLITE_STMTSTATUS counters] that measure the number
6578** of times it has performed specific operations.)^  These counters can
6579** be used to monitor the performance characteristics of the prepared
6580** statements.  For example, if the number of table steps greatly exceeds
6581** the number of table searches or result rows, that would tend to indicate
6582** that the prepared statement is using a full table scan rather than
6583** an index.
6584**
6585** ^(This interface is used to retrieve and reset counter values from
6586** a [prepared statement].  The first argument is the prepared statement
6587** object to be interrogated.  The second argument
6588** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6589** to be interrogated.)^
6590** ^The current value of the requested counter is returned.
6591** ^If the resetFlg is true, then the counter is reset to zero after this
6592** interface call returns.
6593**
6594** See also: [sqlite3_status()] and [sqlite3_db_status()].
6595*/
6596SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6597
6598/*
6599** CAPI3REF: Status Parameters for prepared statements
6600** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6601**
6602** These preprocessor macros define integer codes that name counter
6603** values associated with the [sqlite3_stmt_status()] interface.
6604** The meanings of the various counters are as follows:
6605**
6606** <dl>
6607** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6608** <dd>^This is the number of times that SQLite has stepped forward in
6609** a table as part of a full table scan.  Large numbers for this counter
6610** may indicate opportunities for performance improvement through
6611** careful use of indices.</dd>
6612**
6613** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6614** <dd>^This is the number of sort operations that have occurred.
6615** A non-zero value in this counter may indicate an opportunity to
6616** improvement performance through careful use of indices.</dd>
6617**
6618** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6619** <dd>^This is the number of rows inserted into transient indices that
6620** were created automatically in order to help joins run faster.
6621** A non-zero value in this counter may indicate an opportunity to
6622** improvement performance by adding permanent indices that do not
6623** need to be reinitialized each time the statement is run.</dd>
6624** </dl>
6625*/
6626#define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6627#define SQLITE_STMTSTATUS_SORT              2
6628#define SQLITE_STMTSTATUS_AUTOINDEX         3
6629
6630/*
6631** CAPI3REF: Custom Page Cache Object
6632**
6633** The sqlite3_pcache type is opaque.  It is implemented by
6634** the pluggable module.  The SQLite core has no knowledge of
6635** its size or internal structure and never deals with the
6636** sqlite3_pcache object except by holding and passing pointers
6637** to the object.
6638**
6639** See [sqlite3_pcache_methods2] for additional information.
6640*/
6641typedef struct sqlite3_pcache sqlite3_pcache;
6642
6643/*
6644** CAPI3REF: Custom Page Cache Object
6645**
6646** The sqlite3_pcache_page object represents a single page in the
6647** page cache.  The page cache will allocate instances of this
6648** object.  Various methods of the page cache use pointers to instances
6649** of this object as parameters or as their return value.
6650**
6651** See [sqlite3_pcache_methods2] for additional information.
6652*/
6653typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6654struct sqlite3_pcache_page {
6655  void *pBuf;        /* The content of the page */
6656  void *pExtra;      /* Extra information associated with the page */
6657};
6658
6659/*
6660** CAPI3REF: Application Defined Page Cache.
6661** KEYWORDS: {page cache}
6662**
6663** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6664** register an alternative page cache implementation by passing in an
6665** instance of the sqlite3_pcache_methods2 structure.)^
6666** In many applications, most of the heap memory allocated by
6667** SQLite is used for the page cache.
6668** By implementing a
6669** custom page cache using this API, an application can better control
6670** the amount of memory consumed by SQLite, the way in which
6671** that memory is allocated and released, and the policies used to
6672** determine exactly which parts of a database file are cached and for
6673** how long.
6674**
6675** The alternative page cache mechanism is an
6676** extreme measure that is only needed by the most demanding applications.
6677** The built-in page cache is recommended for most uses.
6678**
6679** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6680** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6681** the application may discard the parameter after the call to
6682** [sqlite3_config()] returns.)^
6683**
6684** [[the xInit() page cache method]]
6685** ^(The xInit() method is called once for each effective
6686** call to [sqlite3_initialize()])^
6687** (usually only once during the lifetime of the process). ^(The xInit()
6688** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6689** The intent of the xInit() method is to set up global data structures
6690** required by the custom page cache implementation.
6691** ^(If the xInit() method is NULL, then the
6692** built-in default page cache is used instead of the application defined
6693** page cache.)^
6694**
6695** [[the xShutdown() page cache method]]
6696** ^The xShutdown() method is called by [sqlite3_shutdown()].
6697** It can be used to clean up
6698** any outstanding resources before process shutdown, if required.
6699** ^The xShutdown() method may be NULL.
6700**
6701** ^SQLite automatically serializes calls to the xInit method,
6702** so the xInit method need not be threadsafe.  ^The
6703** xShutdown method is only called from [sqlite3_shutdown()] so it does
6704** not need to be threadsafe either.  All other methods must be threadsafe
6705** in multithreaded applications.
6706**
6707** ^SQLite will never invoke xInit() more than once without an intervening
6708** call to xShutdown().
6709**
6710** [[the xCreate() page cache methods]]
6711** ^SQLite invokes the xCreate() method to construct a new cache instance.
6712** SQLite will typically create one cache instance for each open database file,
6713** though this is not guaranteed. ^The
6714** first parameter, szPage, is the size in bytes of the pages that must
6715** be allocated by the cache.  ^szPage will always a power of two.  ^The
6716** second parameter szExtra is a number of bytes of extra storage
6717** associated with each page cache entry.  ^The szExtra parameter will
6718** a number less than 250.  SQLite will use the
6719** extra szExtra bytes on each page to store metadata about the underlying
6720** database page on disk.  The value passed into szExtra depends
6721** on the SQLite version, the target platform, and how SQLite was compiled.
6722** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6723** created will be used to cache database pages of a file stored on disk, or
6724** false if it is used for an in-memory database. The cache implementation
6725** does not have to do anything special based with the value of bPurgeable;
6726** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6727** never invoke xUnpin() except to deliberately delete a page.
6728** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6729** false will always have the "discard" flag set to true.
6730** ^Hence, a cache created with bPurgeable false will
6731** never contain any unpinned pages.
6732**
6733** [[the xCachesize() page cache method]]
6734** ^(The xCachesize() method may be called at any time by SQLite to set the
6735** suggested maximum cache-size (number of pages stored by) the cache
6736** instance passed as the first argument. This is the value configured using
6737** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6738** parameter, the implementation is not required to do anything with this
6739** value; it is advisory only.
6740**
6741** [[the xPagecount() page cache methods]]
6742** The xPagecount() method must return the number of pages currently
6743** stored in the cache, both pinned and unpinned.
6744**
6745** [[the xFetch() page cache methods]]
6746** The xFetch() method locates a page in the cache and returns a pointer to
6747** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6748** The pBuf element of the returned sqlite3_pcache_page object will be a
6749** pointer to a buffer of szPage bytes used to store the content of a
6750** single database page.  The pExtra element of sqlite3_pcache_page will be
6751** a pointer to the szExtra bytes of extra storage that SQLite has requested
6752** for each entry in the page cache.
6753**
6754** The page to be fetched is determined by the key. ^The minimum key value
6755** is 1.  After it has been retrieved using xFetch, the page is considered
6756** to be "pinned".
6757**
6758** If the requested page is already in the page cache, then the page cache
6759** implementation must return a pointer to the page buffer with its content
6760** intact.  If the requested page is not already in the cache, then the
6761** cache implementation should use the value of the createFlag
6762** parameter to help it determined what action to take:
6763**
6764** <table border=1 width=85% align=center>
6765** <tr><th> createFlag <th> Behaviour when page is not already in cache
6766** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6767** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6768**                 Otherwise return NULL.
6769** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6770**                 NULL if allocating a new page is effectively impossible.
6771** </table>
6772**
6773** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6774** will only use a createFlag of 2 after a prior call with a createFlag of 1
6775** failed.)^  In between the to xFetch() calls, SQLite may
6776** attempt to unpin one or more cache pages by spilling the content of
6777** pinned pages to disk and synching the operating system disk cache.
6778**
6779** [[the xUnpin() page cache method]]
6780** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6781** as its second argument.  If the third parameter, discard, is non-zero,
6782** then the page must be evicted from the cache.
6783** ^If the discard parameter is
6784** zero, then the page may be discarded or retained at the discretion of
6785** page cache implementation. ^The page cache implementation
6786** may choose to evict unpinned pages at any time.
6787**
6788** The cache must not perform any reference counting. A single
6789** call to xUnpin() unpins the page regardless of the number of prior calls
6790** to xFetch().
6791**
6792** [[the xRekey() page cache methods]]
6793** The xRekey() method is used to change the key value associated with the
6794** page passed as the second argument. If the cache
6795** previously contains an entry associated with newKey, it must be
6796** discarded. ^Any prior cache entry associated with newKey is guaranteed not
6797** to be pinned.
6798**
6799** When SQLite calls the xTruncate() method, the cache must discard all
6800** existing cache entries with page numbers (keys) greater than or equal
6801** to the value of the iLimit parameter passed to xTruncate(). If any
6802** of these pages are pinned, they are implicitly unpinned, meaning that
6803** they can be safely discarded.
6804**
6805** [[the xDestroy() page cache method]]
6806** ^The xDestroy() method is used to delete a cache allocated by xCreate().
6807** All resources associated with the specified cache should be freed. ^After
6808** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
6809** handle invalid, and will not use it with any other sqlite3_pcache_methods2
6810** functions.
6811**
6812** [[the xShrink() page cache method]]
6813** ^SQLite invokes the xShrink() method when it wants the page cache to
6814** free up as much of heap memory as possible.  The page cache implementation
6815** is not obligated to free any memory, but well-behaved implementations should
6816** do their best.
6817*/
6818typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
6819struct sqlite3_pcache_methods2 {
6820  int iVersion;
6821  void *pArg;
6822  int (*xInit)(void*);
6823  void (*xShutdown)(void*);
6824  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
6825  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6826  int (*xPagecount)(sqlite3_pcache*);
6827  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6828  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
6829  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
6830      unsigned oldKey, unsigned newKey);
6831  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6832  void (*xDestroy)(sqlite3_pcache*);
6833  void (*xShrink)(sqlite3_pcache*);
6834};
6835
6836/*
6837** This is the obsolete pcache_methods object that has now been replaced
6838** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
6839** retained in the header file for backwards compatibility only.
6840*/
6841typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
6842struct sqlite3_pcache_methods {
6843  void *pArg;
6844  int (*xInit)(void*);
6845  void (*xShutdown)(void*);
6846  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
6847  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
6848  int (*xPagecount)(sqlite3_pcache*);
6849  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
6850  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
6851  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
6852  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
6853  void (*xDestroy)(sqlite3_pcache*);
6854};
6855
6856
6857/*
6858** CAPI3REF: Online Backup Object
6859**
6860** The sqlite3_backup object records state information about an ongoing
6861** online backup operation.  ^The sqlite3_backup object is created by
6862** a call to [sqlite3_backup_init()] and is destroyed by a call to
6863** [sqlite3_backup_finish()].
6864**
6865** See Also: [Using the SQLite Online Backup API]
6866*/
6867typedef struct sqlite3_backup sqlite3_backup;
6868
6869/*
6870** CAPI3REF: Online Backup API.
6871**
6872** The backup API copies the content of one database into another.
6873** It is useful either for creating backups of databases or
6874** for copying in-memory databases to or from persistent files.
6875**
6876** See Also: [Using the SQLite Online Backup API]
6877**
6878** ^SQLite holds a write transaction open on the destination database file
6879** for the duration of the backup operation.
6880** ^The source database is read-locked only while it is being read;
6881** it is not locked continuously for the entire backup operation.
6882** ^Thus, the backup may be performed on a live source database without
6883** preventing other database connections from
6884** reading or writing to the source database while the backup is underway.
6885**
6886** ^(To perform a backup operation:
6887**   <ol>
6888**     <li><b>sqlite3_backup_init()</b> is called once to initialize the
6889**         backup,
6890**     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
6891**         the data between the two databases, and finally
6892**     <li><b>sqlite3_backup_finish()</b> is called to release all resources
6893**         associated with the backup operation.
6894**   </ol>)^
6895** There should be exactly one call to sqlite3_backup_finish() for each
6896** successful call to sqlite3_backup_init().
6897**
6898** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
6899**
6900** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
6901** [database connection] associated with the destination database
6902** and the database name, respectively.
6903** ^The database name is "main" for the main database, "temp" for the
6904** temporary database, or the name specified after the AS keyword in
6905** an [ATTACH] statement for an attached database.
6906** ^The S and M arguments passed to
6907** sqlite3_backup_init(D,N,S,M) identify the [database connection]
6908** and database name of the source database, respectively.
6909** ^The source and destination [database connections] (parameters S and D)
6910** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
6911** an error.
6912**
6913** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
6914** returned and an error code and error message are stored in the
6915** destination [database connection] D.
6916** ^The error code and message for the failed call to sqlite3_backup_init()
6917** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
6918** [sqlite3_errmsg16()] functions.
6919** ^A successful call to sqlite3_backup_init() returns a pointer to an
6920** [sqlite3_backup] object.
6921** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
6922** sqlite3_backup_finish() functions to perform the specified backup
6923** operation.
6924**
6925** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
6926**
6927** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
6928** the source and destination databases specified by [sqlite3_backup] object B.
6929** ^If N is negative, all remaining source pages are copied.
6930** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
6931** are still more pages to be copied, then the function returns [SQLITE_OK].
6932** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
6933** from source to destination, then it returns [SQLITE_DONE].
6934** ^If an error occurs while running sqlite3_backup_step(B,N),
6935** then an [error code] is returned. ^As well as [SQLITE_OK] and
6936** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
6937** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
6938** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
6939**
6940** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
6941** <ol>
6942** <li> the destination database was opened read-only, or
6943** <li> the destination database is using write-ahead-log journaling
6944** and the destination and source page sizes differ, or
6945** <li> the destination database is an in-memory database and the
6946** destination and source page sizes differ.
6947** </ol>)^
6948**
6949** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
6950** the [sqlite3_busy_handler | busy-handler function]
6951** is invoked (if one is specified). ^If the
6952** busy-handler returns non-zero before the lock is available, then
6953** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
6954** sqlite3_backup_step() can be retried later. ^If the source
6955** [database connection]
6956** is being used to write to the source database when sqlite3_backup_step()
6957** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
6958** case the call to sqlite3_backup_step() can be retried later on. ^(If
6959** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
6960** [SQLITE_READONLY] is returned, then
6961** there is no point in retrying the call to sqlite3_backup_step(). These
6962** errors are considered fatal.)^  The application must accept
6963** that the backup operation has failed and pass the backup operation handle
6964** to the sqlite3_backup_finish() to release associated resources.
6965**
6966** ^The first call to sqlite3_backup_step() obtains an exclusive lock
6967** on the destination file. ^The exclusive lock is not released until either
6968** sqlite3_backup_finish() is called or the backup operation is complete
6969** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
6970** sqlite3_backup_step() obtains a [shared lock] on the source database that
6971** lasts for the duration of the sqlite3_backup_step() call.
6972** ^Because the source database is not locked between calls to
6973** sqlite3_backup_step(), the source database may be modified mid-way
6974** through the backup process.  ^If the source database is modified by an
6975** external process or via a database connection other than the one being
6976** used by the backup operation, then the backup will be automatically
6977** restarted by the next call to sqlite3_backup_step(). ^If the source
6978** database is modified by the using the same database connection as is used
6979** by the backup operation, then the backup database is automatically
6980** updated at the same time.
6981**
6982** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
6983**
6984** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
6985** application wishes to abandon the backup operation, the application
6986** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6987** ^The sqlite3_backup_finish() interfaces releases all
6988** resources associated with the [sqlite3_backup] object.
6989** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6990** active write-transaction on the destination database is rolled back.
6991** The [sqlite3_backup] object is invalid
6992** and may not be used following a call to sqlite3_backup_finish().
6993**
6994** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6995** sqlite3_backup_step() errors occurred, regardless or whether or not
6996** sqlite3_backup_step() completed.
6997** ^If an out-of-memory condition or IO error occurred during any prior
6998** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6999** sqlite3_backup_finish() returns the corresponding [error code].
7000**
7001** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7002** is not a permanent error and does not affect the return value of
7003** sqlite3_backup_finish().
7004**
7005** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7006** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7007**
7008** ^Each call to sqlite3_backup_step() sets two values inside
7009** the [sqlite3_backup] object: the number of pages still to be backed
7010** up and the total number of pages in the source database file.
7011** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7012** retrieve these two values, respectively.
7013**
7014** ^The values returned by these functions are only updated by
7015** sqlite3_backup_step(). ^If the source database is modified during a backup
7016** operation, then the values are not updated to account for any extra
7017** pages that need to be updated or the size of the source database file
7018** changing.
7019**
7020** <b>Concurrent Usage of Database Handles</b>
7021**
7022** ^The source [database connection] may be used by the application for other
7023** purposes while a backup operation is underway or being initialized.
7024** ^If SQLite is compiled and configured to support threadsafe database
7025** connections, then the source database connection may be used concurrently
7026** from within other threads.
7027**
7028** However, the application must guarantee that the destination
7029** [database connection] is not passed to any other API (by any thread) after
7030** sqlite3_backup_init() is called and before the corresponding call to
7031** sqlite3_backup_finish().  SQLite does not currently check to see
7032** if the application incorrectly accesses the destination [database connection]
7033** and so no error code is reported, but the operations may malfunction
7034** nevertheless.  Use of the destination database connection while a
7035** backup is in progress might also also cause a mutex deadlock.
7036**
7037** If running in [shared cache mode], the application must
7038** guarantee that the shared cache used by the destination database
7039** is not accessed while the backup is running. In practice this means
7040** that the application must guarantee that the disk file being
7041** backed up to is not accessed by any connection within the process,
7042** not just the specific connection that was passed to sqlite3_backup_init().
7043**
7044** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7045** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7046** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7047** APIs are not strictly speaking threadsafe. If they are invoked at the
7048** same time as another thread is invoking sqlite3_backup_step() it is
7049** possible that they return invalid values.
7050*/
7051SQLITE_API sqlite3_backup *sqlite3_backup_init(
7052  sqlite3 *pDest,                        /* Destination database handle */
7053  const char *zDestName,                 /* Destination database name */
7054  sqlite3 *pSource,                      /* Source database handle */
7055  const char *zSourceName                /* Source database name */
7056);
7057SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7058SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7059SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7060SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7061
7062/*
7063** CAPI3REF: Unlock Notification
7064**
7065** ^When running in shared-cache mode, a database operation may fail with
7066** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7067** individual tables within the shared-cache cannot be obtained. See
7068** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7069** ^This API may be used to register a callback that SQLite will invoke
7070** when the connection currently holding the required lock relinquishes it.
7071** ^This API is only available if the library was compiled with the
7072** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7073**
7074** See Also: [Using the SQLite Unlock Notification Feature].
7075**
7076** ^Shared-cache locks are released when a database connection concludes
7077** its current transaction, either by committing it or rolling it back.
7078**
7079** ^When a connection (known as the blocked connection) fails to obtain a
7080** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7081** identity of the database connection (the blocking connection) that
7082** has locked the required resource is stored internally. ^After an
7083** application receives an SQLITE_LOCKED error, it may call the
7084** sqlite3_unlock_notify() method with the blocked connection handle as
7085** the first argument to register for a callback that will be invoked
7086** when the blocking connections current transaction is concluded. ^The
7087** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7088** call that concludes the blocking connections transaction.
7089**
7090** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7091** there is a chance that the blocking connection will have already
7092** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7093** If this happens, then the specified callback is invoked immediately,
7094** from within the call to sqlite3_unlock_notify().)^
7095**
7096** ^If the blocked connection is attempting to obtain a write-lock on a
7097** shared-cache table, and more than one other connection currently holds
7098** a read-lock on the same table, then SQLite arbitrarily selects one of
7099** the other connections to use as the blocking connection.
7100**
7101** ^(There may be at most one unlock-notify callback registered by a
7102** blocked connection. If sqlite3_unlock_notify() is called when the
7103** blocked connection already has a registered unlock-notify callback,
7104** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7105** called with a NULL pointer as its second argument, then any existing
7106** unlock-notify callback is canceled. ^The blocked connections
7107** unlock-notify callback may also be canceled by closing the blocked
7108** connection using [sqlite3_close()].
7109**
7110** The unlock-notify callback is not reentrant. If an application invokes
7111** any sqlite3_xxx API functions from within an unlock-notify callback, a
7112** crash or deadlock may be the result.
7113**
7114** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7115** returns SQLITE_OK.
7116**
7117** <b>Callback Invocation Details</b>
7118**
7119** When an unlock-notify callback is registered, the application provides a
7120** single void* pointer that is passed to the callback when it is invoked.
7121** However, the signature of the callback function allows SQLite to pass
7122** it an array of void* context pointers. The first argument passed to
7123** an unlock-notify callback is a pointer to an array of void* pointers,
7124** and the second is the number of entries in the array.
7125**
7126** When a blocking connections transaction is concluded, there may be
7127** more than one blocked connection that has registered for an unlock-notify
7128** callback. ^If two or more such blocked connections have specified the
7129** same callback function, then instead of invoking the callback function
7130** multiple times, it is invoked once with the set of void* context pointers
7131** specified by the blocked connections bundled together into an array.
7132** This gives the application an opportunity to prioritize any actions
7133** related to the set of unblocked database connections.
7134**
7135** <b>Deadlock Detection</b>
7136**
7137** Assuming that after registering for an unlock-notify callback a
7138** database waits for the callback to be issued before taking any further
7139** action (a reasonable assumption), then using this API may cause the
7140** application to deadlock. For example, if connection X is waiting for
7141** connection Y's transaction to be concluded, and similarly connection
7142** Y is waiting on connection X's transaction, then neither connection
7143** will proceed and the system may remain deadlocked indefinitely.
7144**
7145** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7146** detection. ^If a given call to sqlite3_unlock_notify() would put the
7147** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7148** unlock-notify callback is registered. The system is said to be in
7149** a deadlocked state if connection A has registered for an unlock-notify
7150** callback on the conclusion of connection B's transaction, and connection
7151** B has itself registered for an unlock-notify callback when connection
7152** A's transaction is concluded. ^Indirect deadlock is also detected, so
7153** the system is also considered to be deadlocked if connection B has
7154** registered for an unlock-notify callback on the conclusion of connection
7155** C's transaction, where connection C is waiting on connection A. ^Any
7156** number of levels of indirection are allowed.
7157**
7158** <b>The "DROP TABLE" Exception</b>
7159**
7160** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7161** always appropriate to call sqlite3_unlock_notify(). There is however,
7162** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7163** SQLite checks if there are any currently executing SELECT statements
7164** that belong to the same connection. If there are, SQLITE_LOCKED is
7165** returned. In this case there is no "blocking connection", so invoking
7166** sqlite3_unlock_notify() results in the unlock-notify callback being
7167** invoked immediately. If the application then re-attempts the "DROP TABLE"
7168** or "DROP INDEX" query, an infinite loop might be the result.
7169**
7170** One way around this problem is to check the extended error code returned
7171** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7172** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7173** the special "DROP TABLE/INDEX" case, the extended error code is just
7174** SQLITE_LOCKED.)^
7175*/
7176SQLITE_API int sqlite3_unlock_notify(
7177  sqlite3 *pBlocked,                          /* Waiting connection */
7178  void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7179  void *pNotifyArg                            /* Argument to pass to xNotify */
7180);
7181
7182
7183/*
7184** CAPI3REF: String Comparison
7185**
7186** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7187** and extensions to compare the contents of two buffers containing UTF-8
7188** strings in a case-independent fashion, using the same definition of "case
7189** independence" that SQLite uses internally when comparing identifiers.
7190*/
7191SQLITE_API int sqlite3_stricmp(const char *, const char *);
7192SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7193
7194/*
7195** CAPI3REF: Error Logging Interface
7196**
7197** ^The [sqlite3_log()] interface writes a message into the error log
7198** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7199** ^If logging is enabled, the zFormat string and subsequent arguments are
7200** used with [sqlite3_snprintf()] to generate the final output string.
7201**
7202** The sqlite3_log() interface is intended for use by extensions such as
7203** virtual tables, collating functions, and SQL functions.  While there is
7204** nothing to prevent an application from calling sqlite3_log(), doing so
7205** is considered bad form.
7206**
7207** The zFormat string must not be NULL.
7208**
7209** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7210** will not use dynamically allocated memory.  The log message is stored in
7211** a fixed-length buffer on the stack.  If the log message is longer than
7212** a few hundred characters, it will be truncated to the length of the
7213** buffer.
7214*/
7215SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7216
7217/*
7218** CAPI3REF: Write-Ahead Log Commit Hook
7219**
7220** ^The [sqlite3_wal_hook()] function is used to register a callback that
7221** will be invoked each time a database connection commits data to a
7222** [write-ahead log] (i.e. whenever a transaction is committed in
7223** [journal_mode | journal_mode=WAL mode]).
7224**
7225** ^The callback is invoked by SQLite after the commit has taken place and
7226** the associated write-lock on the database released, so the implementation
7227** may read, write or [checkpoint] the database as required.
7228**
7229** ^The first parameter passed to the callback function when it is invoked
7230** is a copy of the third parameter passed to sqlite3_wal_hook() when
7231** registering the callback. ^The second is a copy of the database handle.
7232** ^The third parameter is the name of the database that was written to -
7233** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7234** is the number of pages currently in the write-ahead log file,
7235** including those that were just committed.
7236**
7237** The callback function should normally return [SQLITE_OK].  ^If an error
7238** code is returned, that error will propagate back up through the
7239** SQLite code base to cause the statement that provoked the callback
7240** to report an error, though the commit will have still occurred. If the
7241** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7242** that does not correspond to any valid SQLite error code, the results
7243** are undefined.
7244**
7245** A single database handle may have at most a single write-ahead log callback
7246** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7247** previously registered write-ahead log callback. ^Note that the
7248** [sqlite3_wal_autocheckpoint()] interface and the
7249** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7250** those overwrite any prior [sqlite3_wal_hook()] settings.
7251*/
7252SQLITE_API void *sqlite3_wal_hook(
7253  sqlite3*,
7254  int(*)(void *,sqlite3*,const char*,int),
7255  void*
7256);
7257
7258/*
7259** CAPI3REF: Configure an auto-checkpoint
7260**
7261** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7262** [sqlite3_wal_hook()] that causes any database on [database connection] D
7263** to automatically [checkpoint]
7264** after committing a transaction if there are N or
7265** more frames in the [write-ahead log] file.  ^Passing zero or
7266** a negative value as the nFrame parameter disables automatic
7267** checkpoints entirely.
7268**
7269** ^The callback registered by this function replaces any existing callback
7270** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7271** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7272** configured by this function.
7273**
7274** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7275** from SQL.
7276**
7277** ^Every new [database connection] defaults to having the auto-checkpoint
7278** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7279** pages.  The use of this interface
7280** is only necessary if the default setting is found to be suboptimal
7281** for a particular application.
7282*/
7283SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7284
7285/*
7286** CAPI3REF: Checkpoint a database
7287**
7288** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7289** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7290** empty string, then a checkpoint is run on all databases of
7291** connection D.  ^If the database connection D is not in
7292** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7293**
7294** ^The [wal_checkpoint pragma] can be used to invoke this interface
7295** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7296** [wal_autocheckpoint pragma] can be used to cause this interface to be
7297** run whenever the WAL reaches a certain size threshold.
7298**
7299** See also: [sqlite3_wal_checkpoint_v2()]
7300*/
7301SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7302
7303/*
7304** CAPI3REF: Checkpoint a database
7305**
7306** Run a checkpoint operation on WAL database zDb attached to database
7307** handle db. The specific operation is determined by the value of the
7308** eMode parameter:
7309**
7310** <dl>
7311** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7312**   Checkpoint as many frames as possible without waiting for any database
7313**   readers or writers to finish. Sync the db file if all frames in the log
7314**   are checkpointed. This mode is the same as calling
7315**   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7316**
7317** <dt>SQLITE_CHECKPOINT_FULL<dd>
7318**   This mode blocks (calls the busy-handler callback) until there is no
7319**   database writer and all readers are reading from the most recent database
7320**   snapshot. It then checkpoints all frames in the log file and syncs the
7321**   database file. This call blocks database writers while it is running,
7322**   but not database readers.
7323**
7324** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7325**   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
7326**   checkpointing the log file it blocks (calls the busy-handler callback)
7327**   until all readers are reading from the database file only. This ensures
7328**   that the next client to write to the database file restarts the log file
7329**   from the beginning. This call blocks database writers while it is running,
7330**   but not database readers.
7331** </dl>
7332**
7333** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7334** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7335** the total number of checkpointed frames (including any that were already
7336** checkpointed when this function is called). *pnLog and *pnCkpt may be
7337** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7338** If no values are available because of an error, they are both set to -1
7339** before returning to communicate this to the caller.
7340**
7341** All calls obtain an exclusive "checkpoint" lock on the database file. If
7342** any other process is running a checkpoint operation at the same time, the
7343** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
7344** busy-handler configured, it will not be invoked in this case.
7345**
7346** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
7347** "writer" lock on the database file. If the writer lock cannot be obtained
7348** immediately, and a busy-handler is configured, it is invoked and the writer
7349** lock retried until either the busy-handler returns 0 or the lock is
7350** successfully obtained. The busy-handler is also invoked while waiting for
7351** database readers as described above. If the busy-handler returns 0 before
7352** the writer lock is obtained or while waiting for database readers, the
7353** checkpoint operation proceeds from that point in the same way as
7354** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7355** without blocking any further. SQLITE_BUSY is returned in this case.
7356**
7357** If parameter zDb is NULL or points to a zero length string, then the
7358** specified operation is attempted on all WAL databases. In this case the
7359** values written to output parameters *pnLog and *pnCkpt are undefined. If
7360** an SQLITE_BUSY error is encountered when processing one or more of the
7361** attached WAL databases, the operation is still attempted on any remaining
7362** attached databases and SQLITE_BUSY is returned to the caller. If any other
7363** error occurs while processing an attached database, processing is abandoned
7364** and the error code returned to the caller immediately. If no error
7365** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7366** databases, SQLITE_OK is returned.
7367**
7368** If database zDb is the name of an attached database that is not in WAL
7369** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7370** zDb is not NULL (or a zero length string) and is not the name of any
7371** attached database, SQLITE_ERROR is returned to the caller.
7372*/
7373SQLITE_API int sqlite3_wal_checkpoint_v2(
7374  sqlite3 *db,                    /* Database handle */
7375  const char *zDb,                /* Name of attached database (or NULL) */
7376  int eMode,                      /* SQLITE_CHECKPOINT_* value */
7377  int *pnLog,                     /* OUT: Size of WAL log in frames */
7378  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7379);
7380
7381/*
7382** CAPI3REF: Checkpoint operation parameters
7383**
7384** These constants can be used as the 3rd parameter to
7385** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7386** documentation for additional information about the meaning and use of
7387** each of these values.
7388*/
7389#define SQLITE_CHECKPOINT_PASSIVE 0
7390#define SQLITE_CHECKPOINT_FULL    1
7391#define SQLITE_CHECKPOINT_RESTART 2
7392
7393/*
7394** CAPI3REF: Virtual Table Interface Configuration
7395**
7396** This function may be called by either the [xConnect] or [xCreate] method
7397** of a [virtual table] implementation to configure
7398** various facets of the virtual table interface.
7399**
7400** If this interface is invoked outside the context of an xConnect or
7401** xCreate virtual table method then the behavior is undefined.
7402**
7403** At present, there is only one option that may be configured using
7404** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7405** may be added in the future.
7406*/
7407SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7408
7409/*
7410** CAPI3REF: Virtual Table Configuration Options
7411**
7412** These macros define the various options to the
7413** [sqlite3_vtab_config()] interface that [virtual table] implementations
7414** can use to customize and optimize their behavior.
7415**
7416** <dl>
7417** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7418** <dd>Calls of the form
7419** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7420** where X is an integer.  If X is zero, then the [virtual table] whose
7421** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7422** support constraints.  In this configuration (which is the default) if
7423** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7424** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7425** specified as part of the users SQL statement, regardless of the actual
7426** ON CONFLICT mode specified.
7427**
7428** If X is non-zero, then the virtual table implementation guarantees
7429** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7430** any modifications to internal or persistent data structures have been made.
7431** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
7432** is able to roll back a statement or database transaction, and abandon
7433** or continue processing the current SQL statement as appropriate.
7434** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7435** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7436** had been ABORT.
7437**
7438** Virtual table implementations that are required to handle OR REPLACE
7439** must do so within the [xUpdate] method. If a call to the
7440** [sqlite3_vtab_on_conflict()] function indicates that the current ON
7441** CONFLICT policy is REPLACE, the virtual table implementation should
7442** silently replace the appropriate rows within the xUpdate callback and
7443** return SQLITE_OK. Or, if this is not possible, it may return
7444** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
7445** constraint handling.
7446** </dl>
7447*/
7448#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7449
7450/*
7451** CAPI3REF: Determine The Virtual Table Conflict Policy
7452**
7453** This function may only be called from within a call to the [xUpdate] method
7454** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7455** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7456** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7457** of the SQL statement that triggered the call to the [xUpdate] method of the
7458** [virtual table].
7459*/
7460SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7461
7462/*
7463** CAPI3REF: Conflict resolution modes
7464**
7465** These constants are returned by [sqlite3_vtab_on_conflict()] to
7466** inform a [virtual table] implementation what the [ON CONFLICT] mode
7467** is for the SQL statement being evaluated.
7468**
7469** Note that the [SQLITE_IGNORE] constant is also used as a potential
7470** return value from the [sqlite3_set_authorizer()] callback and that
7471** [SQLITE_ABORT] is also a [result code].
7472*/
7473#define SQLITE_ROLLBACK 1
7474/* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7475#define SQLITE_FAIL     3
7476/* #define SQLITE_ABORT 4  // Also an error code */
7477#define SQLITE_REPLACE  5
7478
7479
7480
7481/*
7482** Undo the hack that converts floating point types to integer for
7483** builds on processors without floating point support.
7484*/
7485#ifdef SQLITE_OMIT_FLOATING_POINT
7486# undef double
7487#endif
7488
7489#if 0
7490}  /* End of the 'extern "C"' block */
7491#endif
7492#endif
7493
7494/*
7495** 2010 August 30
7496**
7497** The author disclaims copyright to this source code.  In place of
7498** a legal notice, here is a blessing:
7499**
7500**    May you do good and not evil.
7501**    May you find forgiveness for yourself and forgive others.
7502**    May you share freely, never taking more than you give.
7503**
7504*************************************************************************
7505*/
7506
7507#ifndef _SQLITE3RTREE_H_
7508#define _SQLITE3RTREE_H_
7509
7510
7511#if 0
7512extern "C" {
7513#endif
7514
7515typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7516
7517/*
7518** Register a geometry callback named zGeom that can be used as part of an
7519** R-Tree geometry query as follows:
7520**
7521**   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7522*/
7523SQLITE_API int sqlite3_rtree_geometry_callback(
7524  sqlite3 *db,
7525  const char *zGeom,
7526  int (*xGeom)(sqlite3_rtree_geometry *, int nCoord, double *aCoord, int *pRes),
7527  void *pContext
7528);
7529
7530
7531/*
7532** A pointer to a structure of the following type is passed as the first
7533** argument to callbacks registered using rtree_geometry_callback().
7534*/
7535struct sqlite3_rtree_geometry {
7536  void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7537  int nParam;                     /* Size of array aParam[] */
7538  double *aParam;                 /* Parameters passed to SQL geom function */
7539  void *pUser;                    /* Callback implementation user data */
7540  void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7541};
7542
7543
7544#if 0
7545}  /* end of the 'extern "C"' block */
7546#endif
7547
7548#endif  /* ifndef _SQLITE3RTREE_H_ */
7549
7550
7551/************** End of sqlite3.h *********************************************/
7552/************** Continuing where we left off in sqliteInt.h ******************/
7553/************** Include hash.h in the middle of sqliteInt.h ******************/
7554/************** Begin file hash.h ********************************************/
7555/*
7556** 2001 September 22
7557**
7558** The author disclaims copyright to this source code.  In place of
7559** a legal notice, here is a blessing:
7560**
7561**    May you do good and not evil.
7562**    May you find forgiveness for yourself and forgive others.
7563**    May you share freely, never taking more than you give.
7564**
7565*************************************************************************
7566** This is the header file for the generic hash-table implemenation
7567** used in SQLite.
7568*/
7569#ifndef _SQLITE_HASH_H_
7570#define _SQLITE_HASH_H_
7571
7572/* Forward declarations of structures. */
7573typedef struct Hash Hash;
7574typedef struct HashElem HashElem;
7575
7576/* A complete hash table is an instance of the following structure.
7577** The internals of this structure are intended to be opaque -- client
7578** code should not attempt to access or modify the fields of this structure
7579** directly.  Change this structure only by using the routines below.
7580** However, some of the "procedures" and "functions" for modifying and
7581** accessing this structure are really macros, so we can't really make
7582** this structure opaque.
7583**
7584** All elements of the hash table are on a single doubly-linked list.
7585** Hash.first points to the head of this list.
7586**
7587** There are Hash.htsize buckets.  Each bucket points to a spot in
7588** the global doubly-linked list.  The contents of the bucket are the
7589** element pointed to plus the next _ht.count-1 elements in the list.
7590**
7591** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7592** by a linear search of the global list.  For small tables, the
7593** Hash.ht table is never allocated because if there are few elements
7594** in the table, it is faster to do a linear search than to manage
7595** the hash table.
7596*/
7597struct Hash {
7598  unsigned int htsize;      /* Number of buckets in the hash table */
7599  unsigned int count;       /* Number of entries in this table */
7600  HashElem *first;          /* The first element of the array */
7601  struct _ht {              /* the hash table */
7602    int count;                 /* Number of entries with this hash */
7603    HashElem *chain;           /* Pointer to first entry with this hash */
7604  } *ht;
7605};
7606
7607/* Each element in the hash table is an instance of the following
7608** structure.  All elements are stored on a single doubly-linked list.
7609**
7610** Again, this structure is intended to be opaque, but it can't really
7611** be opaque because it is used by macros.
7612*/
7613struct HashElem {
7614  HashElem *next, *prev;       /* Next and previous elements in the table */
7615  void *data;                  /* Data associated with this element */
7616  const char *pKey; int nKey;  /* Key associated with this element */
7617};
7618
7619/*
7620** Access routines.  To delete, insert a NULL pointer.
7621*/
7622SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7623SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7624SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7625SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7626
7627/*
7628** Macros for looping over all elements of a hash table.  The idiom is
7629** like this:
7630**
7631**   Hash h;
7632**   HashElem *p;
7633**   ...
7634**   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7635**     SomeStructure *pData = sqliteHashData(p);
7636**     // do something with pData
7637**   }
7638*/
7639#define sqliteHashFirst(H)  ((H)->first)
7640#define sqliteHashNext(E)   ((E)->next)
7641#define sqliteHashData(E)   ((E)->data)
7642/* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7643/* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7644
7645/*
7646** Number of entries in a hash table
7647*/
7648/* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7649
7650#endif /* _SQLITE_HASH_H_ */
7651
7652/************** End of hash.h ************************************************/
7653/************** Continuing where we left off in sqliteInt.h ******************/
7654/************** Include parse.h in the middle of sqliteInt.h *****************/
7655/************** Begin file parse.h *******************************************/
7656#define TK_SEMI                            1
7657#define TK_EXPLAIN                         2
7658#define TK_QUERY                           3
7659#define TK_PLAN                            4
7660#define TK_BEGIN                           5
7661#define TK_TRANSACTION                     6
7662#define TK_DEFERRED                        7
7663#define TK_IMMEDIATE                       8
7664#define TK_EXCLUSIVE                       9
7665#define TK_COMMIT                         10
7666#define TK_END                            11
7667#define TK_ROLLBACK                       12
7668#define TK_SAVEPOINT                      13
7669#define TK_RELEASE                        14
7670#define TK_TO                             15
7671#define TK_TABLE                          16
7672#define TK_CREATE                         17
7673#define TK_IF                             18
7674#define TK_NOT                            19
7675#define TK_EXISTS                         20
7676#define TK_TEMP                           21
7677#define TK_LP                             22
7678#define TK_RP                             23
7679#define TK_AS                             24
7680#define TK_COMMA                          25
7681#define TK_ID                             26
7682#define TK_INDEXED                        27
7683#define TK_ABORT                          28
7684#define TK_ACTION                         29
7685#define TK_AFTER                          30
7686#define TK_ANALYZE                        31
7687#define TK_ASC                            32
7688#define TK_ATTACH                         33
7689#define TK_BEFORE                         34
7690#define TK_BY                             35
7691#define TK_CASCADE                        36
7692#define TK_CAST                           37
7693#define TK_COLUMNKW                       38
7694#define TK_CONFLICT                       39
7695#define TK_DATABASE                       40
7696#define TK_DESC                           41
7697#define TK_DETACH                         42
7698#define TK_EACH                           43
7699#define TK_FAIL                           44
7700#define TK_FOR                            45
7701#define TK_IGNORE                         46
7702#define TK_INITIALLY                      47
7703#define TK_INSTEAD                        48
7704#define TK_LIKE_KW                        49
7705#define TK_MATCH                          50
7706#define TK_NO                             51
7707#define TK_KEY                            52
7708#define TK_OF                             53
7709#define TK_OFFSET                         54
7710#define TK_PRAGMA                         55
7711#define TK_RAISE                          56
7712#define TK_REPLACE                        57
7713#define TK_RESTRICT                       58
7714#define TK_ROW                            59
7715#define TK_TRIGGER                        60
7716#define TK_VACUUM                         61
7717#define TK_VIEW                           62
7718#define TK_VIRTUAL                        63
7719#define TK_REINDEX                        64
7720#define TK_RENAME                         65
7721#define TK_CTIME_KW                       66
7722#define TK_ANY                            67
7723#define TK_OR                             68
7724#define TK_AND                            69
7725#define TK_IS                             70
7726#define TK_BETWEEN                        71
7727#define TK_IN                             72
7728#define TK_ISNULL                         73
7729#define TK_NOTNULL                        74
7730#define TK_NE                             75
7731#define TK_EQ                             76
7732#define TK_GT                             77
7733#define TK_LE                             78
7734#define TK_LT                             79
7735#define TK_GE                             80
7736#define TK_ESCAPE                         81
7737#define TK_BITAND                         82
7738#define TK_BITOR                          83
7739#define TK_LSHIFT                         84
7740#define TK_RSHIFT                         85
7741#define TK_PLUS                           86
7742#define TK_MINUS                          87
7743#define TK_STAR                           88
7744#define TK_SLASH                          89
7745#define TK_REM                            90
7746#define TK_CONCAT                         91
7747#define TK_COLLATE                        92
7748#define TK_BITNOT                         93
7749#define TK_STRING                         94
7750#define TK_JOIN_KW                        95
7751#define TK_CONSTRAINT                     96
7752#define TK_DEFAULT                        97
7753#define TK_NULL                           98
7754#define TK_PRIMARY                        99
7755#define TK_UNIQUE                         100
7756#define TK_CHECK                          101
7757#define TK_REFERENCES                     102
7758#define TK_AUTOINCR                       103
7759#define TK_ON                             104
7760#define TK_INSERT                         105
7761#define TK_DELETE                         106
7762#define TK_UPDATE                         107
7763#define TK_SET                            108
7764#define TK_DEFERRABLE                     109
7765#define TK_FOREIGN                        110
7766#define TK_DROP                           111
7767#define TK_UNION                          112
7768#define TK_ALL                            113
7769#define TK_EXCEPT                         114
7770#define TK_INTERSECT                      115
7771#define TK_SELECT                         116
7772#define TK_DISTINCT                       117
7773#define TK_DOT                            118
7774#define TK_FROM                           119
7775#define TK_JOIN                           120
7776#define TK_USING                          121
7777#define TK_ORDER                          122
7778#define TK_GROUP                          123
7779#define TK_HAVING                         124
7780#define TK_LIMIT                          125
7781#define TK_WHERE                          126
7782#define TK_INTO                           127
7783#define TK_VALUES                         128
7784#define TK_INTEGER                        129
7785#define TK_FLOAT                          130
7786#define TK_BLOB                           131
7787#define TK_REGISTER                       132
7788#define TK_VARIABLE                       133
7789#define TK_CASE                           134
7790#define TK_WHEN                           135
7791#define TK_THEN                           136
7792#define TK_ELSE                           137
7793#define TK_INDEX                          138
7794#define TK_ALTER                          139
7795#define TK_ADD                            140
7796#define TK_TO_TEXT                        141
7797#define TK_TO_BLOB                        142
7798#define TK_TO_NUMERIC                     143
7799#define TK_TO_INT                         144
7800#define TK_TO_REAL                        145
7801#define TK_ISNOT                          146
7802#define TK_END_OF_FILE                    147
7803#define TK_ILLEGAL                        148
7804#define TK_SPACE                          149
7805#define TK_UNCLOSED_STRING                150
7806#define TK_FUNCTION                       151
7807#define TK_COLUMN                         152
7808#define TK_AGG_FUNCTION                   153
7809#define TK_AGG_COLUMN                     154
7810#define TK_CONST_FUNC                     155
7811#define TK_UMINUS                         156
7812#define TK_UPLUS                          157
7813
7814/************** End of parse.h ***********************************************/
7815/************** Continuing where we left off in sqliteInt.h ******************/
7816#include <stdio.h>
7817#include <stdlib.h>
7818#include <string.h>
7819#include <assert.h>
7820#include <stddef.h>
7821
7822/*
7823** If compiling for a processor that lacks floating point support,
7824** substitute integer for floating-point
7825*/
7826#ifdef SQLITE_OMIT_FLOATING_POINT
7827# define double sqlite_int64
7828# define float sqlite_int64
7829# define LONGDOUBLE_TYPE sqlite_int64
7830# ifndef SQLITE_BIG_DBL
7831#   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
7832# endif
7833# define SQLITE_OMIT_DATETIME_FUNCS 1
7834# define SQLITE_OMIT_TRACE 1
7835# undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
7836# undef SQLITE_HAVE_ISNAN
7837#endif
7838#ifndef SQLITE_BIG_DBL
7839# define SQLITE_BIG_DBL (1e99)
7840#endif
7841
7842/*
7843** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
7844** afterward. Having this macro allows us to cause the C compiler
7845** to omit code used by TEMP tables without messy #ifndef statements.
7846*/
7847#ifdef SQLITE_OMIT_TEMPDB
7848#define OMIT_TEMPDB 1
7849#else
7850#define OMIT_TEMPDB 0
7851#endif
7852
7853/*
7854** The "file format" number is an integer that is incremented whenever
7855** the VDBE-level file format changes.  The following macros define the
7856** the default file format for new databases and the maximum file format
7857** that the library can read.
7858*/
7859#define SQLITE_MAX_FILE_FORMAT 4
7860#ifndef SQLITE_DEFAULT_FILE_FORMAT
7861# define SQLITE_DEFAULT_FILE_FORMAT 4
7862#endif
7863
7864/*
7865** Determine whether triggers are recursive by default.  This can be
7866** changed at run-time using a pragma.
7867*/
7868#ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
7869# define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
7870#endif
7871
7872/*
7873** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
7874** on the command-line
7875*/
7876#ifndef SQLITE_TEMP_STORE
7877# define SQLITE_TEMP_STORE 1
7878#endif
7879
7880/*
7881** GCC does not define the offsetof() macro so we'll have to do it
7882** ourselves.
7883*/
7884#ifndef offsetof
7885#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
7886#endif
7887
7888/*
7889** Check to see if this machine uses EBCDIC.  (Yes, believe it or
7890** not, there are still machines out there that use EBCDIC.)
7891*/
7892#if 'A' == '\301'
7893# define SQLITE_EBCDIC 1
7894#else
7895# define SQLITE_ASCII 1
7896#endif
7897
7898/*
7899** Integers of known sizes.  These typedefs might change for architectures
7900** where the sizes very.  Preprocessor macros are available so that the
7901** types can be conveniently redefined at compile-type.  Like this:
7902**
7903**         cc '-DUINTPTR_TYPE=long long int' ...
7904*/
7905#ifndef UINT32_TYPE
7906# ifdef HAVE_UINT32_T
7907#  define UINT32_TYPE uint32_t
7908# else
7909#  define UINT32_TYPE unsigned int
7910# endif
7911#endif
7912#ifndef UINT16_TYPE
7913# ifdef HAVE_UINT16_T
7914#  define UINT16_TYPE uint16_t
7915# else
7916#  define UINT16_TYPE unsigned short int
7917# endif
7918#endif
7919#ifndef INT16_TYPE
7920# ifdef HAVE_INT16_T
7921#  define INT16_TYPE int16_t
7922# else
7923#  define INT16_TYPE short int
7924# endif
7925#endif
7926#ifndef UINT8_TYPE
7927# ifdef HAVE_UINT8_T
7928#  define UINT8_TYPE uint8_t
7929# else
7930#  define UINT8_TYPE unsigned char
7931# endif
7932#endif
7933#ifndef INT8_TYPE
7934# ifdef HAVE_INT8_T
7935#  define INT8_TYPE int8_t
7936# else
7937#  define INT8_TYPE signed char
7938# endif
7939#endif
7940#ifndef LONGDOUBLE_TYPE
7941# define LONGDOUBLE_TYPE long double
7942#endif
7943typedef sqlite_int64 i64;          /* 8-byte signed integer */
7944typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
7945typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
7946typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
7947typedef INT16_TYPE i16;            /* 2-byte signed integer */
7948typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
7949typedef INT8_TYPE i8;              /* 1-byte signed integer */
7950
7951/*
7952** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
7953** that can be stored in a u32 without loss of data.  The value
7954** is 0x00000000ffffffff.  But because of quirks of some compilers, we
7955** have to specify the value in the less intuitive manner shown:
7956*/
7957#define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
7958
7959/*
7960** The datatype used to store estimates of the number of rows in a
7961** table or index.  This is an unsigned integer type.  For 99.9% of
7962** the world, a 32-bit integer is sufficient.  But a 64-bit integer
7963** can be used at compile-time if desired.
7964*/
7965#ifdef SQLITE_64BIT_STATS
7966 typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
7967#else
7968 typedef u32 tRowcnt;    /* 32-bit is the default */
7969#endif
7970
7971/*
7972** Macros to determine whether the machine is big or little endian,
7973** evaluated at runtime.
7974*/
7975#ifdef SQLITE_AMALGAMATION
7976SQLITE_PRIVATE const int sqlite3one = 1;
7977#else
7978SQLITE_PRIVATE const int sqlite3one;
7979#endif
7980#if defined(i386) || defined(__i386__) || defined(_M_IX86)\
7981                             || defined(__x86_64) || defined(__x86_64__)
7982# define SQLITE_BIGENDIAN    0
7983# define SQLITE_LITTLEENDIAN 1
7984# define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
7985#else
7986# define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
7987# define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
7988# define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
7989#endif
7990
7991/*
7992** Constants for the largest and smallest possible 64-bit signed integers.
7993** These macros are designed to work correctly on both 32-bit and 64-bit
7994** compilers.
7995*/
7996#define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
7997#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
7998
7999/*
8000** Round up a number to the next larger multiple of 8.  This is used
8001** to force 8-byte alignment on 64-bit architectures.
8002*/
8003#define ROUND8(x)     (((x)+7)&~7)
8004
8005/*
8006** Round down to the nearest multiple of 8
8007*/
8008#define ROUNDDOWN8(x) ((x)&~7)
8009
8010/*
8011** Assert that the pointer X is aligned to an 8-byte boundary.  This
8012** macro is used only within assert() to verify that the code gets
8013** all alignment restrictions correct.
8014**
8015** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8016** underlying malloc() implemention might return us 4-byte aligned
8017** pointers.  In that case, only verify 4-byte alignment.
8018*/
8019#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8020# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8021#else
8022# define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8023#endif
8024
8025
8026/*
8027** An instance of the following structure is used to store the busy-handler
8028** callback for a given sqlite handle.
8029**
8030** The sqlite.busyHandler member of the sqlite struct contains the busy
8031** callback for the database handle. Each pager opened via the sqlite
8032** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8033** callback is currently invoked only from within pager.c.
8034*/
8035typedef struct BusyHandler BusyHandler;
8036struct BusyHandler {
8037  int (*xFunc)(void *,int);  /* The busy callback */
8038  void *pArg;                /* First arg to busy callback */
8039  int nBusy;                 /* Incremented with each busy call */
8040};
8041
8042/*
8043** Name of the master database table.  The master database table
8044** is a special table that holds the names and attributes of all
8045** user tables and indices.
8046*/
8047#define MASTER_NAME       "sqlite_master"
8048#define TEMP_MASTER_NAME  "sqlite_temp_master"
8049
8050/*
8051** The root-page of the master database table.
8052*/
8053#define MASTER_ROOT       1
8054
8055/*
8056** The name of the schema table.
8057*/
8058#define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8059
8060/*
8061** A convenience macro that returns the number of elements in
8062** an array.
8063*/
8064#define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8065
8066/*
8067** The following value as a destructor means to use sqlite3DbFree().
8068** The sqlite3DbFree() routine requires two parameters instead of the
8069** one parameter that destructors normally want.  So we have to introduce
8070** this magic value that the code knows to handle differently.  Any
8071** pointer will work here as long as it is distinct from SQLITE_STATIC
8072** and SQLITE_TRANSIENT.
8073*/
8074#define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8075
8076/*
8077** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8078** not support Writable Static Data (WSD) such as global and static variables.
8079** All variables must either be on the stack or dynamically allocated from
8080** the heap.  When WSD is unsupported, the variable declarations scattered
8081** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8082** macro is used for this purpose.  And instead of referencing the variable
8083** directly, we use its constant as a key to lookup the run-time allocated
8084** buffer that holds real variable.  The constant is also the initializer
8085** for the run-time allocated buffer.
8086**
8087** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8088** macros become no-ops and have zero performance impact.
8089*/
8090#ifdef SQLITE_OMIT_WSD
8091  #define SQLITE_WSD const
8092  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8093  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8094SQLITE_API   int sqlite3_wsd_init(int N, int J);
8095SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8096#else
8097  #define SQLITE_WSD
8098  #define GLOBAL(t,v) v
8099  #define sqlite3GlobalConfig sqlite3Config
8100#endif
8101
8102/*
8103** The following macros are used to suppress compiler warnings and to
8104** make it clear to human readers when a function parameter is deliberately
8105** left unused within the body of a function. This usually happens when
8106** a function is called via a function pointer. For example the
8107** implementation of an SQL aggregate step callback may not use the
8108** parameter indicating the number of arguments passed to the aggregate,
8109** if it knows that this is enforced elsewhere.
8110**
8111** When a function parameter is not used at all within the body of a function,
8112** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8113** However, these macros may also be used to suppress warnings related to
8114** parameters that may or may not be used depending on compilation options.
8115** For example those parameters only used in assert() statements. In these
8116** cases the parameters are named as per the usual conventions.
8117*/
8118#define UNUSED_PARAMETER(x) (void)(x)
8119#define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8120
8121/*
8122** Forward references to structures
8123*/
8124typedef struct AggInfo AggInfo;
8125typedef struct AuthContext AuthContext;
8126typedef struct AutoincInfo AutoincInfo;
8127typedef struct Bitvec Bitvec;
8128typedef struct CollSeq CollSeq;
8129typedef struct Column Column;
8130typedef struct Db Db;
8131typedef struct Schema Schema;
8132typedef struct Expr Expr;
8133typedef struct ExprList ExprList;
8134typedef struct ExprSpan ExprSpan;
8135typedef struct FKey FKey;
8136typedef struct FuncDestructor FuncDestructor;
8137typedef struct FuncDef FuncDef;
8138typedef struct FuncDefHash FuncDefHash;
8139typedef struct IdList IdList;
8140typedef struct Index Index;
8141typedef struct IndexSample IndexSample;
8142typedef struct KeyClass KeyClass;
8143typedef struct KeyInfo KeyInfo;
8144typedef struct Lookaside Lookaside;
8145typedef struct LookasideSlot LookasideSlot;
8146typedef struct Module Module;
8147typedef struct NameContext NameContext;
8148typedef struct Parse Parse;
8149typedef struct RowSet RowSet;
8150typedef struct Savepoint Savepoint;
8151typedef struct Select Select;
8152typedef struct SrcList SrcList;
8153typedef struct StrAccum StrAccum;
8154typedef struct Table Table;
8155typedef struct TableLock TableLock;
8156typedef struct Token Token;
8157typedef struct Trigger Trigger;
8158typedef struct TriggerPrg TriggerPrg;
8159typedef struct TriggerStep TriggerStep;
8160typedef struct UnpackedRecord UnpackedRecord;
8161typedef struct VTable VTable;
8162typedef struct VtabCtx VtabCtx;
8163typedef struct Walker Walker;
8164typedef struct WherePlan WherePlan;
8165typedef struct WhereInfo WhereInfo;
8166typedef struct WhereLevel WhereLevel;
8167
8168/*
8169** Defer sourcing vdbe.h and btree.h until after the "u8" and
8170** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8171** pointer types (i.e. FuncDef) defined above.
8172*/
8173/************** Include btree.h in the middle of sqliteInt.h *****************/
8174/************** Begin file btree.h *******************************************/
8175/*
8176** 2001 September 15
8177**
8178** The author disclaims copyright to this source code.  In place of
8179** a legal notice, here is a blessing:
8180**
8181**    May you do good and not evil.
8182**    May you find forgiveness for yourself and forgive others.
8183**    May you share freely, never taking more than you give.
8184**
8185*************************************************************************
8186** This header file defines the interface that the sqlite B-Tree file
8187** subsystem.  See comments in the source code for a detailed description
8188** of what each interface routine does.
8189*/
8190#ifndef _BTREE_H_
8191#define _BTREE_H_
8192
8193/* TODO: This definition is just included so other modules compile. It
8194** needs to be revisited.
8195*/
8196#define SQLITE_N_BTREE_META 10
8197
8198/*
8199** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8200** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8201*/
8202#ifndef SQLITE_DEFAULT_AUTOVACUUM
8203  #define SQLITE_DEFAULT_AUTOVACUUM 0
8204#endif
8205
8206#define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8207#define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8208#define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8209
8210/*
8211** Forward declarations of structure
8212*/
8213typedef struct Btree Btree;
8214typedef struct BtCursor BtCursor;
8215typedef struct BtShared BtShared;
8216
8217
8218SQLITE_PRIVATE int sqlite3BtreeOpen(
8219  sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8220  const char *zFilename,   /* Name of database file to open */
8221  sqlite3 *db,             /* Associated database connection */
8222  Btree **ppBtree,         /* Return open Btree* here */
8223  int flags,               /* Flags */
8224  int vfsFlags             /* Flags passed through to VFS open */
8225);
8226
8227/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8228** following values.
8229**
8230** NOTE:  These values must match the corresponding PAGER_ values in
8231** pager.h.
8232*/
8233#define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8234#define BTREE_MEMORY        2  /* This is an in-memory DB */
8235#define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8236#define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8237
8238SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8239SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8240SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8241SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8242SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8243SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8244SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8245SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8246SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8247SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8248SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8249SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8250SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8251SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8252SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8253SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8254SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8255SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8256SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8257SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8258SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8259SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8260SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8261SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8262SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8263SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8264
8265SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8266SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8267SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8268
8269SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8270
8271/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8272** of the flags shown below.
8273**
8274** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8275** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8276** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8277** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8278** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8279** indices.)
8280*/
8281#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8282#define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8283
8284SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8285SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8286SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8287
8288SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8289SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8290
8291/*
8292** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8293** should be one of the following values. The integer values are assigned
8294** to constants so that the offset of the corresponding field in an
8295** SQLite database header may be found using the following formula:
8296**
8297**   offset = 36 + (idx * 4)
8298**
8299** For example, the free-page-count field is located at byte offset 36 of
8300** the database file header. The incr-vacuum-flag field is located at
8301** byte offset 64 (== 36+4*7).
8302*/
8303#define BTREE_FREE_PAGE_COUNT     0
8304#define BTREE_SCHEMA_VERSION      1
8305#define BTREE_FILE_FORMAT         2
8306#define BTREE_DEFAULT_CACHE_SIZE  3
8307#define BTREE_LARGEST_ROOT_PAGE   4
8308#define BTREE_TEXT_ENCODING       5
8309#define BTREE_USER_VERSION        6
8310#define BTREE_INCR_VACUUM         7
8311
8312SQLITE_PRIVATE int sqlite3BtreeCursor(
8313  Btree*,                              /* BTree containing table to open */
8314  int iTable,                          /* Index of root page */
8315  int wrFlag,                          /* 1 for writing.  0 for read-only */
8316  struct KeyInfo*,                     /* First argument to compare function */
8317  BtCursor *pCursor                    /* Space to write cursor structure */
8318);
8319SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8320SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8321
8322SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8323SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8324  BtCursor*,
8325  UnpackedRecord *pUnKey,
8326  i64 intKey,
8327  int bias,
8328  int *pRes
8329);
8330SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8331SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8332SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8333                                  const void *pData, int nData,
8334                                  int nZero, int bias, int seekResult);
8335SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8336SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8337SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8338SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8339SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8340SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8341SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8342SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8343SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8344SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8345SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8346SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8347SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8348
8349SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8350SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8351
8352SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8353SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8354SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8355
8356SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8357
8358#ifndef NDEBUG
8359SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8360#endif
8361
8362#ifndef SQLITE_OMIT_BTREECOUNT
8363SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8364#endif
8365
8366#ifdef SQLITE_TEST
8367SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8368SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8369#endif
8370
8371#ifndef SQLITE_OMIT_WAL
8372SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8373#endif
8374
8375/*
8376** If we are not using shared cache, then there is no need to
8377** use mutexes to access the BtShared structures.  So make the
8378** Enter and Leave procedures no-ops.
8379*/
8380#ifndef SQLITE_OMIT_SHARED_CACHE
8381SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8382SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8383#else
8384# define sqlite3BtreeEnter(X)
8385# define sqlite3BtreeEnterAll(X)
8386#endif
8387
8388#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8389SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8390SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8391SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8392SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8393SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8394#ifndef NDEBUG
8395  /* These routines are used inside assert() statements only. */
8396SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8397SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8398SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8399#endif
8400#else
8401
8402# define sqlite3BtreeSharable(X) 0
8403# define sqlite3BtreeLeave(X)
8404# define sqlite3BtreeEnterCursor(X)
8405# define sqlite3BtreeLeaveCursor(X)
8406# define sqlite3BtreeLeaveAll(X)
8407
8408# define sqlite3BtreeHoldsMutex(X) 1
8409# define sqlite3BtreeHoldsAllMutexes(X) 1
8410# define sqlite3SchemaMutexHeld(X,Y,Z) 1
8411#endif
8412
8413
8414#endif /* _BTREE_H_ */
8415
8416/************** End of btree.h ***********************************************/
8417/************** Continuing where we left off in sqliteInt.h ******************/
8418/************** Include vdbe.h in the middle of sqliteInt.h ******************/
8419/************** Begin file vdbe.h ********************************************/
8420/*
8421** 2001 September 15
8422**
8423** The author disclaims copyright to this source code.  In place of
8424** a legal notice, here is a blessing:
8425**
8426**    May you do good and not evil.
8427**    May you find forgiveness for yourself and forgive others.
8428**    May you share freely, never taking more than you give.
8429**
8430*************************************************************************
8431** Header file for the Virtual DataBase Engine (VDBE)
8432**
8433** This header defines the interface to the virtual database engine
8434** or VDBE.  The VDBE implements an abstract machine that runs a
8435** simple program to access and modify the underlying database.
8436*/
8437#ifndef _SQLITE_VDBE_H_
8438#define _SQLITE_VDBE_H_
8439/* #include <stdio.h> */
8440
8441/*
8442** A single VDBE is an opaque structure named "Vdbe".  Only routines
8443** in the source file sqliteVdbe.c are allowed to see the insides
8444** of this structure.
8445*/
8446typedef struct Vdbe Vdbe;
8447
8448/*
8449** The names of the following types declared in vdbeInt.h are required
8450** for the VdbeOp definition.
8451*/
8452typedef struct VdbeFunc VdbeFunc;
8453typedef struct Mem Mem;
8454typedef struct SubProgram SubProgram;
8455
8456/*
8457** A single instruction of the virtual machine has an opcode
8458** and as many as three operands.  The instruction is recorded
8459** as an instance of the following structure:
8460*/
8461struct VdbeOp {
8462  u8 opcode;          /* What operation to perform */
8463  signed char p4type; /* One of the P4_xxx constants for p4 */
8464  u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8465  u8 p5;              /* Fifth parameter is an unsigned character */
8466  int p1;             /* First operand */
8467  int p2;             /* Second parameter (often the jump destination) */
8468  int p3;             /* The third parameter */
8469  union {             /* fourth parameter */
8470    int i;                 /* Integer value if p4type==P4_INT32 */
8471    void *p;               /* Generic pointer */
8472    char *z;               /* Pointer to data for string (char array) types */
8473    i64 *pI64;             /* Used when p4type is P4_INT64 */
8474    double *pReal;         /* Used when p4type is P4_REAL */
8475    FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8476    VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8477    CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8478    Mem *pMem;             /* Used when p4type is P4_MEM */
8479    VTable *pVtab;         /* Used when p4type is P4_VTAB */
8480    KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8481    int *ai;               /* Used when p4type is P4_INTARRAY */
8482    SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8483    int (*xAdvance)(BtCursor *, int *);
8484  } p4;
8485#ifdef SQLITE_DEBUG
8486  char *zComment;          /* Comment to improve readability */
8487#endif
8488#ifdef VDBE_PROFILE
8489  int cnt;                 /* Number of times this instruction was executed */
8490  u64 cycles;              /* Total time spent executing this instruction */
8491#endif
8492};
8493typedef struct VdbeOp VdbeOp;
8494
8495
8496/*
8497** A sub-routine used to implement a trigger program.
8498*/
8499struct SubProgram {
8500  VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8501  int nOp;                      /* Elements in aOp[] */
8502  int nMem;                     /* Number of memory cells required */
8503  int nCsr;                     /* Number of cursors required */
8504  int nOnce;                    /* Number of OP_Once instructions */
8505  void *token;                  /* id that may be used to recursive triggers */
8506  SubProgram *pNext;            /* Next sub-program already visited */
8507};
8508
8509/*
8510** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8511** it takes up less space.
8512*/
8513struct VdbeOpList {
8514  u8 opcode;          /* What operation to perform */
8515  signed char p1;     /* First operand */
8516  signed char p2;     /* Second parameter (often the jump destination) */
8517  signed char p3;     /* Third parameter */
8518};
8519typedef struct VdbeOpList VdbeOpList;
8520
8521/*
8522** Allowed values of VdbeOp.p4type
8523*/
8524#define P4_NOTUSED    0   /* The P4 parameter is not used */
8525#define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8526#define P4_STATIC   (-2)  /* Pointer to a static string */
8527#define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8528#define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8529#define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8530#define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8531#define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8532#define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8533#define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8534#define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8535#define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8536#define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8537#define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8538#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8539#define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8540#define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8541
8542/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8543** is made.  That copy is freed when the Vdbe is finalized.  But if the
8544** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8545** gets freed when the Vdbe is finalized so it still should be obtained
8546** from a single sqliteMalloc().  But no copy is made and the calling
8547** function should *not* try to free the KeyInfo.
8548*/
8549#define P4_KEYINFO_HANDOFF (-16)
8550#define P4_KEYINFO_STATIC  (-17)
8551
8552/*
8553** The Vdbe.aColName array contains 5n Mem structures, where n is the
8554** number of columns of data returned by the statement.
8555*/
8556#define COLNAME_NAME     0
8557#define COLNAME_DECLTYPE 1
8558#define COLNAME_DATABASE 2
8559#define COLNAME_TABLE    3
8560#define COLNAME_COLUMN   4
8561#ifdef SQLITE_ENABLE_COLUMN_METADATA
8562# define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8563#else
8564# ifdef SQLITE_OMIT_DECLTYPE
8565#   define COLNAME_N      1      /* Store only the name */
8566# else
8567#   define COLNAME_N      2      /* Store the name and decltype */
8568# endif
8569#endif
8570
8571/*
8572** The following macro converts a relative address in the p2 field
8573** of a VdbeOp structure into a negative number so that
8574** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8575** the macro again restores the address.
8576*/
8577#define ADDR(X)  (-1-(X))
8578
8579/*
8580** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8581** header file that defines a number for each opcode used by the VDBE.
8582*/
8583/************** Include opcodes.h in the middle of vdbe.h ********************/
8584/************** Begin file opcodes.h *****************************************/
8585/* Automatically generated.  Do not edit */
8586/* See the mkopcodeh.awk script for details */
8587#define OP_Goto                                 1
8588#define OP_Gosub                                2
8589#define OP_Return                               3
8590#define OP_Yield                                4
8591#define OP_HaltIfNull                           5
8592#define OP_Halt                                 6
8593#define OP_Integer                              7
8594#define OP_Int64                                8
8595#define OP_Real                               130   /* same as TK_FLOAT    */
8596#define OP_String8                             94   /* same as TK_STRING   */
8597#define OP_String                               9
8598#define OP_Null                                10
8599#define OP_Blob                                11
8600#define OP_Variable                            12
8601#define OP_Move                                13
8602#define OP_Copy                                14
8603#define OP_SCopy                               15
8604#define OP_ResultRow                           16
8605#define OP_Concat                              91   /* same as TK_CONCAT   */
8606#define OP_Add                                 86   /* same as TK_PLUS     */
8607#define OP_Subtract                            87   /* same as TK_MINUS    */
8608#define OP_Multiply                            88   /* same as TK_STAR     */
8609#define OP_Divide                              89   /* same as TK_SLASH    */
8610#define OP_Remainder                           90   /* same as TK_REM      */
8611#define OP_CollSeq                             17
8612#define OP_Function                            18
8613#define OP_BitAnd                              82   /* same as TK_BITAND   */
8614#define OP_BitOr                               83   /* same as TK_BITOR    */
8615#define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8616#define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8617#define OP_AddImm                              20
8618#define OP_MustBeInt                           21
8619#define OP_RealAffinity                        22
8620#define OP_ToText                             141   /* same as TK_TO_TEXT  */
8621#define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8622#define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8623#define OP_ToInt                              144   /* same as TK_TO_INT   */
8624#define OP_ToReal                             145   /* same as TK_TO_REAL  */
8625#define OP_Eq                                  76   /* same as TK_EQ       */
8626#define OP_Ne                                  75   /* same as TK_NE       */
8627#define OP_Lt                                  79   /* same as TK_LT       */
8628#define OP_Le                                  78   /* same as TK_LE       */
8629#define OP_Gt                                  77   /* same as TK_GT       */
8630#define OP_Ge                                  80   /* same as TK_GE       */
8631#define OP_Permutation                         23
8632#define OP_Compare                             24
8633#define OP_Jump                                25
8634#define OP_And                                 69   /* same as TK_AND      */
8635#define OP_Or                                  68   /* same as TK_OR       */
8636#define OP_Not                                 19   /* same as TK_NOT      */
8637#define OP_BitNot                              93   /* same as TK_BITNOT   */
8638#define OP_Once                                26
8639#define OP_If                                  27
8640#define OP_IfNot                               28
8641#define OP_IsNull                              73   /* same as TK_ISNULL   */
8642#define OP_NotNull                             74   /* same as TK_NOTNULL  */
8643#define OP_Column                              29
8644#define OP_Affinity                            30
8645#define OP_MakeRecord                          31
8646#define OP_Count                               32
8647#define OP_Savepoint                           33
8648#define OP_AutoCommit                          34
8649#define OP_Transaction                         35
8650#define OP_ReadCookie                          36
8651#define OP_SetCookie                           37
8652#define OP_VerifyCookie                        38
8653#define OP_OpenRead                            39
8654#define OP_OpenWrite                           40
8655#define OP_OpenAutoindex                       41
8656#define OP_OpenEphemeral                       42
8657#define OP_SorterOpen                          43
8658#define OP_OpenPseudo                          44
8659#define OP_Close                               45
8660#define OP_SeekLt                              46
8661#define OP_SeekLe                              47
8662#define OP_SeekGe                              48
8663#define OP_SeekGt                              49
8664#define OP_Seek                                50
8665#define OP_NotFound                            51
8666#define OP_Found                               52
8667#define OP_IsUnique                            53
8668#define OP_NotExists                           54
8669#define OP_Sequence                            55
8670#define OP_NewRowid                            56
8671#define OP_Insert                              57
8672#define OP_InsertInt                           58
8673#define OP_Delete                              59
8674#define OP_ResetCount                          60
8675#define OP_SorterCompare                       61
8676#define OP_SorterData                          62
8677#define OP_RowKey                              63
8678#define OP_RowData                             64
8679#define OP_Rowid                               65
8680#define OP_NullRow                             66
8681#define OP_Last                                67
8682#define OP_SorterSort                          70
8683#define OP_Sort                                71
8684#define OP_Rewind                              72
8685#define OP_SorterNext                          81
8686#define OP_Prev                                92
8687#define OP_Next                                95
8688#define OP_SorterInsert                        96
8689#define OP_IdxInsert                           97
8690#define OP_IdxDelete                           98
8691#define OP_IdxRowid                            99
8692#define OP_IdxLT                              100
8693#define OP_IdxGE                              101
8694#define OP_Destroy                            102
8695#define OP_Clear                              103
8696#define OP_CreateIndex                        104
8697#define OP_CreateTable                        105
8698#define OP_ParseSchema                        106
8699#define OP_LoadAnalysis                       107
8700#define OP_DropTable                          108
8701#define OP_DropIndex                          109
8702#define OP_DropTrigger                        110
8703#define OP_IntegrityCk                        111
8704#define OP_RowSetAdd                          112
8705#define OP_RowSetRead                         113
8706#define OP_RowSetTest                         114
8707#define OP_Program                            115
8708#define OP_Param                              116
8709#define OP_FkCounter                          117
8710#define OP_FkIfZero                           118
8711#define OP_MemMax                             119
8712#define OP_IfPos                              120
8713#define OP_IfNeg                              121
8714#define OP_IfZero                             122
8715#define OP_AggStep                            123
8716#define OP_AggFinal                           124
8717#define OP_Checkpoint                         125
8718#define OP_JournalMode                        126
8719#define OP_Vacuum                             127
8720#define OP_IncrVacuum                         128
8721#define OP_Expire                             129
8722#define OP_TableLock                          131
8723#define OP_VBegin                             132
8724#define OP_VCreate                            133
8725#define OP_VDestroy                           134
8726#define OP_VOpen                              135
8727#define OP_VFilter                            136
8728#define OP_VColumn                            137
8729#define OP_VNext                              138
8730#define OP_VRename                            139
8731#define OP_VUpdate                            140
8732#define OP_Pagecount                          146
8733#define OP_MaxPgcnt                           147
8734#define OP_Trace                              148
8735#define OP_Noop                               149
8736#define OP_Explain                            150
8737
8738
8739/* Properties such as "out2" or "jump" that are specified in
8740** comments following the "case" for each opcode in the vdbe.c
8741** are encoded into bitvectors as follows:
8742*/
8743#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
8744#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
8745#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
8746#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
8747#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
8748#define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
8749#define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
8750#define OPFLG_INITIALIZER {\
8751/*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
8752/*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x24, 0x24,\
8753/*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
8754/*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
8755/*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
8756/*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
8757/*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
8758/*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8759/*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
8760/*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
8761/*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
8762/*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
8763/*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
8764/* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
8765/* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
8766/* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
8767/* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
8768/* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
8769/* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
8770
8771/************** End of opcodes.h *********************************************/
8772/************** Continuing where we left off in vdbe.h ***********************/
8773
8774/*
8775** Prototypes for the VDBE interface.  See comments on the implementation
8776** for a description of what each of these routines does.
8777*/
8778SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
8779SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
8780SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
8781SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
8782SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
8783SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
8784SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
8785SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
8786SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
8787SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
8788SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
8789SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
8790SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
8791SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
8792SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
8793SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
8794SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
8795SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
8796SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
8797SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
8798SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
8799SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3*,Vdbe*);
8800SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
8801SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
8802SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
8803SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
8804#ifdef SQLITE_DEBUG
8805SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
8806SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
8807#endif
8808SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
8809SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
8810SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
8811SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
8812SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
8813SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
8814SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
8815SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
8816SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
8817SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
8818SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
8819SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
8820#ifndef SQLITE_OMIT_TRACE
8821SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
8822#endif
8823
8824SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
8825SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
8826SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
8827
8828#ifndef SQLITE_OMIT_TRIGGER
8829SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
8830#endif
8831
8832
8833#ifndef NDEBUG
8834SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
8835# define VdbeComment(X)  sqlite3VdbeComment X
8836SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
8837# define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
8838#else
8839# define VdbeComment(X)
8840# define VdbeNoopComment(X)
8841#endif
8842
8843#endif
8844
8845/************** End of vdbe.h ************************************************/
8846/************** Continuing where we left off in sqliteInt.h ******************/
8847/************** Include pager.h in the middle of sqliteInt.h *****************/
8848/************** Begin file pager.h *******************************************/
8849/*
8850** 2001 September 15
8851**
8852** The author disclaims copyright to this source code.  In place of
8853** a legal notice, here is a blessing:
8854**
8855**    May you do good and not evil.
8856**    May you find forgiveness for yourself and forgive others.
8857**    May you share freely, never taking more than you give.
8858**
8859*************************************************************************
8860** This header file defines the interface that the sqlite page cache
8861** subsystem.  The page cache subsystem reads and writes a file a page
8862** at a time and provides a journal for rollback.
8863*/
8864
8865#ifndef _PAGER_H_
8866#define _PAGER_H_
8867
8868/*
8869** Default maximum size for persistent journal files. A negative
8870** value means no limit. This value may be overridden using the
8871** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
8872*/
8873#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
8874  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
8875#endif
8876
8877/*
8878** The type used to represent a page number.  The first page in a file
8879** is called page 1.  0 is used to represent "not a page".
8880*/
8881typedef u32 Pgno;
8882
8883/*
8884** Each open file is managed by a separate instance of the "Pager" structure.
8885*/
8886typedef struct Pager Pager;
8887
8888/*
8889** Handle type for pages.
8890*/
8891typedef struct PgHdr DbPage;
8892
8893/*
8894** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
8895** reserved for working around a windows/posix incompatibility). It is
8896** used in the journal to signify that the remainder of the journal file
8897** is devoted to storing a master journal name - there are no more pages to
8898** roll back. See comments for function writeMasterJournal() in pager.c
8899** for details.
8900*/
8901#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
8902
8903/*
8904** Allowed values for the flags parameter to sqlite3PagerOpen().
8905**
8906** NOTE: These values must match the corresponding BTREE_ values in btree.h.
8907*/
8908#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
8909#define PAGER_MEMORY        0x0002    /* In-memory database */
8910
8911/*
8912** Valid values for the second argument to sqlite3PagerLockingMode().
8913*/
8914#define PAGER_LOCKINGMODE_QUERY      -1
8915#define PAGER_LOCKINGMODE_NORMAL      0
8916#define PAGER_LOCKINGMODE_EXCLUSIVE   1
8917
8918/*
8919** Numeric constants that encode the journalmode.
8920*/
8921#define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
8922#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
8923#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
8924#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
8925#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
8926#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
8927#define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
8928
8929/*
8930** The remainder of this file contains the declarations of the functions
8931** that make up the Pager sub-system API. See source code comments for
8932** a detailed description of each routine.
8933*/
8934
8935/* Open and close a Pager connection. */
8936SQLITE_PRIVATE int sqlite3PagerOpen(
8937  sqlite3_vfs*,
8938  Pager **ppPager,
8939  const char*,
8940  int,
8941  int,
8942  int,
8943  void(*)(DbPage*)
8944);
8945SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
8946SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
8947
8948/* Functions used to configure a Pager object. */
8949SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
8950SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
8951SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
8952SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
8953SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
8954SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
8955SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
8956SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
8957SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
8958SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
8959SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
8960SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
8961
8962/* Functions used to obtain and release page references. */
8963SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
8964#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
8965SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
8966SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
8967SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
8968
8969/* Operations on page references. */
8970SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
8971SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
8972SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
8973SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
8974SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
8975SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
8976
8977/* Functions used to manage pager transactions and savepoints. */
8978SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
8979SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
8980SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
8981SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
8982SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
8983SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
8984SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
8985SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
8986SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
8987SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
8988
8989SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
8990SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
8991SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
8992SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
8993SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
8994#ifdef SQLITE_ENABLE_ZIPVFS
8995SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
8996#endif
8997
8998/* Functions used to query pager state and configuration. */
8999SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9000SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9001SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9002SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
9003SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9004SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9005SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9006SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9007SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9008SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9009SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9010SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9011
9012/* Functions used to truncate the database file. */
9013SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9014
9015#if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9016SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9017#endif
9018
9019/* Functions to support testing and debugging. */
9020#if !defined(NDEBUG) || defined(SQLITE_TEST)
9021SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9022SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9023#endif
9024#ifdef SQLITE_TEST
9025SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9026SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9027  void disable_simulated_io_errors(void);
9028  void enable_simulated_io_errors(void);
9029#else
9030# define disable_simulated_io_errors()
9031# define enable_simulated_io_errors()
9032#endif
9033
9034#endif /* _PAGER_H_ */
9035
9036/************** End of pager.h ***********************************************/
9037/************** Continuing where we left off in sqliteInt.h ******************/
9038/************** Include pcache.h in the middle of sqliteInt.h ****************/
9039/************** Begin file pcache.h ******************************************/
9040/*
9041** 2008 August 05
9042**
9043** The author disclaims copyright to this source code.  In place of
9044** a legal notice, here is a blessing:
9045**
9046**    May you do good and not evil.
9047**    May you find forgiveness for yourself and forgive others.
9048**    May you share freely, never taking more than you give.
9049**
9050*************************************************************************
9051** This header file defines the interface that the sqlite page cache
9052** subsystem.
9053*/
9054
9055#ifndef _PCACHE_H_
9056
9057typedef struct PgHdr PgHdr;
9058typedef struct PCache PCache;
9059
9060/*
9061** Every page in the cache is controlled by an instance of the following
9062** structure.
9063*/
9064struct PgHdr {
9065  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9066  void *pData;                   /* Page data */
9067  void *pExtra;                  /* Extra content */
9068  PgHdr *pDirty;                 /* Transient list of dirty pages */
9069  Pager *pPager;                 /* The pager this page is part of */
9070  Pgno pgno;                     /* Page number for this page */
9071#ifdef SQLITE_CHECK_PAGES
9072  u32 pageHash;                  /* Hash of page content */
9073#endif
9074  u16 flags;                     /* PGHDR flags defined below */
9075
9076  /**********************************************************************
9077  ** Elements above are public.  All that follows is private to pcache.c
9078  ** and should not be accessed by other modules.
9079  */
9080  i16 nRef;                      /* Number of users of this page */
9081  PCache *pCache;                /* Cache that owns this page */
9082
9083  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9084  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9085};
9086
9087/* Bit values for PgHdr.flags */
9088#define PGHDR_DIRTY             0x002  /* Page has changed */
9089#define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9090                                       ** writing this page to the database */
9091#define PGHDR_NEED_READ         0x008  /* Content is unread */
9092#define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9093#define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9094
9095/* Initialize and shutdown the page cache subsystem */
9096SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9097SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9098
9099/* Page cache buffer management:
9100** These routines implement SQLITE_CONFIG_PAGECACHE.
9101*/
9102SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9103
9104/* Create a new pager cache.
9105** Under memory stress, invoke xStress to try to make pages clean.
9106** Only clean and unpinned pages can be reclaimed.
9107*/
9108SQLITE_PRIVATE void sqlite3PcacheOpen(
9109  int szPage,                    /* Size of every page */
9110  int szExtra,                   /* Extra space associated with each page */
9111  int bPurgeable,                /* True if pages are on backing store */
9112  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9113  void *pStress,                 /* Argument to xStress */
9114  PCache *pToInit                /* Preallocated space for the PCache */
9115);
9116
9117/* Modify the page-size after the cache has been created. */
9118SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9119
9120/* Return the size in bytes of a PCache object.  Used to preallocate
9121** storage space.
9122*/
9123SQLITE_PRIVATE int sqlite3PcacheSize(void);
9124
9125/* One release per successful fetch.  Page is pinned until released.
9126** Reference counted.
9127*/
9128SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9129SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9130
9131SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9132SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9133SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9134SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9135
9136/* Change a page number.  Used by incr-vacuum. */
9137SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9138
9139/* Remove all pages with pgno>x.  Reset the cache if x==0 */
9140SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9141
9142/* Get a list of all dirty pages in the cache, sorted by page number */
9143SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9144
9145/* Reset and close the cache object */
9146SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9147
9148/* Clear flags from pages of the page cache */
9149SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9150
9151/* Discard the contents of the cache */
9152SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9153
9154/* Return the total number of outstanding page references */
9155SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9156
9157/* Increment the reference count of an existing page */
9158SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9159
9160SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9161
9162/* Return the total number of pages stored in the cache */
9163SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9164
9165#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9166/* Iterate through all dirty pages currently stored in the cache. This
9167** interface is only available if SQLITE_CHECK_PAGES is defined when the
9168** library is built.
9169*/
9170SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9171#endif
9172
9173/* Set and get the suggested cache-size for the specified pager-cache.
9174**
9175** If no global maximum is configured, then the system attempts to limit
9176** the total number of pages cached by purgeable pager-caches to the sum
9177** of the suggested cache-sizes.
9178*/
9179SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9180#ifdef SQLITE_TEST
9181SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9182#endif
9183
9184/* Free up as much memory as possible from the page cache */
9185SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9186
9187#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9188/* Try to return memory used by the pcache module to the main memory heap */
9189SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9190#endif
9191
9192#ifdef SQLITE_TEST
9193SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9194#endif
9195
9196SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9197
9198#endif /* _PCACHE_H_ */
9199
9200/************** End of pcache.h **********************************************/
9201/************** Continuing where we left off in sqliteInt.h ******************/
9202
9203/************** Include os.h in the middle of sqliteInt.h ********************/
9204/************** Begin file os.h **********************************************/
9205/*
9206** 2001 September 16
9207**
9208** The author disclaims copyright to this source code.  In place of
9209** a legal notice, here is a blessing:
9210**
9211**    May you do good and not evil.
9212**    May you find forgiveness for yourself and forgive others.
9213**    May you share freely, never taking more than you give.
9214**
9215******************************************************************************
9216**
9217** This header file (together with is companion C source-code file
9218** "os.c") attempt to abstract the underlying operating system so that
9219** the SQLite library will work on both POSIX and windows systems.
9220**
9221** This header file is #include-ed by sqliteInt.h and thus ends up
9222** being included by every source file.
9223*/
9224#ifndef _SQLITE_OS_H_
9225#define _SQLITE_OS_H_
9226
9227/*
9228** Figure out if we are dealing with Unix, Windows, or some other
9229** operating system.  After the following block of preprocess macros,
9230** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER
9231** will defined to either 1 or 0.  One of the four will be 1.  The other
9232** three will be 0.
9233*/
9234#if defined(SQLITE_OS_OTHER)
9235# if SQLITE_OS_OTHER==1
9236#   undef SQLITE_OS_UNIX
9237#   define SQLITE_OS_UNIX 0
9238#   undef SQLITE_OS_WIN
9239#   define SQLITE_OS_WIN 0
9240#   undef SQLITE_OS_OS2
9241#   define SQLITE_OS_OS2 0
9242# else
9243#   undef SQLITE_OS_OTHER
9244# endif
9245#endif
9246#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9247# define SQLITE_OS_OTHER 0
9248# ifndef SQLITE_OS_WIN
9249#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9250#     define SQLITE_OS_WIN 1
9251#     define SQLITE_OS_UNIX 0
9252#     define SQLITE_OS_OS2 0
9253#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
9254#     define SQLITE_OS_WIN 0
9255#     define SQLITE_OS_UNIX 0
9256#     define SQLITE_OS_OS2 1
9257#   else
9258#     define SQLITE_OS_WIN 0
9259#     define SQLITE_OS_UNIX 1
9260#     define SQLITE_OS_OS2 0
9261#  endif
9262# else
9263#  define SQLITE_OS_UNIX 0
9264#  define SQLITE_OS_OS2 0
9265# endif
9266#else
9267# ifndef SQLITE_OS_WIN
9268#  define SQLITE_OS_WIN 0
9269# endif
9270#endif
9271
9272/*
9273** Define the maximum size of a temporary filename
9274*/
9275#if SQLITE_OS_WIN
9276# include <windows.h>
9277# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
9278#elif SQLITE_OS_OS2
9279# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
9280#  include <os2safe.h> /* has to be included before os2.h for linking to work */
9281# endif
9282# define INCL_DOSDATETIME
9283# define INCL_DOSFILEMGR
9284# define INCL_DOSERRORS
9285# define INCL_DOSMISC
9286# define INCL_DOSPROCESS
9287# define INCL_DOSMODULEMGR
9288# define INCL_DOSSEMAPHORES
9289# include <os2.h>
9290# include <uconv.h>
9291# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
9292#else
9293# define SQLITE_TEMPNAME_SIZE 200
9294#endif
9295
9296/*
9297** Determine if we are dealing with Windows NT.
9298**
9299** We ought to be able to determine if we are compiling for win98 or winNT
9300** using the _WIN32_WINNT macro as follows:
9301**
9302** #if defined(_WIN32_WINNT)
9303** # define SQLITE_OS_WINNT 1
9304** #else
9305** # define SQLITE_OS_WINNT 0
9306** #endif
9307**
9308** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9309** so the above test does not work.  We'll just assume that everything is
9310** winNT unless the programmer explicitly says otherwise by setting
9311** SQLITE_OS_WINNT to 0.
9312*/
9313#if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9314# define SQLITE_OS_WINNT 1
9315#endif
9316
9317/*
9318** Determine if we are dealing with WindowsCE - which has a much
9319** reduced API.
9320*/
9321#if defined(_WIN32_WCE)
9322# define SQLITE_OS_WINCE 1
9323#else
9324# define SQLITE_OS_WINCE 0
9325#endif
9326
9327/* If the SET_FULLSYNC macro is not defined above, then make it
9328** a no-op
9329*/
9330#ifndef SET_FULLSYNC
9331# define SET_FULLSYNC(x,y)
9332#endif
9333
9334/*
9335** The default size of a disk sector
9336*/
9337#ifndef SQLITE_DEFAULT_SECTOR_SIZE
9338# define SQLITE_DEFAULT_SECTOR_SIZE 4096
9339#endif
9340
9341/*
9342** Temporary files are named starting with this prefix followed by 16 random
9343** alphanumeric characters, and no file extension. They are stored in the
9344** OS's standard temporary file directory, and are deleted prior to exit.
9345** If sqlite is being embedded in another program, you may wish to change the
9346** prefix to reflect your program's name, so that if your program exits
9347** prematurely, old temporary files can be easily identified. This can be done
9348** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9349**
9350** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9351** Mcafee started using SQLite in their anti-virus product and it
9352** started putting files with the "sqlite" name in the c:/temp folder.
9353** This annoyed many windows users.  Those users would then do a
9354** Google search for "sqlite", find the telephone numbers of the
9355** developers and call to wake them up at night and complain.
9356** For this reason, the default name prefix is changed to be "sqlite"
9357** spelled backwards.  So the temp files are still identified, but
9358** anybody smart enough to figure out the code is also likely smart
9359** enough to know that calling the developer will not help get rid
9360** of the file.
9361*/
9362#ifndef SQLITE_TEMP_FILE_PREFIX
9363# define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9364#endif
9365
9366/*
9367** The following values may be passed as the second argument to
9368** sqlite3OsLock(). The various locks exhibit the following semantics:
9369**
9370** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9371** RESERVED:  A single process may hold a RESERVED lock on a file at
9372**            any time. Other processes may hold and obtain new SHARED locks.
9373** PENDING:   A single process may hold a PENDING lock on a file at
9374**            any one time. Existing SHARED locks may persist, but no new
9375**            SHARED locks may be obtained by other processes.
9376** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9377**
9378** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9379** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9380** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9381** sqlite3OsLock().
9382*/
9383#define NO_LOCK         0
9384#define SHARED_LOCK     1
9385#define RESERVED_LOCK   2
9386#define PENDING_LOCK    3
9387#define EXCLUSIVE_LOCK  4
9388
9389/*
9390** File Locking Notes:  (Mostly about windows but also some info for Unix)
9391**
9392** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9393** those functions are not available.  So we use only LockFile() and
9394** UnlockFile().
9395**
9396** LockFile() prevents not just writing but also reading by other processes.
9397** A SHARED_LOCK is obtained by locking a single randomly-chosen
9398** byte out of a specific range of bytes. The lock byte is obtained at
9399** random so two separate readers can probably access the file at the
9400** same time, unless they are unlucky and choose the same lock byte.
9401** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9402** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9403** a single byte of the file that is designated as the reserved lock byte.
9404** A PENDING_LOCK is obtained by locking a designated byte different from
9405** the RESERVED_LOCK byte.
9406**
9407** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9408** which means we can use reader/writer locks.  When reader/writer locks
9409** are used, the lock is placed on the same range of bytes that is used
9410** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9411** will support two or more Win95 readers or two or more WinNT readers.
9412** But a single Win95 reader will lock out all WinNT readers and a single
9413** WinNT reader will lock out all other Win95 readers.
9414**
9415** The following #defines specify the range of bytes used for locking.
9416** SHARED_SIZE is the number of bytes available in the pool from which
9417** a random byte is selected for a shared lock.  The pool of bytes for
9418** shared locks begins at SHARED_FIRST.
9419**
9420** The same locking strategy and
9421** byte ranges are used for Unix.  This leaves open the possiblity of having
9422** clients on win95, winNT, and unix all talking to the same shared file
9423** and all locking correctly.  To do so would require that samba (or whatever
9424** tool is being used for file sharing) implements locks correctly between
9425** windows and unix.  I'm guessing that isn't likely to happen, but by
9426** using the same locking range we are at least open to the possibility.
9427**
9428** Locking in windows is manditory.  For this reason, we cannot store
9429** actual data in the bytes used for locking.  The pager never allocates
9430** the pages involved in locking therefore.  SHARED_SIZE is selected so
9431** that all locks will fit on a single page even at the minimum page size.
9432** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9433** is set high so that we don't have to allocate an unused page except
9434** for very large databases.  But one should test the page skipping logic
9435** by setting PENDING_BYTE low and running the entire regression suite.
9436**
9437** Changing the value of PENDING_BYTE results in a subtly incompatible
9438** file format.  Depending on how it is changed, you might not notice
9439** the incompatibility right away, even running a full regression test.
9440** The default location of PENDING_BYTE is the first byte past the
9441** 1GB boundary.
9442**
9443*/
9444#ifdef SQLITE_OMIT_WSD
9445# define PENDING_BYTE     (0x40000000)
9446#else
9447# define PENDING_BYTE      sqlite3PendingByte
9448#endif
9449#define RESERVED_BYTE     (PENDING_BYTE+1)
9450#define SHARED_FIRST      (PENDING_BYTE+2)
9451#define SHARED_SIZE       510
9452
9453/*
9454** Wrapper around OS specific sqlite3_os_init() function.
9455*/
9456SQLITE_PRIVATE int sqlite3OsInit(void);
9457
9458/*
9459** Functions for accessing sqlite3_file methods
9460*/
9461SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9462SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9463SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9464SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9465SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9466SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9467SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9468SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9469SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9470SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9471SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9472#define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9473SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9474SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9475SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9476SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9477SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9478SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9479
9480
9481/*
9482** Functions for accessing sqlite3_vfs methods
9483*/
9484SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9485SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9486SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9487SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9488#ifndef SQLITE_OMIT_LOAD_EXTENSION
9489SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9490SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9491SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9492SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9493#endif /* SQLITE_OMIT_LOAD_EXTENSION */
9494SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9495SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9496SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9497
9498/*
9499** Convenience functions for opening and closing files using
9500** sqlite3_malloc() to obtain space for the file-handle structure.
9501*/
9502SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9503SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9504
9505#endif /* _SQLITE_OS_H_ */
9506
9507/************** End of os.h **************************************************/
9508/************** Continuing where we left off in sqliteInt.h ******************/
9509/************** Include mutex.h in the middle of sqliteInt.h *****************/
9510/************** Begin file mutex.h *******************************************/
9511/*
9512** 2007 August 28
9513**
9514** The author disclaims copyright to this source code.  In place of
9515** a legal notice, here is a blessing:
9516**
9517**    May you do good and not evil.
9518**    May you find forgiveness for yourself and forgive others.
9519**    May you share freely, never taking more than you give.
9520**
9521*************************************************************************
9522**
9523** This file contains the common header for all mutex implementations.
9524** The sqliteInt.h header #includes this file so that it is available
9525** to all source files.  We break it out in an effort to keep the code
9526** better organized.
9527**
9528** NOTE:  source files should *not* #include this header file directly.
9529** Source files should #include the sqliteInt.h file and let that file
9530** include this one indirectly.
9531*/
9532
9533
9534/*
9535** Figure out what version of the code to use.  The choices are
9536**
9537**   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9538**                             mutexes implemention cannot be overridden
9539**                             at start-time.
9540**
9541**   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9542**                             mutual exclusion is provided.  But this
9543**                             implementation can be overridden at
9544**                             start-time.
9545**
9546**   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9547**
9548**   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9549**
9550**   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
9551*/
9552#if !SQLITE_THREADSAFE
9553# define SQLITE_MUTEX_OMIT
9554#endif
9555#if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9556#  if SQLITE_OS_UNIX
9557#    define SQLITE_MUTEX_PTHREADS
9558#  elif SQLITE_OS_WIN
9559#    define SQLITE_MUTEX_W32
9560#  elif SQLITE_OS_OS2
9561#    define SQLITE_MUTEX_OS2
9562#  else
9563#    define SQLITE_MUTEX_NOOP
9564#  endif
9565#endif
9566
9567#ifdef SQLITE_MUTEX_OMIT
9568/*
9569** If this is a no-op implementation, implement everything as macros.
9570*/
9571#define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9572#define sqlite3_mutex_free(X)
9573#define sqlite3_mutex_enter(X)
9574#define sqlite3_mutex_try(X)      SQLITE_OK
9575#define sqlite3_mutex_leave(X)
9576#define sqlite3_mutex_held(X)     ((void)(X),1)
9577#define sqlite3_mutex_notheld(X)  ((void)(X),1)
9578#define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9579#define sqlite3MutexInit()        SQLITE_OK
9580#define sqlite3MutexEnd()
9581#define MUTEX_LOGIC(X)
9582#else
9583#define MUTEX_LOGIC(X)            X
9584#endif /* defined(SQLITE_MUTEX_OMIT) */
9585
9586/************** End of mutex.h ***********************************************/
9587/************** Continuing where we left off in sqliteInt.h ******************/
9588
9589
9590/*
9591** Each database file to be accessed by the system is an instance
9592** of the following structure.  There are normally two of these structures
9593** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9594** aDb[1] is the database file used to hold temporary tables.  Additional
9595** databases may be attached.
9596*/
9597struct Db {
9598  char *zName;         /* Name of this database */
9599  Btree *pBt;          /* The B*Tree structure for this database file */
9600  u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9601  u8 safety_level;     /* How aggressive at syncing data to disk */
9602  Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9603};
9604
9605/*
9606** An instance of the following structure stores a database schema.
9607**
9608** Most Schema objects are associated with a Btree.  The exception is
9609** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9610** In shared cache mode, a single Schema object can be shared by multiple
9611** Btrees that refer to the same underlying BtShared object.
9612**
9613** Schema objects are automatically deallocated when the last Btree that
9614** references them is destroyed.   The TEMP Schema is manually freed by
9615** sqlite3_close().
9616*
9617** A thread must be holding a mutex on the corresponding Btree in order
9618** to access Schema content.  This implies that the thread must also be
9619** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9620** For a TEMP Schema, only the connection mutex is required.
9621*/
9622struct Schema {
9623  int schema_cookie;   /* Database schema version number for this file */
9624  int iGeneration;     /* Generation counter.  Incremented with each change */
9625  Hash tblHash;        /* All tables indexed by name */
9626  Hash idxHash;        /* All (named) indices indexed by name */
9627  Hash trigHash;       /* All triggers indexed by name */
9628  Hash fkeyHash;       /* All foreign keys by referenced table name */
9629  Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9630  u8 file_format;      /* Schema format version for this file */
9631  u8 enc;              /* Text encoding used by this database */
9632  u16 flags;           /* Flags associated with this schema */
9633  int cache_size;      /* Number of pages to use in the cache */
9634};
9635
9636/*
9637** These macros can be used to test, set, or clear bits in the
9638** Db.pSchema->flags field.
9639*/
9640#define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9641#define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9642#define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9643#define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9644
9645/*
9646** Allowed values for the DB.pSchema->flags field.
9647**
9648** The DB_SchemaLoaded flag is set after the database schema has been
9649** read into internal hash tables.
9650**
9651** DB_UnresetViews means that one or more views have column names that
9652** have been filled out.  If the schema changes, these column names might
9653** changes and so the view will need to be reset.
9654*/
9655#define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9656#define DB_UnresetViews    0x0002  /* Some views have defined column names */
9657#define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9658
9659/*
9660** The number of different kinds of things that can be limited
9661** using the sqlite3_limit() interface.
9662*/
9663#define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9664
9665/*
9666** Lookaside malloc is a set of fixed-size buffers that can be used
9667** to satisfy small transient memory allocation requests for objects
9668** associated with a particular database connection.  The use of
9669** lookaside malloc provides a significant performance enhancement
9670** (approx 10%) by avoiding numerous malloc/free requests while parsing
9671** SQL statements.
9672**
9673** The Lookaside structure holds configuration information about the
9674** lookaside malloc subsystem.  Each available memory allocation in
9675** the lookaside subsystem is stored on a linked list of LookasideSlot
9676** objects.
9677**
9678** Lookaside allocations are only allowed for objects that are associated
9679** with a particular database connection.  Hence, schema information cannot
9680** be stored in lookaside because in shared cache mode the schema information
9681** is shared by multiple database connections.  Therefore, while parsing
9682** schema information, the Lookaside.bEnabled flag is cleared so that
9683** lookaside allocations are not used to construct the schema objects.
9684*/
9685struct Lookaside {
9686  u16 sz;                 /* Size of each buffer in bytes */
9687  u8 bEnabled;            /* False to disable new lookaside allocations */
9688  u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
9689  int nOut;               /* Number of buffers currently checked out */
9690  int mxOut;              /* Highwater mark for nOut */
9691  int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
9692  LookasideSlot *pFree;   /* List of available buffers */
9693  void *pStart;           /* First byte of available memory space */
9694  void *pEnd;             /* First byte past end of available space */
9695};
9696struct LookasideSlot {
9697  LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
9698};
9699
9700/*
9701** A hash table for function definitions.
9702**
9703** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
9704** Collisions are on the FuncDef.pHash chain.
9705*/
9706struct FuncDefHash {
9707  FuncDef *a[23];       /* Hash table for functions */
9708};
9709
9710/*
9711** Each database connection is an instance of the following structure.
9712*/
9713struct sqlite3 {
9714  sqlite3_vfs *pVfs;            /* OS Interface */
9715  struct Vdbe *pVdbe;           /* List of active virtual machines */
9716  CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
9717  sqlite3_mutex *mutex;         /* Connection mutex */
9718  Db *aDb;                      /* All backends */
9719  int nDb;                      /* Number of backends currently in use */
9720  int flags;                    /* Miscellaneous flags. See below */
9721  i64 lastRowid;                /* ROWID of most recent insert (see above) */
9722  unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
9723  int errCode;                  /* Most recent error code (SQLITE_*) */
9724  int errMask;                  /* & result codes with this before returning */
9725  u8 autoCommit;                /* The auto-commit flag. */
9726  u8 temp_store;                /* 1: file 2: memory 0: default */
9727  u8 mallocFailed;              /* True if we have seen a malloc failure */
9728  u8 dfltLockMode;              /* Default locking-mode for attached dbs */
9729  signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
9730  u8 suppressErr;               /* Do not issue error messages if true */
9731  u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
9732  u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
9733  int nextPagesize;             /* Pagesize after VACUUM if >0 */
9734  u32 magic;                    /* Magic number for detect library misuse */
9735  int nChange;                  /* Value returned by sqlite3_changes() */
9736  int nTotalChange;             /* Value returned by sqlite3_total_changes() */
9737  int aLimit[SQLITE_N_LIMIT];   /* Limits */
9738  struct sqlite3InitInfo {      /* Information used during initialization */
9739    int newTnum;                /* Rootpage of table being initialized */
9740    u8 iDb;                     /* Which db file is being initialized */
9741    u8 busy;                    /* TRUE if currently initializing */
9742    u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
9743  } init;
9744  int activeVdbeCnt;            /* Number of VDBEs currently executing */
9745  int writeVdbeCnt;             /* Number of active VDBEs that are writing */
9746  int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
9747  int nExtension;               /* Number of loaded extensions */
9748  void **aExtension;            /* Array of shared library handles */
9749  void (*xTrace)(void*,const char*);        /* Trace function */
9750  void *pTraceArg;                          /* Argument to the trace function */
9751  void (*xProfile)(void*,const char*,u64);  /* Profiling function */
9752  void *pProfileArg;                        /* Argument to profile function */
9753  void *pCommitArg;                 /* Argument to xCommitCallback() */
9754  int (*xCommitCallback)(void*);    /* Invoked at every commit. */
9755  void *pRollbackArg;               /* Argument to xRollbackCallback() */
9756  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
9757  void *pUpdateArg;
9758  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
9759#ifndef SQLITE_OMIT_WAL
9760  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
9761  void *pWalArg;
9762#endif
9763  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
9764  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
9765  void *pCollNeededArg;
9766  sqlite3_value *pErr;          /* Most recent error message */
9767  char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
9768  char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
9769  union {
9770    volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
9771    double notUsed1;            /* Spacer */
9772  } u1;
9773  Lookaside lookaside;          /* Lookaside malloc configuration */
9774#ifndef SQLITE_OMIT_AUTHORIZATION
9775  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
9776                                /* Access authorization function */
9777  void *pAuthArg;               /* 1st argument to the access auth function */
9778#endif
9779#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
9780  int (*xProgress)(void *);     /* The progress callback */
9781  void *pProgressArg;           /* Argument to the progress callback */
9782  int nProgressOps;             /* Number of opcodes for progress callback */
9783#endif
9784#ifndef SQLITE_OMIT_VIRTUALTABLE
9785  int nVTrans;                  /* Allocated size of aVTrans */
9786  Hash aModule;                 /* populated by sqlite3_create_module() */
9787  VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
9788  VTable **aVTrans;             /* Virtual tables with open transactions */
9789  VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
9790#endif
9791  FuncDefHash aFunc;            /* Hash table of connection functions */
9792  Hash aCollSeq;                /* All collating sequences */
9793  BusyHandler busyHandler;      /* Busy callback */
9794  Db aDbStatic[2];              /* Static space for the 2 default backends */
9795  Savepoint *pSavepoint;        /* List of active savepoints */
9796  int busyTimeout;              /* Busy handler timeout, in msec */
9797  int nSavepoint;               /* Number of non-transaction savepoints */
9798  int nStatement;               /* Number of nested statement-transactions  */
9799  i64 nDeferredCons;            /* Net deferred constraints this transaction. */
9800  int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
9801
9802#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
9803  /* The following variables are all protected by the STATIC_MASTER
9804  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
9805  **
9806  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
9807  ** unlock so that it can proceed.
9808  **
9809  ** When X.pBlockingConnection==Y, that means that something that X tried
9810  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
9811  ** held by Y.
9812  */
9813  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
9814  sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
9815  void *pUnlockArg;                     /* Argument to xUnlockNotify */
9816  void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
9817  sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
9818#endif
9819};
9820
9821/*
9822** A macro to discover the encoding of a database.
9823*/
9824#define ENC(db) ((db)->aDb[0].pSchema->enc)
9825
9826/*
9827** Possible values for the sqlite3.flags.
9828*/
9829#define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
9830#define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
9831#define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
9832#define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
9833#define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
9834                                          /*   DELETE, or UPDATE and return */
9835                                          /*   the count using a callback. */
9836#define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
9837                                          /*   result set is empty */
9838#define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
9839#define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
9840#define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
9841                         /*   0x00020000  Unused */
9842#define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
9843#define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
9844#define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
9845#define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
9846#define SQLITE_CkptFullFSync  0x00400000  /* Use full fsync for checkpoint */
9847#define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
9848#define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
9849#define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
9850#define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
9851#define SQLITE_AutoIndex      0x08000000  /* Enable automatic indexes */
9852#define SQLITE_PreferBuiltin  0x10000000  /* Preference to built-in funcs */
9853#define SQLITE_LoadExtension  0x20000000  /* Enable load_extension */
9854#define SQLITE_EnableTrigger  0x40000000  /* True to enable triggers */
9855
9856/*
9857** Bits of the sqlite3.flags field that are used by the
9858** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
9859** These must be the low-order bits of the flags field.
9860*/
9861#define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
9862#define SQLITE_ColumnCache    0x02        /* Disable the column cache */
9863#define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
9864#define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
9865#define SQLITE_IndexCover     0x10        /* Disable index covering table */
9866#define SQLITE_GroupByOrder   0x20        /* Disable GROUPBY cover of ORDERBY */
9867#define SQLITE_FactorOutConst 0x40        /* Disable factoring out constants */
9868#define SQLITE_IdxRealAsInt   0x80        /* Store REAL as INT in indices */
9869#define SQLITE_DistinctOpt    0x80        /* DISTINCT using indexes */
9870#define SQLITE_OptMask        0xff        /* Mask of all disablable opts */
9871
9872/*
9873** Possible values for the sqlite.magic field.
9874** The numbers are obtained at random and have no special meaning, other
9875** than being distinct from one another.
9876*/
9877#define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
9878#define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
9879#define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
9880#define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
9881#define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
9882
9883/*
9884** Each SQL function is defined by an instance of the following
9885** structure.  A pointer to this structure is stored in the sqlite.aFunc
9886** hash table.  When multiple functions have the same name, the hash table
9887** points to a linked list of these structures.
9888*/
9889struct FuncDef {
9890  i16 nArg;            /* Number of arguments.  -1 means unlimited */
9891  u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
9892  u8 flags;            /* Some combination of SQLITE_FUNC_* */
9893  void *pUserData;     /* User data parameter */
9894  FuncDef *pNext;      /* Next function with same name */
9895  void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
9896  void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
9897  void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
9898  char *zName;         /* SQL name of the function. */
9899  FuncDef *pHash;      /* Next with a different name but the same hash */
9900  FuncDestructor *pDestructor;   /* Reference counted destructor function */
9901};
9902
9903/*
9904** This structure encapsulates a user-function destructor callback (as
9905** configured using create_function_v2()) and a reference counter. When
9906** create_function_v2() is called to create a function with a destructor,
9907** a single object of this type is allocated. FuncDestructor.nRef is set to
9908** the number of FuncDef objects created (either 1 or 3, depending on whether
9909** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
9910** member of each of the new FuncDef objects is set to point to the allocated
9911** FuncDestructor.
9912**
9913** Thereafter, when one of the FuncDef objects is deleted, the reference
9914** count on this object is decremented. When it reaches 0, the destructor
9915** is invoked and the FuncDestructor structure freed.
9916*/
9917struct FuncDestructor {
9918  int nRef;
9919  void (*xDestroy)(void *);
9920  void *pUserData;
9921};
9922
9923/*
9924** Possible values for FuncDef.flags
9925*/
9926#define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
9927#define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
9928#define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
9929#define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
9930#define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
9931#define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
9932
9933/*
9934** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
9935** used to create the initializers for the FuncDef structures.
9936**
9937**   FUNCTION(zName, nArg, iArg, bNC, xFunc)
9938**     Used to create a scalar function definition of a function zName
9939**     implemented by C function xFunc that accepts nArg arguments. The
9940**     value passed as iArg is cast to a (void*) and made available
9941**     as the user-data (sqlite3_user_data()) for the function. If
9942**     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
9943**
9944**   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
9945**     Used to create an aggregate function definition implemented by
9946**     the C functions xStep and xFinal. The first four parameters
9947**     are interpreted in the same way as the first 4 parameters to
9948**     FUNCTION().
9949**
9950**   LIKEFUNC(zName, nArg, pArg, flags)
9951**     Used to create a scalar function definition of a function zName
9952**     that accepts nArg arguments and is implemented by a call to C
9953**     function likeFunc. Argument pArg is cast to a (void *) and made
9954**     available as the function user-data (sqlite3_user_data()). The
9955**     FuncDef.flags variable is set to the value passed as the flags
9956**     parameter.
9957*/
9958#define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
9959  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9960   SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
9961#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
9962  {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
9963   pArg, 0, xFunc, 0, 0, #zName, 0, 0}
9964#define LIKEFUNC(zName, nArg, arg, flags) \
9965  {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
9966#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
9967  {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
9968   SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
9969
9970/*
9971** All current savepoints are stored in a linked list starting at
9972** sqlite3.pSavepoint. The first element in the list is the most recently
9973** opened savepoint. Savepoints are added to the list by the vdbe
9974** OP_Savepoint instruction.
9975*/
9976struct Savepoint {
9977  char *zName;                        /* Savepoint name (nul-terminated) */
9978  i64 nDeferredCons;                  /* Number of deferred fk violations */
9979  Savepoint *pNext;                   /* Parent savepoint (if any) */
9980};
9981
9982/*
9983** The following are used as the second parameter to sqlite3Savepoint(),
9984** and as the P1 argument to the OP_Savepoint instruction.
9985*/
9986#define SAVEPOINT_BEGIN      0
9987#define SAVEPOINT_RELEASE    1
9988#define SAVEPOINT_ROLLBACK   2
9989
9990
9991/*
9992** Each SQLite module (virtual table definition) is defined by an
9993** instance of the following structure, stored in the sqlite3.aModule
9994** hash table.
9995*/
9996struct Module {
9997  const sqlite3_module *pModule;       /* Callback pointers */
9998  const char *zName;                   /* Name passed to create_module() */
9999  void *pAux;                          /* pAux passed to create_module() */
10000  void (*xDestroy)(void *);            /* Module destructor function */
10001};
10002
10003/*
10004** information about each column of an SQL table is held in an instance
10005** of this structure.
10006*/
10007struct Column {
10008  char *zName;     /* Name of this column */
10009  Expr *pDflt;     /* Default value of this column */
10010  char *zDflt;     /* Original text of the default value */
10011  char *zType;     /* Data type for this column */
10012  char *zColl;     /* Collating sequence.  If NULL, use the default */
10013  u8 notNull;      /* True if there is a NOT NULL constraint */
10014  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
10015  char affinity;   /* One of the SQLITE_AFF_... values */
10016#ifndef SQLITE_OMIT_VIRTUALTABLE
10017  u8 isHidden;     /* True if this column is 'hidden' */
10018#endif
10019};
10020
10021/*
10022** A "Collating Sequence" is defined by an instance of the following
10023** structure. Conceptually, a collating sequence consists of a name and
10024** a comparison routine that defines the order of that sequence.
10025**
10026** There may two separate implementations of the collation function, one
10027** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
10028** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
10029** native byte order. When a collation sequence is invoked, SQLite selects
10030** the version that will require the least expensive encoding
10031** translations, if any.
10032**
10033** The CollSeq.pUser member variable is an extra parameter that passed in
10034** as the first argument to the UTF-8 comparison function, xCmp.
10035** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
10036** xCmp16.
10037**
10038** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
10039** collating sequence is undefined.  Indices built on an undefined
10040** collating sequence may not be read or written.
10041*/
10042struct CollSeq {
10043  char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10044  u8 enc;               /* Text encoding handled by xCmp() */
10045  void *pUser;          /* First argument to xCmp() */
10046  int (*xCmp)(void*,int, const void*, int, const void*);
10047  void (*xDel)(void*);  /* Destructor for pUser */
10048};
10049
10050/*
10051** A sort order can be either ASC or DESC.
10052*/
10053#define SQLITE_SO_ASC       0  /* Sort in ascending order */
10054#define SQLITE_SO_DESC      1  /* Sort in ascending order */
10055
10056/*
10057** Column affinity types.
10058**
10059** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10060** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10061** the speed a little by numbering the values consecutively.
10062**
10063** But rather than start with 0 or 1, we begin with 'a'.  That way,
10064** when multiple affinity types are concatenated into a string and
10065** used as the P4 operand, they will be more readable.
10066**
10067** Note also that the numeric types are grouped together so that testing
10068** for a numeric type is a single comparison.
10069*/
10070#define SQLITE_AFF_TEXT     'a'
10071#define SQLITE_AFF_NONE     'b'
10072#define SQLITE_AFF_NUMERIC  'c'
10073#define SQLITE_AFF_INTEGER  'd'
10074#define SQLITE_AFF_REAL     'e'
10075
10076#define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10077
10078/*
10079** The SQLITE_AFF_MASK values masks off the significant bits of an
10080** affinity value.
10081*/
10082#define SQLITE_AFF_MASK     0x67
10083
10084/*
10085** Additional bit values that can be ORed with an affinity without
10086** changing the affinity.
10087*/
10088#define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10089#define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10090#define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10091
10092/*
10093** An object of this type is created for each virtual table present in
10094** the database schema.
10095**
10096** If the database schema is shared, then there is one instance of this
10097** structure for each database connection (sqlite3*) that uses the shared
10098** schema. This is because each database connection requires its own unique
10099** instance of the sqlite3_vtab* handle used to access the virtual table
10100** implementation. sqlite3_vtab* handles can not be shared between
10101** database connections, even when the rest of the in-memory database
10102** schema is shared, as the implementation often stores the database
10103** connection handle passed to it via the xConnect() or xCreate() method
10104** during initialization internally. This database connection handle may
10105** then be used by the virtual table implementation to access real tables
10106** within the database. So that they appear as part of the callers
10107** transaction, these accesses need to be made via the same database
10108** connection as that used to execute SQL operations on the virtual table.
10109**
10110** All VTable objects that correspond to a single table in a shared
10111** database schema are initially stored in a linked-list pointed to by
10112** the Table.pVTable member variable of the corresponding Table object.
10113** When an sqlite3_prepare() operation is required to access the virtual
10114** table, it searches the list for the VTable that corresponds to the
10115** database connection doing the preparing so as to use the correct
10116** sqlite3_vtab* handle in the compiled query.
10117**
10118** When an in-memory Table object is deleted (for example when the
10119** schema is being reloaded for some reason), the VTable objects are not
10120** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
10121** immediately. Instead, they are moved from the Table.pVTable list to
10122** another linked list headed by the sqlite3.pDisconnect member of the
10123** corresponding sqlite3 structure. They are then deleted/xDisconnected
10124** next time a statement is prepared using said sqlite3*. This is done
10125** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10126** Refer to comments above function sqlite3VtabUnlockList() for an
10127** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10128** list without holding the corresponding sqlite3.mutex mutex.
10129**
10130** The memory for objects of this type is always allocated by
10131** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
10132** the first argument.
10133*/
10134struct VTable {
10135  sqlite3 *db;              /* Database connection associated with this table */
10136  Module *pMod;             /* Pointer to module implementation */
10137  sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10138  int nRef;                 /* Number of pointers to this structure */
10139  u8 bConstraint;           /* True if constraints are supported */
10140  int iSavepoint;           /* Depth of the SAVEPOINT stack */
10141  VTable *pNext;            /* Next in linked list (see above) */
10142};
10143
10144/*
10145** Each SQL table is represented in memory by an instance of the
10146** following structure.
10147**
10148** Table.zName is the name of the table.  The case of the original
10149** CREATE TABLE statement is stored, but case is not significant for
10150** comparisons.
10151**
10152** Table.nCol is the number of columns in this table.  Table.aCol is a
10153** pointer to an array of Column structures, one for each column.
10154**
10155** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10156** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10157** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10158** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10159** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10160** is generated for each row of the table.  TF_HasPrimaryKey is set if
10161** the table has any PRIMARY KEY, INTEGER or otherwise.
10162**
10163** Table.tnum is the page number for the root BTree page of the table in the
10164** database file.  If Table.iDb is the index of the database table backend
10165** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10166** holds temporary tables and indices.  If TF_Ephemeral is set
10167** then the table is stored in a file that is automatically deleted
10168** when the VDBE cursor to the table is closed.  In this case Table.tnum
10169** refers VDBE cursor number that holds the table open, not to the root
10170** page number.  Transient tables are used to hold the results of a
10171** sub-query that appears instead of a real table name in the FROM clause
10172** of a SELECT statement.
10173*/
10174struct Table {
10175  char *zName;         /* Name of the table or view */
10176  int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10177  int nCol;            /* Number of columns in this table */
10178  Column *aCol;        /* Information about each column */
10179  Index *pIndex;       /* List of SQL indexes on this table. */
10180  int tnum;            /* Root BTree node for this table (see note above) */
10181  tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10182  Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10183  u16 nRef;            /* Number of pointers to this Table */
10184  u8 tabFlags;         /* Mask of TF_* values */
10185  u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10186  FKey *pFKey;         /* Linked list of all foreign keys in this table */
10187  char *zColAff;       /* String defining the affinity of each column */
10188#ifndef SQLITE_OMIT_CHECK
10189  Expr *pCheck;        /* The AND of all CHECK constraints */
10190#endif
10191#ifndef SQLITE_OMIT_ALTERTABLE
10192  int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10193#endif
10194#ifndef SQLITE_OMIT_VIRTUALTABLE
10195  VTable *pVTable;     /* List of VTable objects. */
10196  int nModuleArg;      /* Number of arguments to the module */
10197  char **azModuleArg;  /* Text of all module args. [0] is module name */
10198#endif
10199  Trigger *pTrigger;   /* List of triggers stored in pSchema */
10200  Schema *pSchema;     /* Schema that contains this table */
10201  Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10202};
10203
10204/*
10205** Allowed values for Tabe.tabFlags.
10206*/
10207#define TF_Readonly        0x01    /* Read-only system table */
10208#define TF_Ephemeral       0x02    /* An ephemeral table */
10209#define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10210#define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10211#define TF_Virtual         0x10    /* Is a virtual table */
10212
10213
10214/*
10215** Test to see whether or not a table is a virtual table.  This is
10216** done as a macro so that it will be optimized out when virtual
10217** table support is omitted from the build.
10218*/
10219#ifndef SQLITE_OMIT_VIRTUALTABLE
10220#  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10221#  define IsHiddenColumn(X) ((X)->isHidden)
10222#else
10223#  define IsVirtual(X)      0
10224#  define IsHiddenColumn(X) 0
10225#endif
10226
10227/*
10228** Each foreign key constraint is an instance of the following structure.
10229**
10230** A foreign key is associated with two tables.  The "from" table is
10231** the table that contains the REFERENCES clause that creates the foreign
10232** key.  The "to" table is the table that is named in the REFERENCES clause.
10233** Consider this example:
10234**
10235**     CREATE TABLE ex1(
10236**       a INTEGER PRIMARY KEY,
10237**       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10238**     );
10239**
10240** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10241**
10242** Each REFERENCES clause generates an instance of the following structure
10243** which is attached to the from-table.  The to-table need not exist when
10244** the from-table is created.  The existence of the to-table is not checked.
10245*/
10246struct FKey {
10247  Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10248  FKey *pNextFrom;  /* Next foreign key in pFrom */
10249  char *zTo;        /* Name of table that the key points to (aka: Parent) */
10250  FKey *pNextTo;    /* Next foreign key on table named zTo */
10251  FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10252  int nCol;         /* Number of columns in this key */
10253  /* EV: R-30323-21917 */
10254  u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10255  u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10256  Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10257  struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10258    int iFrom;         /* Index of column in pFrom */
10259    char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10260  } aCol[1];        /* One entry for each of nCol column s */
10261};
10262
10263/*
10264** SQLite supports many different ways to resolve a constraint
10265** error.  ROLLBACK processing means that a constraint violation
10266** causes the operation in process to fail and for the current transaction
10267** to be rolled back.  ABORT processing means the operation in process
10268** fails and any prior changes from that one operation are backed out,
10269** but the transaction is not rolled back.  FAIL processing means that
10270** the operation in progress stops and returns an error code.  But prior
10271** changes due to the same operation are not backed out and no rollback
10272** occurs.  IGNORE means that the particular row that caused the constraint
10273** error is not inserted or updated.  Processing continues and no error
10274** is returned.  REPLACE means that preexisting database rows that caused
10275** a UNIQUE constraint violation are removed so that the new insert or
10276** update can proceed.  Processing continues and no error is reported.
10277**
10278** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10279** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10280** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10281** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10282** referenced table row is propagated into the row that holds the
10283** foreign key.
10284**
10285** The following symbolic values are used to record which type
10286** of action to take.
10287*/
10288#define OE_None     0   /* There is no constraint to check */
10289#define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10290#define OE_Abort    2   /* Back out changes but do no rollback transaction */
10291#define OE_Fail     3   /* Stop the operation but leave all prior changes */
10292#define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10293#define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10294
10295#define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10296#define OE_SetNull  7   /* Set the foreign key value to NULL */
10297#define OE_SetDflt  8   /* Set the foreign key value to its default */
10298#define OE_Cascade  9   /* Cascade the changes */
10299
10300#define OE_Default  99  /* Do whatever the default action is */
10301
10302
10303/*
10304** An instance of the following structure is passed as the first
10305** argument to sqlite3VdbeKeyCompare and is used to control the
10306** comparison of the two index keys.
10307*/
10308struct KeyInfo {
10309  sqlite3 *db;        /* The database connection */
10310  u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10311  u16 nField;         /* Number of entries in aColl[] */
10312  u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10313  CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10314};
10315
10316/*
10317** An instance of the following structure holds information about a
10318** single index record that has already been parsed out into individual
10319** values.
10320**
10321** A record is an object that contains one or more fields of data.
10322** Records are used to store the content of a table row and to store
10323** the key of an index.  A blob encoding of a record is created by
10324** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10325** OP_Column opcode.
10326**
10327** This structure holds a record that has already been disassembled
10328** into its constituent fields.
10329*/
10330struct UnpackedRecord {
10331  KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10332  u16 nField;         /* Number of entries in apMem[] */
10333  u8 flags;           /* Boolean settings.  UNPACKED_... below */
10334  i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10335  Mem *aMem;          /* Values */
10336};
10337
10338/*
10339** Allowed values of UnpackedRecord.flags
10340*/
10341#define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10342#define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10343#define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
10344
10345/*
10346** Each SQL index is represented in memory by an
10347** instance of the following structure.
10348**
10349** The columns of the table that are to be indexed are described
10350** by the aiColumn[] field of this structure.  For example, suppose
10351** we have the following table and index:
10352**
10353**     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10354**     CREATE INDEX Ex2 ON Ex1(c3,c1);
10355**
10356** In the Table structure describing Ex1, nCol==3 because there are
10357** three columns in the table.  In the Index structure describing
10358** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10359** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the
10360** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10361** The second column to be indexed (c1) has an index of 0 in
10362** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10363**
10364** The Index.onError field determines whether or not the indexed columns
10365** must be unique and what to do if they are not.  When Index.onError=OE_None,
10366** it means this is not a unique index.  Otherwise it is a unique index
10367** and the value of Index.onError indicate the which conflict resolution
10368** algorithm to employ whenever an attempt is made to insert a non-unique
10369** element.
10370*/
10371struct Index {
10372  char *zName;     /* Name of this index */
10373  int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
10374  tRowcnt *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
10375  Table *pTable;   /* The SQL table being indexed */
10376  char *zColAff;   /* String defining the affinity of each column */
10377  Index *pNext;    /* The next index associated with the same table */
10378  Schema *pSchema; /* Schema containing this index */
10379  u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
10380  char **azColl;   /* Array of collation sequence names for index */
10381  int nColumn;     /* Number of columns in the table used by this index */
10382  int tnum;        /* Page containing root of this index in database file */
10383  u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10384  u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
10385  u8 bUnordered;   /* Use this index for == or IN queries only */
10386#ifdef SQLITE_ENABLE_STAT3
10387  int nSample;             /* Number of elements in aSample[] */
10388  tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10389  IndexSample *aSample;    /* Samples of the left-most key */
10390#endif
10391};
10392
10393/*
10394** Each sample stored in the sqlite_stat3 table is represented in memory
10395** using a structure of this type.  See documentation at the top of the
10396** analyze.c source file for additional information.
10397*/
10398struct IndexSample {
10399  union {
10400    char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10401    double r;       /* Value if eType is SQLITE_FLOAT */
10402    i64 i;          /* Value if eType is SQLITE_INTEGER */
10403  } u;
10404  u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10405  int nByte;        /* Size in byte of text or blob. */
10406  tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10407  tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10408  tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10409};
10410
10411/*
10412** Each token coming out of the lexer is an instance of
10413** this structure.  Tokens are also used as part of an expression.
10414**
10415** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10416** may contain random values.  Do not make any assumptions about Token.dyn
10417** and Token.n when Token.z==0.
10418*/
10419struct Token {
10420  const char *z;     /* Text of the token.  Not NULL-terminated! */
10421  unsigned int n;    /* Number of characters in this token */
10422};
10423
10424/*
10425** An instance of this structure contains information needed to generate
10426** code for a SELECT that contains aggregate functions.
10427**
10428** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10429** pointer to this structure.  The Expr.iColumn field is the index in
10430** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10431** code for that node.
10432**
10433** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10434** original Select structure that describes the SELECT statement.  These
10435** fields do not need to be freed when deallocating the AggInfo structure.
10436*/
10437struct AggInfo {
10438  u8 directMode;          /* Direct rendering mode means take data directly
10439                          ** from source tables rather than from accumulators */
10440  u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10441                          ** than the source table */
10442  int sortingIdx;         /* Cursor number of the sorting index */
10443  int sortingIdxPTab;     /* Cursor number of pseudo-table */
10444  int nSortingColumn;     /* Number of columns in the sorting index */
10445  ExprList *pGroupBy;     /* The group by clause */
10446  struct AggInfo_col {    /* For each column used in source tables */
10447    Table *pTab;             /* Source table */
10448    int iTable;              /* Cursor number of the source table */
10449    int iColumn;             /* Column number within the source table */
10450    int iSorterColumn;       /* Column number in the sorting index */
10451    int iMem;                /* Memory location that acts as accumulator */
10452    Expr *pExpr;             /* The original expression */
10453  } *aCol;
10454  int nColumn;            /* Number of used entries in aCol[] */
10455  int nAccumulator;       /* Number of columns that show through to the output.
10456                          ** Additional columns are used only as parameters to
10457                          ** aggregate functions */
10458  struct AggInfo_func {   /* For each aggregate function */
10459    Expr *pExpr;             /* Expression encoding the function */
10460    FuncDef *pFunc;          /* The aggregate function implementation */
10461    int iMem;                /* Memory location that acts as accumulator */
10462    int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10463  } *aFunc;
10464  int nFunc;              /* Number of entries in aFunc[] */
10465};
10466
10467/*
10468** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10469** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10470** than 32767 we have to make it 32-bit.  16-bit is preferred because
10471** it uses less memory in the Expr object, which is a big memory user
10472** in systems with lots of prepared statements.  And few applications
10473** need more than about 10 or 20 variables.  But some extreme users want
10474** to have prepared statements with over 32767 variables, and for them
10475** the option is available (at compile-time).
10476*/
10477#if SQLITE_MAX_VARIABLE_NUMBER<=32767
10478typedef i16 ynVar;
10479#else
10480typedef int ynVar;
10481#endif
10482
10483/*
10484** Each node of an expression in the parse tree is an instance
10485** of this structure.
10486**
10487** Expr.op is the opcode. The integer parser token codes are reused
10488** as opcodes here. For example, the parser defines TK_GE to be an integer
10489** code representing the ">=" operator. This same integer code is reused
10490** to represent the greater-than-or-equal-to operator in the expression
10491** tree.
10492**
10493** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
10494** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10495** the expression is a variable (TK_VARIABLE), then Expr.token contains the
10496** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10497** then Expr.token contains the name of the function.
10498**
10499** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10500** binary operator. Either or both may be NULL.
10501**
10502** Expr.x.pList is a list of arguments if the expression is an SQL function,
10503** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10504** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10505** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10506** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
10507** valid.
10508**
10509** An expression of the form ID or ID.ID refers to a column in a table.
10510** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10511** the integer cursor number of a VDBE cursor pointing to that table and
10512** Expr.iColumn is the column number for the specific column.  If the
10513** expression is used as a result in an aggregate SELECT, then the
10514** value is also stored in the Expr.iAgg column in the aggregate so that
10515** it can be accessed after all aggregates are computed.
10516**
10517** If the expression is an unbound variable marker (a question mark
10518** character '?' in the original SQL) then the Expr.iTable holds the index
10519** number for that variable.
10520**
10521** If the expression is a subquery then Expr.iColumn holds an integer
10522** register number containing the result of the subquery.  If the
10523** subquery gives a constant result, then iTable is -1.  If the subquery
10524** gives a different answer at different times during statement processing
10525** then iTable is the address of a subroutine that computes the subquery.
10526**
10527** If the Expr is of type OP_Column, and the table it is selecting from
10528** is a disk table or the "old.*" pseudo-table, then pTab points to the
10529** corresponding table definition.
10530**
10531** ALLOCATION NOTES:
10532**
10533** Expr objects can use a lot of memory space in database schema.  To
10534** help reduce memory requirements, sometimes an Expr object will be
10535** truncated.  And to reduce the number of memory allocations, sometimes
10536** two or more Expr objects will be stored in a single memory allocation,
10537** together with Expr.zToken strings.
10538**
10539** If the EP_Reduced and EP_TokenOnly flags are set when
10540** an Expr object is truncated.  When EP_Reduced is set, then all
10541** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10542** are contained within the same memory allocation.  Note, however, that
10543** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10544** allocated, regardless of whether or not EP_Reduced is set.
10545*/
10546struct Expr {
10547  u8 op;                 /* Operation performed by this node */
10548  char affinity;         /* The affinity of the column or 0 if not a column */
10549  u16 flags;             /* Various flags.  EP_* See below */
10550  union {
10551    char *zToken;          /* Token value. Zero terminated and dequoted */
10552    int iValue;            /* Non-negative integer value if EP_IntValue */
10553  } u;
10554
10555  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10556  ** space is allocated for the fields below this point. An attempt to
10557  ** access them will result in a segfault or malfunction.
10558  *********************************************************************/
10559
10560  Expr *pLeft;           /* Left subnode */
10561  Expr *pRight;          /* Right subnode */
10562  union {
10563    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10564    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10565  } x;
10566  CollSeq *pColl;        /* The collation type of the column or 0 */
10567
10568  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10569  ** space is allocated for the fields below this point. An attempt to
10570  ** access them will result in a segfault or malfunction.
10571  *********************************************************************/
10572
10573  int iTable;            /* TK_COLUMN: cursor number of table holding column
10574                         ** TK_REGISTER: register number
10575                         ** TK_TRIGGER: 1 -> new, 0 -> old */
10576  ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10577                         ** TK_VARIABLE: variable number (always >= 1). */
10578  i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10579  i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10580  u8 flags2;             /* Second set of flags.  EP2_... */
10581  u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
10582  AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10583  Table *pTab;           /* Table for TK_COLUMN expressions. */
10584#if SQLITE_MAX_EXPR_DEPTH>0
10585  int nHeight;           /* Height of the tree headed by this node */
10586#endif
10587};
10588
10589/*
10590** The following are the meanings of bits in the Expr.flags field.
10591*/
10592#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10593#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10594#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10595#define EP_Error      0x0008  /* Expression contains one or more errors */
10596#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10597#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10598#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10599#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10600#define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
10601#define EP_FixedDest  0x0200  /* Result needed in a specific register */
10602#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10603#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10604#define EP_Hint       0x1000  /* Optimizer hint. Not required for correctness */
10605#define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10606#define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10607#define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
10608
10609/*
10610** The following are the meanings of bits in the Expr.flags2 field.
10611*/
10612#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10613#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10614
10615/*
10616** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10617** flag on an expression structure.  This flag is used for VV&A only.  The
10618** routine is implemented as a macro that only works when in debugging mode,
10619** so as not to burden production code.
10620*/
10621#ifdef SQLITE_DEBUG
10622# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10623#else
10624# define ExprSetIrreducible(X)
10625#endif
10626
10627/*
10628** These macros can be used to test, set, or clear bits in the
10629** Expr.flags field.
10630*/
10631#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10632#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10633#define ExprSetProperty(E,P)     (E)->flags|=(P)
10634#define ExprClearProperty(E,P)   (E)->flags&=~(P)
10635
10636/*
10637** Macros to determine the number of bytes required by a normal Expr
10638** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
10639** and an Expr struct with the EP_TokenOnly flag set.
10640*/
10641#define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10642#define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10643#define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10644
10645/*
10646** Flags passed to the sqlite3ExprDup() function. See the header comment
10647** above sqlite3ExprDup() for details.
10648*/
10649#define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10650
10651/*
10652** A list of expressions.  Each expression may optionally have a
10653** name.  An expr/name combination can be used in several ways, such
10654** as the list of "expr AS ID" fields following a "SELECT" or in the
10655** list of "ID = expr" items in an UPDATE.  A list of expressions can
10656** also be used as the argument to a function, in which case the a.zName
10657** field is not used.
10658*/
10659struct ExprList {
10660  int nExpr;             /* Number of expressions on the list */
10661  int iECursor;          /* VDBE Cursor associated with this ExprList */
10662  struct ExprList_item { /* For each expression in the list */
10663    Expr *pExpr;           /* The list of expressions */
10664    char *zName;           /* Token associated with this expression */
10665    char *zSpan;           /* Original text of the expression */
10666    u8 sortOrder;          /* 1 for DESC or 0 for ASC */
10667    u8 done;               /* A flag to indicate when processing is finished */
10668    u16 iOrderByCol;       /* For ORDER BY, column number in result set */
10669    u16 iAlias;            /* Index into Parse.aAlias[] for zName */
10670  } *a;                  /* Alloc a power of two greater or equal to nExpr */
10671};
10672
10673/*
10674** An instance of this structure is used by the parser to record both
10675** the parse tree for an expression and the span of input text for an
10676** expression.
10677*/
10678struct ExprSpan {
10679  Expr *pExpr;          /* The expression parse tree */
10680  const char *zStart;   /* First character of input text */
10681  const char *zEnd;     /* One character past the end of input text */
10682};
10683
10684/*
10685** An instance of this structure can hold a simple list of identifiers,
10686** such as the list "a,b,c" in the following statements:
10687**
10688**      INSERT INTO t(a,b,c) VALUES ...;
10689**      CREATE INDEX idx ON t(a,b,c);
10690**      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
10691**
10692** The IdList.a.idx field is used when the IdList represents the list of
10693** column names after a table name in an INSERT statement.  In the statement
10694**
10695**     INSERT INTO t(a,b,c) ...
10696**
10697** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
10698*/
10699struct IdList {
10700  struct IdList_item {
10701    char *zName;      /* Name of the identifier */
10702    int idx;          /* Index in some Table.aCol[] of a column named zName */
10703  } *a;
10704  int nId;         /* Number of identifiers on the list */
10705};
10706
10707/*
10708** The bitmask datatype defined below is used for various optimizations.
10709**
10710** Changing this from a 64-bit to a 32-bit type limits the number of
10711** tables in a join to 32 instead of 64.  But it also reduces the size
10712** of the library by 738 bytes on ix86.
10713*/
10714typedef u64 Bitmask;
10715
10716/*
10717** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
10718*/
10719#define BMS  ((int)(sizeof(Bitmask)*8))
10720
10721/*
10722** The following structure describes the FROM clause of a SELECT statement.
10723** Each table or subquery in the FROM clause is a separate element of
10724** the SrcList.a[] array.
10725**
10726** With the addition of multiple database support, the following structure
10727** can also be used to describe a particular table such as the table that
10728** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
10729** such a table must be a simple name: ID.  But in SQLite, the table can
10730** now be identified by a database name, a dot, then the table name: ID.ID.
10731**
10732** The jointype starts out showing the join type between the current table
10733** and the next table on the list.  The parser builds the list this way.
10734** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
10735** jointype expresses the join between the table and the previous table.
10736**
10737** In the colUsed field, the high-order bit (bit 63) is set if the table
10738** contains more than 63 columns and the 64-th or later column is used.
10739*/
10740struct SrcList {
10741  i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
10742  i16 nAlloc;      /* Number of entries allocated in a[] below */
10743  struct SrcList_item {
10744    char *zDatabase;  /* Name of database holding this table */
10745    char *zName;      /* Name of the table */
10746    char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
10747    Table *pTab;      /* An SQL table corresponding to zName */
10748    Select *pSelect;  /* A SELECT statement used in place of a table name */
10749    int addrFillSub;  /* Address of subroutine to manifest a subquery */
10750    int regReturn;    /* Register holding return address of addrFillSub */
10751    u8 jointype;      /* Type of join between this able and the previous */
10752    u8 notIndexed;    /* True if there is a NOT INDEXED clause */
10753    u8 isCorrelated;  /* True if sub-query is correlated */
10754#ifndef SQLITE_OMIT_EXPLAIN
10755    u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
10756#endif
10757    int iCursor;      /* The VDBE cursor number used to access this table */
10758    Expr *pOn;        /* The ON clause of a join */
10759    IdList *pUsing;   /* The USING clause of a join */
10760    Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
10761    char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
10762    Index *pIndex;    /* Index structure corresponding to zIndex, if any */
10763  } a[1];             /* One entry for each identifier on the list */
10764};
10765
10766/*
10767** Permitted values of the SrcList.a.jointype field
10768*/
10769#define JT_INNER     0x0001    /* Any kind of inner or cross join */
10770#define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
10771#define JT_NATURAL   0x0004    /* True for a "natural" join */
10772#define JT_LEFT      0x0008    /* Left outer join */
10773#define JT_RIGHT     0x0010    /* Right outer join */
10774#define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
10775#define JT_ERROR     0x0040    /* unknown or unsupported join type */
10776
10777
10778/*
10779** A WherePlan object holds information that describes a lookup
10780** strategy.
10781**
10782** This object is intended to be opaque outside of the where.c module.
10783** It is included here only so that that compiler will know how big it
10784** is.  None of the fields in this object should be used outside of
10785** the where.c module.
10786**
10787** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
10788** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
10789** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
10790** case that more than one of these conditions is true.
10791*/
10792struct WherePlan {
10793  u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
10794  u32 nEq;                       /* Number of == constraints */
10795  double nRow;                   /* Estimated number of rows (for EQP) */
10796  union {
10797    Index *pIdx;                   /* Index when WHERE_INDEXED is true */
10798    struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
10799    sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
10800  } u;
10801};
10802
10803/*
10804** For each nested loop in a WHERE clause implementation, the WhereInfo
10805** structure contains a single instance of this structure.  This structure
10806** is intended to be private the the where.c module and should not be
10807** access or modified by other modules.
10808**
10809** The pIdxInfo field is used to help pick the best index on a
10810** virtual table.  The pIdxInfo pointer contains indexing
10811** information for the i-th table in the FROM clause before reordering.
10812** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
10813** All other information in the i-th WhereLevel object for the i-th table
10814** after FROM clause ordering.
10815*/
10816struct WhereLevel {
10817  WherePlan plan;       /* query plan for this element of the FROM clause */
10818  int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
10819  int iTabCur;          /* The VDBE cursor used to access the table */
10820  int iIdxCur;          /* The VDBE cursor used to access pIdx */
10821  int addrBrk;          /* Jump here to break out of the loop */
10822  int addrNxt;          /* Jump here to start the next IN combination */
10823  int addrCont;         /* Jump here to continue with the next loop cycle */
10824  int addrFirst;        /* First instruction of interior of the loop */
10825  u8 iFrom;             /* Which entry in the FROM clause */
10826  u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
10827  int p1, p2;           /* Operands of the opcode used to ends the loop */
10828  union {               /* Information that depends on plan.wsFlags */
10829    struct {
10830      int nIn;              /* Number of entries in aInLoop[] */
10831      struct InLoop {
10832        int iCur;              /* The VDBE cursor used by this IN operator */
10833        int addrInTop;         /* Top of the IN loop */
10834      } *aInLoop;           /* Information about each nested IN operator */
10835    } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
10836  } u;
10837
10838  /* The following field is really not part of the current level.  But
10839  ** we need a place to cache virtual table index information for each
10840  ** virtual table in the FROM clause and the WhereLevel structure is
10841  ** a convenient place since there is one WhereLevel for each FROM clause
10842  ** element.
10843  */
10844  sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
10845};
10846
10847/*
10848** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
10849** and the WhereInfo.wctrlFlags member.
10850*/
10851#define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
10852#define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
10853#define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
10854#define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
10855#define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
10856#define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
10857#define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
10858#define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
10859#define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
10860
10861/*
10862** The WHERE clause processing routine has two halves.  The
10863** first part does the start of the WHERE loop and the second
10864** half does the tail of the WHERE loop.  An instance of
10865** this structure is returned by the first half and passed
10866** into the second half to give some continuity.
10867*/
10868struct WhereInfo {
10869  Parse *pParse;       /* Parsing and code generating context */
10870  u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
10871  u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
10872  u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
10873  u8 eDistinct;
10874  SrcList *pTabList;             /* List of tables in the join */
10875  int iTop;                      /* The very beginning of the WHERE loop */
10876  int iContinue;                 /* Jump here to continue with next record */
10877  int iBreak;                    /* Jump here to break out of the loop */
10878  int nLevel;                    /* Number of nested loop */
10879  struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
10880  double savedNQueryLoop;        /* pParse->nQueryLoop outside the WHERE loop */
10881  double nRowOut;                /* Estimated number of output rows */
10882  WhereLevel a[1];               /* Information about each nest loop in WHERE */
10883};
10884
10885#define WHERE_DISTINCT_UNIQUE 1
10886#define WHERE_DISTINCT_ORDERED 2
10887
10888/*
10889** A NameContext defines a context in which to resolve table and column
10890** names.  The context consists of a list of tables (the pSrcList) field and
10891** a list of named expression (pEList).  The named expression list may
10892** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
10893** to the table being operated on by INSERT, UPDATE, or DELETE.  The
10894** pEList corresponds to the result set of a SELECT and is NULL for
10895** other statements.
10896**
10897** NameContexts can be nested.  When resolving names, the inner-most
10898** context is searched first.  If no match is found, the next outer
10899** context is checked.  If there is still no match, the next context
10900** is checked.  This process continues until either a match is found
10901** or all contexts are check.  When a match is found, the nRef member of
10902** the context containing the match is incremented.
10903**
10904** Each subquery gets a new NameContext.  The pNext field points to the
10905** NameContext in the parent query.  Thus the process of scanning the
10906** NameContext list corresponds to searching through successively outer
10907** subqueries looking for a match.
10908*/
10909struct NameContext {
10910  Parse *pParse;       /* The parser */
10911  SrcList *pSrcList;   /* One or more tables used to resolve names */
10912  ExprList *pEList;    /* Optional list of named expressions */
10913  int nRef;            /* Number of names resolved by this context */
10914  int nErr;            /* Number of errors encountered while resolving names */
10915  u8 allowAgg;         /* Aggregate functions allowed here */
10916  u8 hasAgg;           /* True if aggregates are seen */
10917  u8 isCheck;          /* True if resolving names in a CHECK constraint */
10918  int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
10919  AggInfo *pAggInfo;   /* Information about aggregates at this level */
10920  NameContext *pNext;  /* Next outer name context.  NULL for outermost */
10921};
10922
10923/*
10924** An instance of the following structure contains all information
10925** needed to generate code for a single SELECT statement.
10926**
10927** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
10928** If there is a LIMIT clause, the parser sets nLimit to the value of the
10929** limit and nOffset to the value of the offset (or 0 if there is not
10930** offset).  But later on, nLimit and nOffset become the memory locations
10931** in the VDBE that record the limit and offset counters.
10932**
10933** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
10934** These addresses must be stored so that we can go back and fill in
10935** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
10936** the number of columns in P2 can be computed at the same time
10937** as the OP_OpenEphm instruction is coded because not
10938** enough information about the compound query is known at that point.
10939** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
10940** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
10941** sequences for the ORDER BY clause.
10942*/
10943struct Select {
10944  ExprList *pEList;      /* The fields of the result */
10945  u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
10946  char affinity;         /* MakeRecord with this affinity for SRT_Set */
10947  u16 selFlags;          /* Various SF_* values */
10948  int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
10949  int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
10950  double nSelectRow;     /* Estimated number of result rows */
10951  SrcList *pSrc;         /* The FROM clause */
10952  Expr *pWhere;          /* The WHERE clause */
10953  ExprList *pGroupBy;    /* The GROUP BY clause */
10954  Expr *pHaving;         /* The HAVING clause */
10955  ExprList *pOrderBy;    /* The ORDER BY clause */
10956  Select *pPrior;        /* Prior select in a compound select statement */
10957  Select *pNext;         /* Next select to the left in a compound */
10958  Select *pRightmost;    /* Right-most select in a compound select statement */
10959  Expr *pLimit;          /* LIMIT expression. NULL means not used. */
10960  Expr *pOffset;         /* OFFSET expression. NULL means not used. */
10961};
10962
10963/*
10964** Allowed values for Select.selFlags.  The "SF" prefix stands for
10965** "Select Flag".
10966*/
10967#define SF_Distinct        0x01  /* Output should be DISTINCT */
10968#define SF_Resolved        0x02  /* Identifiers have been resolved */
10969#define SF_Aggregate       0x04  /* Contains aggregate functions */
10970#define SF_UsesEphemeral   0x08  /* Uses the OpenEphemeral opcode */
10971#define SF_Expanded        0x10  /* sqlite3SelectExpand() called on this */
10972#define SF_HasTypeInfo     0x20  /* FROM subqueries have Table metadata */
10973#define SF_UseSorter       0x40  /* Sort using a sorter */
10974#define SF_Values          0x80  /* Synthesized from VALUES clause */
10975
10976
10977/*
10978** The results of a select can be distributed in several ways.  The
10979** "SRT" prefix means "SELECT Result Type".
10980*/
10981#define SRT_Union        1  /* Store result as keys in an index */
10982#define SRT_Except       2  /* Remove result from a UNION index */
10983#define SRT_Exists       3  /* Store 1 if the result is not empty */
10984#define SRT_Discard      4  /* Do not save the results anywhere */
10985
10986/* The ORDER BY clause is ignored for all of the above */
10987#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
10988
10989#define SRT_Output       5  /* Output each row of result */
10990#define SRT_Mem          6  /* Store result in a memory cell */
10991#define SRT_Set          7  /* Store results as keys in an index */
10992#define SRT_Table        8  /* Store result as data with an automatic rowid */
10993#define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
10994#define SRT_Coroutine   10  /* Generate a single row of result */
10995
10996/*
10997** A structure used to customize the behavior of sqlite3Select(). See
10998** comments above sqlite3Select() for details.
10999*/
11000typedef struct SelectDest SelectDest;
11001struct SelectDest {
11002  u8 eDest;         /* How to dispose of the results */
11003  u8 affinity;      /* Affinity used when eDest==SRT_Set */
11004  int iParm;        /* A parameter used by the eDest disposal method */
11005  int iMem;         /* Base register where results are written */
11006  int nMem;         /* Number of registers allocated */
11007};
11008
11009/*
11010** During code generation of statements that do inserts into AUTOINCREMENT
11011** tables, the following information is attached to the Table.u.autoInc.p
11012** pointer of each autoincrement table to record some side information that
11013** the code generator needs.  We have to keep per-table autoincrement
11014** information in case inserts are down within triggers.  Triggers do not
11015** normally coordinate their activities, but we do need to coordinate the
11016** loading and saving of autoincrement information.
11017*/
11018struct AutoincInfo {
11019  AutoincInfo *pNext;   /* Next info block in a list of them all */
11020  Table *pTab;          /* Table this info block refers to */
11021  int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11022  int regCtr;           /* Memory register holding the rowid counter */
11023};
11024
11025/*
11026** Size of the column cache
11027*/
11028#ifndef SQLITE_N_COLCACHE
11029# define SQLITE_N_COLCACHE 10
11030#endif
11031
11032/*
11033** At least one instance of the following structure is created for each
11034** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11035** statement. All such objects are stored in the linked list headed at
11036** Parse.pTriggerPrg and deleted once statement compilation has been
11037** completed.
11038**
11039** A Vdbe sub-program that implements the body and WHEN clause of trigger
11040** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11041** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11042** The Parse.pTriggerPrg list never contains two entries with the same
11043** values for both pTrigger and orconf.
11044**
11045** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11046** accessed (or set to 0 for triggers fired as a result of INSERT
11047** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11048** a mask of new.* columns used by the program.
11049*/
11050struct TriggerPrg {
11051  Trigger *pTrigger;      /* Trigger this program was coded from */
11052  TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11053  SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11054  int orconf;             /* Default ON CONFLICT policy */
11055  u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11056};
11057
11058/*
11059** The yDbMask datatype for the bitmask of all attached databases.
11060*/
11061#if SQLITE_MAX_ATTACHED>30
11062  typedef sqlite3_uint64 yDbMask;
11063#else
11064  typedef unsigned int yDbMask;
11065#endif
11066
11067/*
11068** An SQL parser context.  A copy of this structure is passed through
11069** the parser and down into all the parser action routine in order to
11070** carry around information that is global to the entire parse.
11071**
11072** The structure is divided into two parts.  When the parser and code
11073** generate call themselves recursively, the first part of the structure
11074** is constant but the second part is reset at the beginning and end of
11075** each recursion.
11076**
11077** The nTableLock and aTableLock variables are only used if the shared-cache
11078** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11079** used to store the set of table-locks required by the statement being
11080** compiled. Function sqlite3TableLock() is used to add entries to the
11081** list.
11082*/
11083struct Parse {
11084  sqlite3 *db;         /* The main database structure */
11085  char *zErrMsg;       /* An error message */
11086  Vdbe *pVdbe;         /* An engine for executing database bytecode */
11087  int rc;              /* Return code from execution */
11088  u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11089  u8 checkSchema;      /* Causes schema cookie check after an error */
11090  u8 nested;           /* Number of nested calls to the parser/code generator */
11091  u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11092  u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11093  u8 nColCache;        /* Number of entries in aColCache[] */
11094  u8 iColCache;        /* Next entry in aColCache[] to replace */
11095  u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11096  u8 mayAbort;         /* True if statement may throw an ABORT exception */
11097  int aTempReg[8];     /* Holding area for temporary registers */
11098  int nRangeReg;       /* Size of the temporary register block */
11099  int iRangeReg;       /* First register in temporary register block */
11100  int nErr;            /* Number of errors seen */
11101  int nTab;            /* Number of previously allocated VDBE cursors */
11102  int nMem;            /* Number of memory cells used so far */
11103  int nSet;            /* Number of sets used so far */
11104  int nOnce;           /* Number of OP_Once instructions so far */
11105  int ckBase;          /* Base register of data during check constraints */
11106  int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11107  int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11108  struct yColCache {
11109    int iTable;           /* Table cursor number */
11110    int iColumn;          /* Table column number */
11111    u8 tempReg;           /* iReg is a temp register that needs to be freed */
11112    int iLevel;           /* Nesting level */
11113    int iReg;             /* Reg with value of this column. 0 means none. */
11114    int lru;              /* Least recently used entry has the smallest value */
11115  } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11116  yDbMask writeMask;   /* Start a write transaction on these databases */
11117  yDbMask cookieMask;  /* Bitmask of schema verified databases */
11118  int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11119  int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11120  int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11121  int regRoot;         /* Register holding root page number for new objects */
11122  int nMaxArg;         /* Max args passed to user function by sub-program */
11123#ifndef SQLITE_OMIT_SHARED_CACHE
11124  int nTableLock;        /* Number of locks in aTableLock */
11125  TableLock *aTableLock; /* Required table locks for shared-cache mode */
11126#endif
11127  AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11128
11129  /* Information used while coding trigger programs. */
11130  Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11131  Table *pTriggerTab;  /* Table triggers are being coded for */
11132  double nQueryLoop;   /* Estimated number of iterations of a query */
11133  u32 oldmask;         /* Mask of old.* columns referenced */
11134  u32 newmask;         /* Mask of new.* columns referenced */
11135  u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11136  u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11137  u8 disableTriggers;  /* True to disable triggers */
11138
11139  /* Above is constant between recursions.  Below is reset before and after
11140  ** each recursion */
11141
11142  int nVar;                 /* Number of '?' variables seen in the SQL so far */
11143  int nzVar;                /* Number of available slots in azVar[] */
11144  u8 explain;               /* True if the EXPLAIN flag is found on the query */
11145#ifndef SQLITE_OMIT_VIRTUALTABLE
11146  u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11147  int nVtabLock;            /* Number of virtual tables to lock */
11148#endif
11149  int nAlias;               /* Number of aliased result set columns */
11150  int nHeight;              /* Expression tree height of current sub-select */
11151#ifndef SQLITE_OMIT_EXPLAIN
11152  int iSelectId;            /* ID of current select for EXPLAIN output */
11153  int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11154#endif
11155  char **azVar;             /* Pointers to names of parameters */
11156  Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11157  int *aAlias;              /* Register used to hold aliased result */
11158  const char *zTail;        /* All SQL text past the last semicolon parsed */
11159  Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11160  Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11161  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11162  Token sNameToken;         /* Token with unqualified schema object name */
11163  Token sLastToken;         /* The last token parsed */
11164#ifndef SQLITE_OMIT_VIRTUALTABLE
11165  Token sArg;               /* Complete text of a module argument */
11166  Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11167#endif
11168  Table *pZombieTab;        /* List of Table objects to delete after code gen */
11169  TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11170};
11171
11172/*
11173** Return true if currently inside an sqlite3_declare_vtab() call.
11174*/
11175#ifdef SQLITE_OMIT_VIRTUALTABLE
11176  #define IN_DECLARE_VTAB 0
11177#else
11178  #define IN_DECLARE_VTAB (pParse->declareVtab)
11179#endif
11180
11181/*
11182** An instance of the following structure can be declared on a stack and used
11183** to save the Parse.zAuthContext value so that it can be restored later.
11184*/
11185struct AuthContext {
11186  const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11187  Parse *pParse;              /* The Parse structure */
11188};
11189
11190/*
11191** Bitfield flags for P5 value in OP_Insert and OP_Delete
11192*/
11193#define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11194#define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11195#define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11196#define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11197#define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11198#define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11199
11200/*
11201 * Each trigger present in the database schema is stored as an instance of
11202 * struct Trigger.
11203 *
11204 * Pointers to instances of struct Trigger are stored in two ways.
11205 * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
11206 *    database). This allows Trigger structures to be retrieved by name.
11207 * 2. All triggers associated with a single table form a linked list, using the
11208 *    pNext member of struct Trigger. A pointer to the first element of the
11209 *    linked list is stored as the "pTrigger" member of the associated
11210 *    struct Table.
11211 *
11212 * The "step_list" member points to the first element of a linked list
11213 * containing the SQL statements specified as the trigger program.
11214 */
11215struct Trigger {
11216  char *zName;            /* The name of the trigger                        */
11217  char *table;            /* The table or view to which the trigger applies */
11218  u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11219  u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11220  Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11221  IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11222                             the <column-list> is stored here */
11223  Schema *pSchema;        /* Schema containing the trigger */
11224  Schema *pTabSchema;     /* Schema containing the table */
11225  TriggerStep *step_list; /* Link list of trigger program steps             */
11226  Trigger *pNext;         /* Next trigger associated with the table */
11227};
11228
11229/*
11230** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11231** determine which.
11232**
11233** If there are multiple triggers, you might of some BEFORE and some AFTER.
11234** In that cases, the constants below can be ORed together.
11235*/
11236#define TRIGGER_BEFORE  1
11237#define TRIGGER_AFTER   2
11238
11239/*
11240 * An instance of struct TriggerStep is used to store a single SQL statement
11241 * that is a part of a trigger-program.
11242 *
11243 * Instances of struct TriggerStep are stored in a singly linked list (linked
11244 * using the "pNext" member) referenced by the "step_list" member of the
11245 * associated struct Trigger instance. The first element of the linked list is
11246 * the first step of the trigger-program.
11247 *
11248 * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11249 * "SELECT" statement. The meanings of the other members is determined by the
11250 * value of "op" as follows:
11251 *
11252 * (op == TK_INSERT)
11253 * orconf    -> stores the ON CONFLICT algorithm
11254 * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11255 *              this stores a pointer to the SELECT statement. Otherwise NULL.
11256 * target    -> A token holding the quoted name of the table to insert into.
11257 * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11258 *              this stores values to be inserted. Otherwise NULL.
11259 * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ...
11260 *              statement, then this stores the column-names to be
11261 *              inserted into.
11262 *
11263 * (op == TK_DELETE)
11264 * target    -> A token holding the quoted name of the table to delete from.
11265 * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11266 *              Otherwise NULL.
11267 *
11268 * (op == TK_UPDATE)
11269 * target    -> A token holding the quoted name of the table to update rows of.
11270 * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11271 *              Otherwise NULL.
11272 * pExprList -> A list of the columns to update and the expressions to update
11273 *              them to. See sqlite3Update() documentation of "pChanges"
11274 *              argument.
11275 *
11276 */
11277struct TriggerStep {
11278  u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11279  u8 orconf;           /* OE_Rollback etc. */
11280  Trigger *pTrig;      /* The trigger that this step is a part of */
11281  Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11282  Token target;        /* Target table for DELETE, UPDATE, INSERT */
11283  Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11284  ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11285  IdList *pIdList;     /* Column names for INSERT */
11286  TriggerStep *pNext;  /* Next in the link-list */
11287  TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11288};
11289
11290/*
11291** The following structure contains information used by the sqliteFix...
11292** routines as they walk the parse tree to make database references
11293** explicit.
11294*/
11295typedef struct DbFixer DbFixer;
11296struct DbFixer {
11297  Parse *pParse;      /* The parsing context.  Error messages written here */
11298  const char *zDb;    /* Make sure all objects are contained in this database */
11299  const char *zType;  /* Type of the container - used for error messages */
11300  const Token *pName; /* Name of the container - used for error messages */
11301};
11302
11303/*
11304** An objected used to accumulate the text of a string where we
11305** do not necessarily know how big the string will be in the end.
11306*/
11307struct StrAccum {
11308  sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11309  char *zBase;         /* A base allocation.  Not from malloc. */
11310  char *zText;         /* The string collected so far */
11311  int  nChar;          /* Length of the string so far */
11312  int  nAlloc;         /* Amount of space allocated in zText */
11313  int  mxAlloc;        /* Maximum allowed string length */
11314  u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11315  u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11316  u8   tooBig;         /* Becomes true if string size exceeds limits */
11317};
11318
11319/*
11320** A pointer to this structure is used to communicate information
11321** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11322*/
11323typedef struct {
11324  sqlite3 *db;        /* The database being initialized */
11325  char **pzErrMsg;    /* Error message stored here */
11326  int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11327  int rc;             /* Result code stored here */
11328} InitData;
11329
11330/*
11331** Structure containing global configuration data for the SQLite library.
11332**
11333** This structure also contains some state information.
11334*/
11335struct Sqlite3Config {
11336  int bMemstat;                     /* True to enable memory status */
11337  int bCoreMutex;                   /* True to enable core mutexing */
11338  int bFullMutex;                   /* True to enable full mutexing */
11339  int bOpenUri;                     /* True to interpret filenames as URIs */
11340  int mxStrlen;                     /* Maximum string length */
11341  int szLookaside;                  /* Default lookaside buffer size */
11342  int nLookaside;                   /* Default lookaside buffer count */
11343  sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11344  sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11345  sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11346  void *pHeap;                      /* Heap storage space */
11347  int nHeap;                        /* Size of pHeap[] */
11348  int mnReq, mxReq;                 /* Min and max heap requests sizes */
11349  void *pScratch;                   /* Scratch memory */
11350  int szScratch;                    /* Size of each scratch buffer */
11351  int nScratch;                     /* Number of scratch buffers */
11352  void *pPage;                      /* Page cache memory */
11353  int szPage;                       /* Size of each page in pPage[] */
11354  int nPage;                        /* Number of pages in pPage[] */
11355  int mxParserStack;                /* maximum depth of the parser stack */
11356  int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11357  /* The above might be initialized to non-zero.  The following need to always
11358  ** initially be zero, however. */
11359  int isInit;                       /* True after initialization has finished */
11360  int inProgress;                   /* True while initialization in progress */
11361  int isMutexInit;                  /* True after mutexes are initialized */
11362  int isMallocInit;                 /* True after malloc is initialized */
11363  int isPCacheInit;                 /* True after malloc is initialized */
11364  sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11365  int nRefInitMutex;                /* Number of users of pInitMutex */
11366  void (*xLog)(void*,int,const char*); /* Function for logging */
11367  void *pLogArg;                       /* First argument to xLog() */
11368  int bLocaltimeFault;              /* True to fail localtime() calls */
11369};
11370
11371/*
11372** Context pointer passed down through the tree-walk.
11373*/
11374struct Walker {
11375  int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11376  int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11377  Parse *pParse;                            /* Parser context.  */
11378  union {                                   /* Extra data for callback */
11379    NameContext *pNC;                          /* Naming context */
11380    int i;                                     /* Integer value */
11381  } u;
11382};
11383
11384/* Forward declarations */
11385SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11386SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11387SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11388SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11389SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11390
11391/*
11392** Return code from the parse-tree walking primitives and their
11393** callbacks.
11394*/
11395#define WRC_Continue    0   /* Continue down into children */
11396#define WRC_Prune       1   /* Omit children but continue walking siblings */
11397#define WRC_Abort       2   /* Abandon the tree walk */
11398
11399/*
11400** Assuming zIn points to the first byte of a UTF-8 character,
11401** advance zIn to point to the first byte of the next UTF-8 character.
11402*/
11403#define SQLITE_SKIP_UTF8(zIn) {                        \
11404  if( (*(zIn++))>=0xc0 ){                              \
11405    while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11406  }                                                    \
11407}
11408
11409/*
11410** The SQLITE_*_BKPT macros are substitutes for the error codes with
11411** the same name but without the _BKPT suffix.  These macros invoke
11412** routines that report the line-number on which the error originated
11413** using sqlite3_log().  The routines also provide a convenient place
11414** to set a debugger breakpoint.
11415*/
11416SQLITE_PRIVATE int sqlite3CorruptError(int);
11417SQLITE_PRIVATE int sqlite3MisuseError(int);
11418SQLITE_PRIVATE int sqlite3CantopenError(int);
11419#define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11420#define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11421#define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11422
11423
11424/*
11425** FTS4 is really an extension for FTS3.  It is enabled using the
11426** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11427** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11428*/
11429#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11430# define SQLITE_ENABLE_FTS3
11431#endif
11432
11433/*
11434** The ctype.h header is needed for non-ASCII systems.  It is also
11435** needed by FTS3 when FTS3 is included in the amalgamation.
11436*/
11437#if !defined(SQLITE_ASCII) || \
11438    (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11439# include <ctype.h>
11440#endif
11441
11442/*
11443** The following macros mimic the standard library functions toupper(),
11444** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11445** sqlite versions only work for ASCII characters, regardless of locale.
11446*/
11447#ifdef SQLITE_ASCII
11448# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11449# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11450# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11451# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11452# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11453# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11454# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11455#else
11456# define sqlite3Toupper(x)   toupper((unsigned char)(x))
11457# define sqlite3Isspace(x)   isspace((unsigned char)(x))
11458# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11459# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11460# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11461# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11462# define sqlite3Tolower(x)   tolower((unsigned char)(x))
11463#endif
11464
11465/*
11466** Internal function prototypes
11467*/
11468#define sqlite3StrICmp sqlite3_stricmp
11469SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11470#define sqlite3StrNICmp sqlite3_strnicmp
11471
11472SQLITE_PRIVATE int sqlite3MallocInit(void);
11473SQLITE_PRIVATE void sqlite3MallocEnd(void);
11474SQLITE_PRIVATE void *sqlite3Malloc(int);
11475SQLITE_PRIVATE void *sqlite3MallocZero(int);
11476SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11477SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11478SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11479SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11480SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11481SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11482SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11483SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11484SQLITE_PRIVATE int sqlite3MallocSize(void*);
11485SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11486SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11487SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11488SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11489SQLITE_PRIVATE void sqlite3PageFree(void*);
11490SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11491SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11492SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11493
11494/*
11495** On systems with ample stack space and that support alloca(), make
11496** use of alloca() to obtain space for large automatic objects.  By default,
11497** obtain space from malloc().
11498**
11499** The alloca() routine never returns NULL.  This will cause code paths
11500** that deal with sqlite3StackAlloc() failures to be unreachable.
11501*/
11502#ifdef SQLITE_USE_ALLOCA
11503# define sqlite3StackAllocRaw(D,N)   alloca(N)
11504# define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11505# define sqlite3StackFree(D,P)
11506#else
11507# define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11508# define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11509# define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11510#endif
11511
11512#ifdef SQLITE_ENABLE_MEMSYS3
11513SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11514#endif
11515#ifdef SQLITE_ENABLE_MEMSYS5
11516SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11517#endif
11518
11519
11520#ifndef SQLITE_MUTEX_OMIT
11521SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11522SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11523SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11524SQLITE_PRIVATE   int sqlite3MutexInit(void);
11525SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11526#endif
11527
11528SQLITE_PRIVATE int sqlite3StatusValue(int);
11529SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11530SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11531
11532#ifndef SQLITE_OMIT_FLOATING_POINT
11533SQLITE_PRIVATE   int sqlite3IsNaN(double);
11534#else
11535# define sqlite3IsNaN(X)  0
11536#endif
11537
11538SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11539#ifndef SQLITE_OMIT_TRACE
11540SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11541#endif
11542SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11543SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11544SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11545#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11546SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11547#endif
11548#if defined(SQLITE_TEST)
11549SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11550#endif
11551
11552/* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11553#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11554SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
11555SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11556SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
11557SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
11558SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
11559SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
11560SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
11561SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
11562SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
11563SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
11564#else
11565# define sqlite3ExplainBegin(X)
11566# define sqlite3ExplainSelect(A,B)
11567# define sqlite3ExplainExpr(A,B)
11568# define sqlite3ExplainExprList(A,B)
11569# define sqlite3ExplainFinish(X)
11570# define sqlite3VdbeExplanation(X) 0
11571#endif
11572
11573
11574SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11575SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11576SQLITE_PRIVATE int sqlite3Dequote(char*);
11577SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11578SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11579SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11580SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11581SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11582SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11583SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11584SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11585SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11586SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11587SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11588SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11589SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11590SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11591SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11592SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11593SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11594SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11595SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11596SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11597SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11598SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11599SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11600SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
11601SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11602SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11603SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11604SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11605SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11606SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11607SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11608SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11609SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11610SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11611SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11612SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11613SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11614SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11615                    sqlite3_vfs**,char**,char **);
11616SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11617SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11618
11619SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11620SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
11621SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
11622SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
11623SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
11624SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
11625SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
11626
11627SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
11628SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
11629SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
11630SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
11631SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
11632
11633SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
11634
11635#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
11636SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
11637#else
11638# define sqlite3ViewGetColumnNames(A,B) 0
11639#endif
11640
11641SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
11642SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
11643SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
11644#ifndef SQLITE_OMIT_AUTOINCREMENT
11645SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
11646SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
11647#else
11648# define sqlite3AutoincrementBegin(X)
11649# define sqlite3AutoincrementEnd(X)
11650#endif
11651SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
11652SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
11653SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
11654SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
11655SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
11656SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
11657SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
11658                                      Token*, Select*, Expr*, IdList*);
11659SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
11660SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
11661SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
11662SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
11663SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
11664SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
11665SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
11666                        Token*, int, int);
11667SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
11668SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
11669SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
11670                         Expr*,ExprList*,int,Expr*,Expr*);
11671SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
11672SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
11673SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
11674SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
11675#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
11676SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
11677#endif
11678SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
11679SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
11680SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**,ExprList*,u16);
11681SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
11682SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
11683SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
11684SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
11685SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
11686SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
11687SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
11688SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
11689SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
11690SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
11691SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
11692SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
11693SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
11694SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
11695SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
11696SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
11697SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
11698SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
11699SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
11700SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
11701SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
11702SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
11703SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
11704SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
11705SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
11706SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
11707SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
11708SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
11709SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
11710SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
11711SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
11712SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
11713SQLITE_PRIVATE void sqlite3PrngSaveState(void);
11714SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
11715SQLITE_PRIVATE void sqlite3PrngResetState(void);
11716SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
11717SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
11718SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
11719SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
11720SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
11721SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
11722SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
11723SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
11724SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
11725SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
11726SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
11727SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
11728SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
11729SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
11730SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
11731SQLITE_PRIVATE int sqlite3IsRowid(const char*);
11732SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
11733SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
11734SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
11735SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
11736                                     int*,int,int,int,int,int*);
11737SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
11738SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
11739SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
11740SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
11741SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
11742SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
11743SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
11744SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
11745SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
11746SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
11747SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
11748SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
11749SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
11750SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
11751SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
11752SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
11753SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
11754SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
11755SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
11756
11757#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
11758SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
11759#endif
11760
11761#ifndef SQLITE_OMIT_TRIGGER
11762SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
11763                           Expr*,int, int);
11764SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
11765SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
11766SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
11767SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
11768SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
11769SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
11770                            int, int, int);
11771SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
11772  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
11773SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
11774SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
11775SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
11776                                        ExprList*,Select*,u8);
11777SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
11778SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
11779SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
11780SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
11781SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
11782# define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
11783#else
11784# define sqlite3TriggersExist(B,C,D,E,F) 0
11785# define sqlite3DeleteTrigger(A,B)
11786# define sqlite3DropTriggerPtr(A,B)
11787# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
11788# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
11789# define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
11790# define sqlite3TriggerList(X, Y) 0
11791# define sqlite3ParseToplevel(p) p
11792# define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
11793#endif
11794
11795SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
11796SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
11797SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
11798#ifndef SQLITE_OMIT_AUTHORIZATION
11799SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
11800SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
11801SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
11802SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
11803SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
11804#else
11805# define sqlite3AuthRead(a,b,c,d)
11806# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
11807# define sqlite3AuthContextPush(a,b,c)
11808# define sqlite3AuthContextPop(a)  ((void)(a))
11809#endif
11810SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
11811SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
11812SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
11813SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
11814SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
11815SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
11816SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
11817SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
11818SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
11819SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
11820SQLITE_PRIVATE int sqlite3Atoi(const char*);
11821SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
11822SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
11823SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8*, const u8**);
11824
11825/*
11826** Routines to read and write variable-length integers.  These used to
11827** be defined locally, but now we use the varint routines in the util.c
11828** file.  Code should use the MACRO forms below, as the Varint32 versions
11829** are coded to assume the single byte case is already handled (which
11830** the MACRO form does).
11831*/
11832SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
11833SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
11834SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
11835SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
11836SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
11837
11838/*
11839** The header of a record consists of a sequence variable-length integers.
11840** These integers are almost always small and are encoded as a single byte.
11841** The following macros take advantage this fact to provide a fast encode
11842** and decode of the integers in a record header.  It is faster for the common
11843** case where the integer is a single byte.  It is a little slower when the
11844** integer is two or more bytes.  But overall it is faster.
11845**
11846** The following expressions are equivalent:
11847**
11848**     x = sqlite3GetVarint32( A, &B );
11849**     x = sqlite3PutVarint32( A, B );
11850**
11851**     x = getVarint32( A, B );
11852**     x = putVarint32( A, B );
11853**
11854*/
11855#define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
11856#define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
11857#define getVarint    sqlite3GetVarint
11858#define putVarint    sqlite3PutVarint
11859
11860
11861SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
11862SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
11863SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
11864SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
11865SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
11866SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
11867SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
11868SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
11869SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
11870SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
11871SQLITE_PRIVATE const char *sqlite3ErrStr(int);
11872SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
11873SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
11874SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
11875SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
11876SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr*, CollSeq*);
11877SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr*, Token*);
11878SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
11879SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
11880SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
11881SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
11882SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
11883SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
11884SQLITE_PRIVATE int sqlite3AbsInt32(int);
11885#ifdef SQLITE_ENABLE_8_3_NAMES
11886SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
11887#else
11888# define sqlite3FileSuffix3(X,Y)
11889#endif
11890SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
11891
11892SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
11893SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
11894SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
11895                        void(*)(void*));
11896SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
11897SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
11898SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
11899#ifdef SQLITE_ENABLE_STAT3
11900SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
11901#endif
11902SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
11903SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
11904#ifndef SQLITE_AMALGAMATION
11905SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
11906SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
11907SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
11908SQLITE_PRIVATE const Token sqlite3IntTokens[];
11909SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
11910SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
11911#ifndef SQLITE_OMIT_WSD
11912SQLITE_PRIVATE int sqlite3PendingByte;
11913#endif
11914#endif
11915SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
11916SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
11917SQLITE_PRIVATE void sqlite3AlterFunctions(void);
11918SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
11919SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
11920SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
11921SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
11922SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
11923SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
11924SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
11925SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
11926SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
11927SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
11928SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
11929SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
11930SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
11931SQLITE_PRIVATE char sqlite3AffinityType(const char*);
11932SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
11933SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
11934SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
11935SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
11936SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
11937SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
11938SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
11939SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
11940SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
11941SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
11942SQLITE_PRIVATE void sqlite3SchemaClear(void *);
11943SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
11944SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
11945SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
11946SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
11947  void (*)(sqlite3_context*,int,sqlite3_value **),
11948  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
11949  FuncDestructor *pDestructor
11950);
11951SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
11952SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
11953
11954SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
11955SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
11956SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
11957SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
11958SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
11959SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
11960SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
11961
11962SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
11963SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
11964
11965/*
11966** The interface to the LEMON-generated parser
11967*/
11968SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
11969SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
11970SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
11971#ifdef YYTRACKMAXSTACKDEPTH
11972SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
11973#endif
11974
11975SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
11976#ifndef SQLITE_OMIT_LOAD_EXTENSION
11977SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
11978#else
11979# define sqlite3CloseExtensions(X)
11980#endif
11981
11982#ifndef SQLITE_OMIT_SHARED_CACHE
11983SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
11984#else
11985  #define sqlite3TableLock(v,w,x,y,z)
11986#endif
11987
11988#ifdef SQLITE_TEST
11989SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
11990#endif
11991
11992#ifdef SQLITE_OMIT_VIRTUALTABLE
11993#  define sqlite3VtabClear(Y)
11994#  define sqlite3VtabSync(X,Y) SQLITE_OK
11995#  define sqlite3VtabRollback(X)
11996#  define sqlite3VtabCommit(X)
11997#  define sqlite3VtabInSync(db) 0
11998#  define sqlite3VtabLock(X)
11999#  define sqlite3VtabUnlock(X)
12000#  define sqlite3VtabUnlockList(X)
12001#  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12002#  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12003#else
12004SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12005SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
12006SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12007SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12008SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12009SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12010SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12011SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12012SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12013#  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12014#endif
12015SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12016SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12017SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12018SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12019SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12020SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12021SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12022SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12023SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12024SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12025SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12026SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12027SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12028SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12029SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12030SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12031SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12032SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12033SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12034SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12035
12036/* Declarations for functions in fkey.c. All of these are replaced by
12037** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12038** key functionality is available. If OMIT_TRIGGER is defined but
12039** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12040** this case foreign keys are parsed, but no other functionality is
12041** provided (enforcement of FK constraints requires the triggers sub-system).
12042*/
12043#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12044SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
12045SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12046SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12047SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12048SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12049SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12050#else
12051  #define sqlite3FkActions(a,b,c,d)
12052  #define sqlite3FkCheck(a,b,c,d)
12053  #define sqlite3FkDropTable(a,b,c)
12054  #define sqlite3FkOldmask(a,b)      0
12055  #define sqlite3FkRequired(a,b,c,d) 0
12056#endif
12057#ifndef SQLITE_OMIT_FOREIGN_KEY
12058SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12059#else
12060  #define sqlite3FkDelete(a,b)
12061#endif
12062
12063
12064/*
12065** Available fault injectors.  Should be numbered beginning with 0.
12066*/
12067#define SQLITE_FAULTINJECTOR_MALLOC     0
12068#define SQLITE_FAULTINJECTOR_COUNT      1
12069
12070/*
12071** The interface to the code in fault.c used for identifying "benign"
12072** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12073** is not defined.
12074*/
12075#ifndef SQLITE_OMIT_BUILTIN_TEST
12076SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12077SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12078#else
12079  #define sqlite3BeginBenignMalloc()
12080  #define sqlite3EndBenignMalloc()
12081#endif
12082
12083#define IN_INDEX_ROWID           1
12084#define IN_INDEX_EPH             2
12085#define IN_INDEX_INDEX           3
12086SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12087
12088#ifdef SQLITE_ENABLE_ATOMIC_WRITE
12089SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12090SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12091SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12092#else
12093  #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12094#endif
12095
12096SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12097SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12098SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12099
12100#if SQLITE_MAX_EXPR_DEPTH>0
12101SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12102SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12103SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12104#else
12105  #define sqlite3ExprSetHeight(x,y)
12106  #define sqlite3SelectExprHeight(x) 0
12107  #define sqlite3ExprCheckHeight(x,y)
12108#endif
12109
12110SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12111SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12112
12113#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12114SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12115SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12116SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12117#else
12118  #define sqlite3ConnectionBlocked(x,y)
12119  #define sqlite3ConnectionUnlocked(x)
12120  #define sqlite3ConnectionClosed(x)
12121#endif
12122
12123#ifdef SQLITE_DEBUG
12124SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12125#endif
12126
12127/*
12128** If the SQLITE_ENABLE IOTRACE exists then the global variable
12129** sqlite3IoTrace is a pointer to a printf-like routine used to
12130** print I/O tracing messages.
12131*/
12132#ifdef SQLITE_ENABLE_IOTRACE
12133# define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12134SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12135SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12136#else
12137# define IOTRACE(A)
12138# define sqlite3VdbeIOTraceSql(X)
12139#endif
12140
12141/*
12142** These routines are available for the mem2.c debugging memory allocator
12143** only.  They are used to verify that different "types" of memory
12144** allocations are properly tracked by the system.
12145**
12146** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12147** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12148** a single bit set.
12149**
12150** sqlite3MemdebugHasType() returns true if any of the bits in its second
12151** argument match the type set by the previous sqlite3MemdebugSetType().
12152** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12153**
12154** sqlite3MemdebugNoType() returns true if none of the bits in its second
12155** argument match the type set by the previous sqlite3MemdebugSetType().
12156**
12157** Perhaps the most important point is the difference between MEMTYPE_HEAP
12158** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12159** it might have been allocated by lookaside, except the allocation was
12160** too large or lookaside was already full.  It is important to verify
12161** that allocations that might have been satisfied by lookaside are not
12162** passed back to non-lookaside free() routines.  Asserts such as the
12163** example above are placed on the non-lookaside free() routines to verify
12164** this constraint.
12165**
12166** All of this is no-op for a production build.  It only comes into
12167** play when the SQLITE_MEMDEBUG compile-time option is used.
12168*/
12169#ifdef SQLITE_MEMDEBUG
12170SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12171SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12172SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12173#else
12174# define sqlite3MemdebugSetType(X,Y)  /* no-op */
12175# define sqlite3MemdebugHasType(X,Y)  1
12176# define sqlite3MemdebugNoType(X,Y)   1
12177#endif
12178#define MEMTYPE_HEAP       0x01  /* General heap allocations */
12179#define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12180#define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12181#define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12182#define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12183
12184#endif /* _SQLITEINT_H_ */
12185
12186/************** End of sqliteInt.h *******************************************/
12187/************** Begin file global.c ******************************************/
12188/*
12189** 2008 June 13
12190**
12191** The author disclaims copyright to this source code.  In place of
12192** a legal notice, here is a blessing:
12193**
12194**    May you do good and not evil.
12195**    May you find forgiveness for yourself and forgive others.
12196**    May you share freely, never taking more than you give.
12197**
12198*************************************************************************
12199**
12200** This file contains definitions of global variables and contants.
12201*/
12202
12203/* An array to map all upper-case characters into their corresponding
12204** lower-case character.
12205**
12206** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12207** handle case conversions for the UTF character set since the tables
12208** involved are nearly as big or bigger than SQLite itself.
12209*/
12210SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12211#ifdef SQLITE_ASCII
12212      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12213     18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12214     36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12215     54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12216    104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12217    122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12218    108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12219    126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12220    144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12221    162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12222    180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12223    198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12224    216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12225    234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12226    252,253,254,255
12227#endif
12228#ifdef SQLITE_EBCDIC
12229      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12230     16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12231     32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12232     48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12233     64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12234     80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12235     96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12236    112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12237    128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12238    144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12239    160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12240    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12241    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12242    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12243    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12244    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12245#endif
12246};
12247
12248/*
12249** The following 256 byte lookup table is used to support SQLites built-in
12250** equivalents to the following standard library functions:
12251**
12252**   isspace()                        0x01
12253**   isalpha()                        0x02
12254**   isdigit()                        0x04
12255**   isalnum()                        0x06
12256**   isxdigit()                       0x08
12257**   toupper()                        0x20
12258**   SQLite identifier character      0x40
12259**
12260** Bit 0x20 is set if the mapped character requires translation to upper
12261** case. i.e. if the character is a lower-case ASCII character.
12262** If x is a lower-case ASCII character, then its upper-case equivalent
12263** is (x - 0x20). Therefore toupper() can be implemented as:
12264**
12265**   (x & ~(map[x]&0x20))
12266**
12267** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12268** array. tolower() is used more often than toupper() by SQLite.
12269**
12270** Bit 0x40 is set if the character non-alphanumeric and can be used in an
12271** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12272** non-ASCII UTF character. Hence the test for whether or not a character is
12273** part of an identifier is 0x46.
12274**
12275** SQLite's versions are identical to the standard versions assuming a
12276** locale of "C". They are implemented as macros in sqliteInt.h.
12277*/
12278#ifdef SQLITE_ASCII
12279SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12280  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12281  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12282  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12283  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12284  0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12285  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12286  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12287  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12288
12289  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12290  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12291  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12292  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12293  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12294  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12295  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12296  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12297
12298  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12299  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12300  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12301  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12302  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12303  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12304  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12305  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12306
12307  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12308  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12309  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12310  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12311  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12312  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12313  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12314  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12315};
12316#endif
12317
12318#ifndef SQLITE_USE_URI
12319# define  SQLITE_USE_URI 0
12320#endif
12321
12322/*
12323** The following singleton contains the global configuration for
12324** the SQLite library.
12325*/
12326SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12327   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12328   1,                         /* bCoreMutex */
12329   SQLITE_THREADSAFE==1,      /* bFullMutex */
12330   SQLITE_USE_URI,            /* bOpenUri */
12331   0x7ffffffe,                /* mxStrlen */
12332   128,                       /* szLookaside */
12333   500,                       /* nLookaside */
12334   {0,0,0,0,0,0,0,0},         /* m */
12335   {0,0,0,0,0,0,0,0,0},       /* mutex */
12336   {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12337   (void*)0,                  /* pHeap */
12338   0,                         /* nHeap */
12339   0, 0,                      /* mnHeap, mxHeap */
12340   (void*)0,                  /* pScratch */
12341   0,                         /* szScratch */
12342   0,                         /* nScratch */
12343   (void*)0,                  /* pPage */
12344   0,                         /* szPage */
12345   0,                         /* nPage */
12346   0,                         /* mxParserStack */
12347   0,                         /* sharedCacheEnabled */
12348   /* All the rest should always be initialized to zero */
12349   0,                         /* isInit */
12350   0,                         /* inProgress */
12351   0,                         /* isMutexInit */
12352   0,                         /* isMallocInit */
12353   0,                         /* isPCacheInit */
12354   0,                         /* pInitMutex */
12355   0,                         /* nRefInitMutex */
12356   0,                         /* xLog */
12357   0,                         /* pLogArg */
12358   0,                         /* bLocaltimeFault */
12359};
12360
12361
12362/*
12363** Hash table for global functions - functions common to all
12364** database connections.  After initialization, this table is
12365** read-only.
12366*/
12367SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12368
12369/*
12370** Constant tokens for values 0 and 1.
12371*/
12372SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12373   { "0", 1 },
12374   { "1", 1 }
12375};
12376
12377
12378/*
12379** The value of the "pending" byte must be 0x40000000 (1 byte past the
12380** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12381** the database page that contains the pending byte.  It never attempts
12382** to read or write that page.  The pending byte page is set assign
12383** for use by the VFS layers as space for managing file locks.
12384**
12385** During testing, it is often desirable to move the pending byte to
12386** a different position in the file.  This allows code that has to
12387** deal with the pending byte to run on files that are much smaller
12388** than 1 GiB.  The sqlite3_test_control() interface can be used to
12389** move the pending byte.
12390**
12391** IMPORTANT:  Changing the pending byte to any value other than
12392** 0x40000000 results in an incompatible database file format!
12393** Changing the pending byte during operating results in undefined
12394** and dileterious behavior.
12395*/
12396#ifndef SQLITE_OMIT_WSD
12397SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12398#endif
12399
12400/*
12401** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12402** created by mkopcodeh.awk during compilation.  Data is obtained
12403** from the comments following the "case OP_xxxx:" statements in
12404** the vdbe.c file.
12405*/
12406SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12407
12408/************** End of global.c **********************************************/
12409/************** Begin file ctime.c *******************************************/
12410/*
12411** 2010 February 23
12412**
12413** The author disclaims copyright to this source code.  In place of
12414** a legal notice, here is a blessing:
12415**
12416**    May you do good and not evil.
12417**    May you find forgiveness for yourself and forgive others.
12418**    May you share freely, never taking more than you give.
12419**
12420*************************************************************************
12421**
12422** This file implements routines used to report what compile-time options
12423** SQLite was built with.
12424*/
12425
12426#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12427
12428
12429/*
12430** An array of names of all compile-time options.  This array should
12431** be sorted A-Z.
12432**
12433** This array looks large, but in a typical installation actually uses
12434** only a handful of compile-time options, so most times this array is usually
12435** rather short and uses little memory space.
12436*/
12437static const char * const azCompileOpt[] = {
12438
12439/* These macros are provided to "stringify" the value of the define
12440** for those options in which the value is meaningful. */
12441#define CTIMEOPT_VAL_(opt) #opt
12442#define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12443
12444#ifdef SQLITE_32BIT_ROWID
12445  "32BIT_ROWID",
12446#endif
12447#ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12448  "4_BYTE_ALIGNED_MALLOC",
12449#endif
12450#ifdef SQLITE_CASE_SENSITIVE_LIKE
12451  "CASE_SENSITIVE_LIKE",
12452#endif
12453#ifdef SQLITE_CHECK_PAGES
12454  "CHECK_PAGES",
12455#endif
12456#ifdef SQLITE_COVERAGE_TEST
12457  "COVERAGE_TEST",
12458#endif
12459#ifdef SQLITE_DEBUG
12460  "DEBUG",
12461#endif
12462#ifdef SQLITE_DEFAULT_LOCKING_MODE
12463  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12464#endif
12465#ifdef SQLITE_DISABLE_DIRSYNC
12466  "DISABLE_DIRSYNC",
12467#endif
12468#ifdef SQLITE_DISABLE_LFS
12469  "DISABLE_LFS",
12470#endif
12471#ifdef SQLITE_ENABLE_ATOMIC_WRITE
12472  "ENABLE_ATOMIC_WRITE",
12473#endif
12474#ifdef SQLITE_ENABLE_CEROD
12475  "ENABLE_CEROD",
12476#endif
12477#ifdef SQLITE_ENABLE_COLUMN_METADATA
12478  "ENABLE_COLUMN_METADATA",
12479#endif
12480#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12481  "ENABLE_EXPENSIVE_ASSERT",
12482#endif
12483#ifdef SQLITE_ENABLE_FTS1
12484  "ENABLE_FTS1",
12485#endif
12486#ifdef SQLITE_ENABLE_FTS2
12487  "ENABLE_FTS2",
12488#endif
12489#ifdef SQLITE_ENABLE_FTS3
12490  "ENABLE_FTS3",
12491#endif
12492#ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12493  "ENABLE_FTS3_PARENTHESIS",
12494#endif
12495#ifdef SQLITE_ENABLE_FTS4
12496  "ENABLE_FTS4",
12497#endif
12498#ifdef SQLITE_ENABLE_ICU
12499  "ENABLE_ICU",
12500#endif
12501#ifdef SQLITE_ENABLE_IOTRACE
12502  "ENABLE_IOTRACE",
12503#endif
12504#ifdef SQLITE_ENABLE_LOAD_EXTENSION
12505  "ENABLE_LOAD_EXTENSION",
12506#endif
12507#ifdef SQLITE_ENABLE_LOCKING_STYLE
12508  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12509#endif
12510#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12511  "ENABLE_MEMORY_MANAGEMENT",
12512#endif
12513#ifdef SQLITE_ENABLE_MEMSYS3
12514  "ENABLE_MEMSYS3",
12515#endif
12516#ifdef SQLITE_ENABLE_MEMSYS5
12517  "ENABLE_MEMSYS5",
12518#endif
12519#ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12520  "ENABLE_OVERSIZE_CELL_CHECK",
12521#endif
12522#ifdef SQLITE_ENABLE_RTREE
12523  "ENABLE_RTREE",
12524#endif
12525#ifdef SQLITE_ENABLE_STAT3
12526  "ENABLE_STAT3",
12527#endif
12528#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12529  "ENABLE_UNLOCK_NOTIFY",
12530#endif
12531#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12532  "ENABLE_UPDATE_DELETE_LIMIT",
12533#endif
12534#ifdef SQLITE_HAS_CODEC
12535  "HAS_CODEC",
12536#endif
12537#ifdef SQLITE_HAVE_ISNAN
12538  "HAVE_ISNAN",
12539#endif
12540#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12541  "HOMEGROWN_RECURSIVE_MUTEX",
12542#endif
12543#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12544  "IGNORE_AFP_LOCK_ERRORS",
12545#endif
12546#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12547  "IGNORE_FLOCK_LOCK_ERRORS",
12548#endif
12549#ifdef SQLITE_INT64_TYPE
12550  "INT64_TYPE",
12551#endif
12552#ifdef SQLITE_LOCK_TRACE
12553  "LOCK_TRACE",
12554#endif
12555#ifdef SQLITE_MAX_SCHEMA_RETRY
12556  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12557#endif
12558#ifdef SQLITE_MEMDEBUG
12559  "MEMDEBUG",
12560#endif
12561#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12562  "MIXED_ENDIAN_64BIT_FLOAT",
12563#endif
12564#ifdef SQLITE_NO_SYNC
12565  "NO_SYNC",
12566#endif
12567#ifdef SQLITE_OMIT_ALTERTABLE
12568  "OMIT_ALTERTABLE",
12569#endif
12570#ifdef SQLITE_OMIT_ANALYZE
12571  "OMIT_ANALYZE",
12572#endif
12573#ifdef SQLITE_OMIT_ATTACH
12574  "OMIT_ATTACH",
12575#endif
12576#ifdef SQLITE_OMIT_AUTHORIZATION
12577  "OMIT_AUTHORIZATION",
12578#endif
12579#ifdef SQLITE_OMIT_AUTOINCREMENT
12580  "OMIT_AUTOINCREMENT",
12581#endif
12582#ifdef SQLITE_OMIT_AUTOINIT
12583  "OMIT_AUTOINIT",
12584#endif
12585#ifdef SQLITE_OMIT_AUTOMATIC_INDEX
12586  "OMIT_AUTOMATIC_INDEX",
12587#endif
12588#ifdef SQLITE_OMIT_AUTORESET
12589  "OMIT_AUTORESET",
12590#endif
12591#ifdef SQLITE_OMIT_AUTOVACUUM
12592  "OMIT_AUTOVACUUM",
12593#endif
12594#ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
12595  "OMIT_BETWEEN_OPTIMIZATION",
12596#endif
12597#ifdef SQLITE_OMIT_BLOB_LITERAL
12598  "OMIT_BLOB_LITERAL",
12599#endif
12600#ifdef SQLITE_OMIT_BTREECOUNT
12601  "OMIT_BTREECOUNT",
12602#endif
12603#ifdef SQLITE_OMIT_BUILTIN_TEST
12604  "OMIT_BUILTIN_TEST",
12605#endif
12606#ifdef SQLITE_OMIT_CAST
12607  "OMIT_CAST",
12608#endif
12609#ifdef SQLITE_OMIT_CHECK
12610  "OMIT_CHECK",
12611#endif
12612/* // redundant
12613** #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
12614**   "OMIT_COMPILEOPTION_DIAGS",
12615** #endif
12616*/
12617#ifdef SQLITE_OMIT_COMPLETE
12618  "OMIT_COMPLETE",
12619#endif
12620#ifdef SQLITE_OMIT_COMPOUND_SELECT
12621  "OMIT_COMPOUND_SELECT",
12622#endif
12623#ifdef SQLITE_OMIT_DATETIME_FUNCS
12624  "OMIT_DATETIME_FUNCS",
12625#endif
12626#ifdef SQLITE_OMIT_DECLTYPE
12627  "OMIT_DECLTYPE",
12628#endif
12629#ifdef SQLITE_OMIT_DEPRECATED
12630  "OMIT_DEPRECATED",
12631#endif
12632#ifdef SQLITE_OMIT_DISKIO
12633  "OMIT_DISKIO",
12634#endif
12635#ifdef SQLITE_OMIT_EXPLAIN
12636  "OMIT_EXPLAIN",
12637#endif
12638#ifdef SQLITE_OMIT_FLAG_PRAGMAS
12639  "OMIT_FLAG_PRAGMAS",
12640#endif
12641#ifdef SQLITE_OMIT_FLOATING_POINT
12642  "OMIT_FLOATING_POINT",
12643#endif
12644#ifdef SQLITE_OMIT_FOREIGN_KEY
12645  "OMIT_FOREIGN_KEY",
12646#endif
12647#ifdef SQLITE_OMIT_GET_TABLE
12648  "OMIT_GET_TABLE",
12649#endif
12650#ifdef SQLITE_OMIT_INCRBLOB
12651  "OMIT_INCRBLOB",
12652#endif
12653#ifdef SQLITE_OMIT_INTEGRITY_CHECK
12654  "OMIT_INTEGRITY_CHECK",
12655#endif
12656#ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
12657  "OMIT_LIKE_OPTIMIZATION",
12658#endif
12659#ifdef SQLITE_OMIT_LOAD_EXTENSION
12660  "OMIT_LOAD_EXTENSION",
12661#endif
12662#ifdef SQLITE_OMIT_LOCALTIME
12663  "OMIT_LOCALTIME",
12664#endif
12665#ifdef SQLITE_OMIT_LOOKASIDE
12666  "OMIT_LOOKASIDE",
12667#endif
12668#ifdef SQLITE_OMIT_MEMORYDB
12669  "OMIT_MEMORYDB",
12670#endif
12671#ifdef SQLITE_OMIT_MERGE_SORT
12672  "OMIT_MERGE_SORT",
12673#endif
12674#ifdef SQLITE_OMIT_OR_OPTIMIZATION
12675  "OMIT_OR_OPTIMIZATION",
12676#endif
12677#ifdef SQLITE_OMIT_PAGER_PRAGMAS
12678  "OMIT_PAGER_PRAGMAS",
12679#endif
12680#ifdef SQLITE_OMIT_PRAGMA
12681  "OMIT_PRAGMA",
12682#endif
12683#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
12684  "OMIT_PROGRESS_CALLBACK",
12685#endif
12686#ifdef SQLITE_OMIT_QUICKBALANCE
12687  "OMIT_QUICKBALANCE",
12688#endif
12689#ifdef SQLITE_OMIT_REINDEX
12690  "OMIT_REINDEX",
12691#endif
12692#ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
12693  "OMIT_SCHEMA_PRAGMAS",
12694#endif
12695#ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
12696  "OMIT_SCHEMA_VERSION_PRAGMAS",
12697#endif
12698#ifdef SQLITE_OMIT_SHARED_CACHE
12699  "OMIT_SHARED_CACHE",
12700#endif
12701#ifdef SQLITE_OMIT_SUBQUERY
12702  "OMIT_SUBQUERY",
12703#endif
12704#ifdef SQLITE_OMIT_TCL_VARIABLE
12705  "OMIT_TCL_VARIABLE",
12706#endif
12707#ifdef SQLITE_OMIT_TEMPDB
12708  "OMIT_TEMPDB",
12709#endif
12710#ifdef SQLITE_OMIT_TRACE
12711  "OMIT_TRACE",
12712#endif
12713#ifdef SQLITE_OMIT_TRIGGER
12714  "OMIT_TRIGGER",
12715#endif
12716#ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
12717  "OMIT_TRUNCATE_OPTIMIZATION",
12718#endif
12719#ifdef SQLITE_OMIT_UTF16
12720  "OMIT_UTF16",
12721#endif
12722#ifdef SQLITE_OMIT_VACUUM
12723  "OMIT_VACUUM",
12724#endif
12725#ifdef SQLITE_OMIT_VIEW
12726  "OMIT_VIEW",
12727#endif
12728#ifdef SQLITE_OMIT_VIRTUALTABLE
12729  "OMIT_VIRTUALTABLE",
12730#endif
12731#ifdef SQLITE_OMIT_WAL
12732  "OMIT_WAL",
12733#endif
12734#ifdef SQLITE_OMIT_WSD
12735  "OMIT_WSD",
12736#endif
12737#ifdef SQLITE_OMIT_XFER_OPT
12738  "OMIT_XFER_OPT",
12739#endif
12740#ifdef SQLITE_PERFORMANCE_TRACE
12741  "PERFORMANCE_TRACE",
12742#endif
12743#ifdef SQLITE_PROXY_DEBUG
12744  "PROXY_DEBUG",
12745#endif
12746#ifdef SQLITE_SECURE_DELETE
12747  "SECURE_DELETE",
12748#endif
12749#ifdef SQLITE_SMALL_STACK
12750  "SMALL_STACK",
12751#endif
12752#ifdef SQLITE_SOUNDEX
12753  "SOUNDEX",
12754#endif
12755#ifdef SQLITE_TCL
12756  "TCL",
12757#endif
12758#ifdef SQLITE_TEMP_STORE
12759  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
12760#endif
12761#ifdef SQLITE_TEST
12762  "TEST",
12763#endif
12764#ifdef SQLITE_THREADSAFE
12765  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
12766#endif
12767#ifdef SQLITE_USE_ALLOCA
12768  "USE_ALLOCA",
12769#endif
12770#ifdef SQLITE_ZERO_MALLOC
12771  "ZERO_MALLOC"
12772#endif
12773};
12774
12775/*
12776** Given the name of a compile-time option, return true if that option
12777** was used and false if not.
12778**
12779** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
12780** is not required for a match.
12781*/
12782SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
12783  int i, n;
12784  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
12785  n = sqlite3Strlen30(zOptName);
12786
12787  /* Since ArraySize(azCompileOpt) is normally in single digits, a
12788  ** linear search is adequate.  No need for a binary search. */
12789  for(i=0; i<ArraySize(azCompileOpt); i++){
12790    if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
12791       && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
12792  }
12793  return 0;
12794}
12795
12796/*
12797** Return the N-th compile-time option string.  If N is out of range,
12798** return a NULL pointer.
12799*/
12800SQLITE_API const char *sqlite3_compileoption_get(int N){
12801  if( N>=0 && N<ArraySize(azCompileOpt) ){
12802    return azCompileOpt[N];
12803  }
12804  return 0;
12805}
12806
12807#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
12808
12809/************** End of ctime.c ***********************************************/
12810/************** Begin file status.c ******************************************/
12811/*
12812** 2008 June 18
12813**
12814** The author disclaims copyright to this source code.  In place of
12815** a legal notice, here is a blessing:
12816**
12817**    May you do good and not evil.
12818**    May you find forgiveness for yourself and forgive others.
12819**    May you share freely, never taking more than you give.
12820**
12821*************************************************************************
12822**
12823** This module implements the sqlite3_status() interface and related
12824** functionality.
12825*/
12826/************** Include vdbeInt.h in the middle of status.c ******************/
12827/************** Begin file vdbeInt.h *****************************************/
12828/*
12829** 2003 September 6
12830**
12831** The author disclaims copyright to this source code.  In place of
12832** a legal notice, here is a blessing:
12833**
12834**    May you do good and not evil.
12835**    May you find forgiveness for yourself and forgive others.
12836**    May you share freely, never taking more than you give.
12837**
12838*************************************************************************
12839** This is the header file for information that is private to the
12840** VDBE.  This information used to all be at the top of the single
12841** source code file "vdbe.c".  When that file became too big (over
12842** 6000 lines long) it was split up into several smaller files and
12843** this header information was factored out.
12844*/
12845#ifndef _VDBEINT_H_
12846#define _VDBEINT_H_
12847
12848/*
12849** SQL is translated into a sequence of instructions to be
12850** executed by a virtual machine.  Each instruction is an instance
12851** of the following structure.
12852*/
12853typedef struct VdbeOp Op;
12854
12855/*
12856** Boolean values
12857*/
12858typedef unsigned char Bool;
12859
12860/* Opaque type used by code in vdbesort.c */
12861typedef struct VdbeSorter VdbeSorter;
12862
12863/* Opaque type used by the explainer */
12864typedef struct Explain Explain;
12865
12866/*
12867** A cursor is a pointer into a single BTree within a database file.
12868** The cursor can seek to a BTree entry with a particular key, or
12869** loop over all entries of the Btree.  You can also insert new BTree
12870** entries or retrieve the key or data from the entry that the cursor
12871** is currently pointing to.
12872**
12873** Every cursor that the virtual machine has open is represented by an
12874** instance of the following structure.
12875*/
12876struct VdbeCursor {
12877  BtCursor *pCursor;    /* The cursor structure of the backend */
12878  Btree *pBt;           /* Separate file holding temporary table */
12879  KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
12880  int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
12881  int pseudoTableReg;   /* Register holding pseudotable content. */
12882  int nField;           /* Number of fields in the header */
12883  Bool zeroed;          /* True if zeroed out and ready for reuse */
12884  Bool rowidIsValid;    /* True if lastRowid is valid */
12885  Bool atFirst;         /* True if pointing to first entry */
12886  Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
12887  Bool nullRow;         /* True if pointing to a row with no data */
12888  Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
12889  Bool isTable;         /* True if a table requiring integer keys */
12890  Bool isIndex;         /* True if an index containing keys only - no data */
12891  Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
12892  Bool isSorter;        /* True if a new-style sorter */
12893  sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
12894  const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
12895  i64 seqCount;         /* Sequence counter */
12896  i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
12897  i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
12898  VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
12899
12900  /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
12901  ** OP_IsUnique opcode on this cursor. */
12902  int seekResult;
12903
12904  /* Cached information about the header for the data record that the
12905  ** cursor is currently pointing to.  Only valid if cacheStatus matches
12906  ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
12907  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
12908  ** the cache is out of date.
12909  **
12910  ** aRow might point to (ephemeral) data for the current row, or it might
12911  ** be NULL.
12912  */
12913  u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
12914  int payloadSize;      /* Total number of bytes in the record */
12915  u32 *aType;           /* Type values for all entries in the record */
12916  u32 *aOffset;         /* Cached offsets to the start of each columns data */
12917  u8 *aRow;             /* Data for the current row, if all on one page */
12918};
12919typedef struct VdbeCursor VdbeCursor;
12920
12921/*
12922** When a sub-program is executed (OP_Program), a structure of this type
12923** is allocated to store the current value of the program counter, as
12924** well as the current memory cell array and various other frame specific
12925** values stored in the Vdbe struct. When the sub-program is finished,
12926** these values are copied back to the Vdbe from the VdbeFrame structure,
12927** restoring the state of the VM to as it was before the sub-program
12928** began executing.
12929**
12930** The memory for a VdbeFrame object is allocated and managed by a memory
12931** cell in the parent (calling) frame. When the memory cell is deleted or
12932** overwritten, the VdbeFrame object is not freed immediately. Instead, it
12933** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
12934** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
12935** this instead of deleting the VdbeFrame immediately is to avoid recursive
12936** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
12937** child frame are released.
12938**
12939** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
12940** set to NULL if the currently executing frame is the main program.
12941*/
12942typedef struct VdbeFrame VdbeFrame;
12943struct VdbeFrame {
12944  Vdbe *v;                /* VM this frame belongs to */
12945  VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
12946  Op *aOp;                /* Program instructions for parent frame */
12947  Mem *aMem;              /* Array of memory cells for parent frame */
12948  u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
12949  VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
12950  void *token;            /* Copy of SubProgram.token */
12951  i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
12952  u16 nCursor;            /* Number of entries in apCsr */
12953  int pc;                 /* Program Counter in parent (calling) frame */
12954  int nOp;                /* Size of aOp array */
12955  int nMem;               /* Number of entries in aMem */
12956  int nOnceFlag;          /* Number of entries in aOnceFlag */
12957  int nChildMem;          /* Number of memory cells for child frame */
12958  int nChildCsr;          /* Number of cursors for child frame */
12959  int nChange;            /* Statement changes (Vdbe.nChanges)     */
12960};
12961
12962#define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
12963
12964/*
12965** A value for VdbeCursor.cacheValid that means the cache is always invalid.
12966*/
12967#define CACHE_STALE 0
12968
12969/*
12970** Internally, the vdbe manipulates nearly all SQL values as Mem
12971** structures. Each Mem struct may cache multiple representations (string,
12972** integer etc.) of the same value.
12973*/
12974struct Mem {
12975  sqlite3 *db;        /* The associated database connection */
12976  char *z;            /* String or BLOB value */
12977  double r;           /* Real value */
12978  union {
12979    i64 i;              /* Integer value used when MEM_Int is set in flags */
12980    int nZero;          /* Used when bit MEM_Zero is set in flags */
12981    FuncDef *pDef;      /* Used only when flags==MEM_Agg */
12982    RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
12983    VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
12984  } u;
12985  int n;              /* Number of characters in string value, excluding '\0' */
12986  u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
12987  u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
12988  u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
12989#ifdef SQLITE_DEBUG
12990  Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
12991  void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
12992#endif
12993  void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
12994  char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
12995};
12996
12997/* One or more of the following flags are set to indicate the validOK
12998** representations of the value stored in the Mem struct.
12999**
13000** If the MEM_Null flag is set, then the value is an SQL NULL value.
13001** No other flags may be set in this case.
13002**
13003** If the MEM_Str flag is set then Mem.z points at a string representation.
13004** Usually this is encoded in the same unicode encoding as the main
13005** database (see below for exceptions). If the MEM_Term flag is also
13006** set, then the string is nul terminated. The MEM_Int and MEM_Real
13007** flags may coexist with the MEM_Str flag.
13008*/
13009#define MEM_Null      0x0001   /* Value is NULL */
13010#define MEM_Str       0x0002   /* Value is a string */
13011#define MEM_Int       0x0004   /* Value is an integer */
13012#define MEM_Real      0x0008   /* Value is a real number */
13013#define MEM_Blob      0x0010   /* Value is a BLOB */
13014#define MEM_RowSet    0x0020   /* Value is a RowSet object */
13015#define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13016#define MEM_Invalid   0x0080   /* Value is undefined */
13017#define MEM_TypeMask  0x00ff   /* Mask of type bits */
13018
13019/* Whenever Mem contains a valid string or blob representation, one of
13020** the following flags must be set to determine the memory management
13021** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13022** string is \000 or \u0000 terminated
13023*/
13024#define MEM_Term      0x0200   /* String rep is nul terminated */
13025#define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13026#define MEM_Static    0x0800   /* Mem.z points to a static string */
13027#define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13028#define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13029#define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13030#ifdef SQLITE_OMIT_INCRBLOB
13031  #undef MEM_Zero
13032  #define MEM_Zero 0x0000
13033#endif
13034
13035/*
13036** Clear any existing type flags from a Mem and replace them with f
13037*/
13038#define MemSetTypeFlag(p, f) \
13039   ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13040
13041/*
13042** Return true if a memory cell is not marked as invalid.  This macro
13043** is for use inside assert() statements only.
13044*/
13045#ifdef SQLITE_DEBUG
13046#define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13047#endif
13048
13049
13050/* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
13051** additional information about auxiliary information bound to arguments
13052** of the function.  This is used to implement the sqlite3_get_auxdata()
13053** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
13054** that can be associated with a constant argument to a function.  This
13055** allows functions such as "regexp" to compile their constant regular
13056** expression argument once and reused the compiled code for multiple
13057** invocations.
13058*/
13059struct VdbeFunc {
13060  FuncDef *pFunc;               /* The definition of the function */
13061  int nAux;                     /* Number of entries allocated for apAux[] */
13062  struct AuxData {
13063    void *pAux;                   /* Aux data for the i-th argument */
13064    void (*xDelete)(void *);      /* Destructor for the aux data */
13065  } apAux[1];                   /* One slot for each function argument */
13066};
13067
13068/*
13069** The "context" argument for a installable function.  A pointer to an
13070** instance of this structure is the first argument to the routines used
13071** implement the SQL functions.
13072**
13073** There is a typedef for this structure in sqlite.h.  So all routines,
13074** even the public interface to SQLite, can use a pointer to this structure.
13075** But this file is the only place where the internal details of this
13076** structure are known.
13077**
13078** This structure is defined inside of vdbeInt.h because it uses substructures
13079** (Mem) which are only defined there.
13080*/
13081struct sqlite3_context {
13082  FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13083  VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
13084  Mem s;                /* The return value is stored here */
13085  Mem *pMem;            /* Memory cell used to store aggregate context */
13086  CollSeq *pColl;       /* Collating sequence */
13087  int isError;          /* Error code returned by the function. */
13088  int skipFlag;         /* Skip skip accumulator loading if true */
13089};
13090
13091/*
13092** An Explain object accumulates indented output which is helpful
13093** in describing recursive data structures.
13094*/
13095struct Explain {
13096  Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13097  StrAccum str;      /* The string being accumulated */
13098  int nIndent;       /* Number of elements in aIndent */
13099  u16 aIndent[100];  /* Levels of indentation */
13100  char zBase[100];   /* Initial space */
13101};
13102
13103/*
13104** An instance of the virtual machine.  This structure contains the complete
13105** state of the virtual machine.
13106**
13107** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13108** is really a pointer to an instance of this structure.
13109**
13110** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13111** any virtual table method invocations made by the vdbe program. It is
13112** set to 2 for xDestroy method calls and 1 for all other methods. This
13113** variable is used for two purposes: to allow xDestroy methods to execute
13114** "DROP TABLE" statements and to prevent some nasty side effects of
13115** malloc failure when SQLite is invoked recursively by a virtual table
13116** method function.
13117*/
13118struct Vdbe {
13119  sqlite3 *db;            /* The database connection that owns this statement */
13120  Op *aOp;                /* Space to hold the virtual machine's program */
13121  Mem *aMem;              /* The memory locations */
13122  Mem **apArg;            /* Arguments to currently executing user function */
13123  Mem *aColName;          /* Column names to return */
13124  Mem *pResultSet;        /* Pointer to an array of results */
13125  int nMem;               /* Number of memory locations currently allocated */
13126  int nOp;                /* Number of instructions in the program */
13127  int nOpAlloc;           /* Number of slots allocated for aOp[] */
13128  int nLabel;             /* Number of labels used */
13129  int *aLabel;            /* Space to hold the labels */
13130  u16 nResColumn;         /* Number of columns in one row of the result set */
13131  u16 nCursor;            /* Number of slots in apCsr[] */
13132  u32 magic;              /* Magic number for sanity checking */
13133  char *zErrMsg;          /* Error message written here */
13134  Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13135  VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13136  Mem *aVar;              /* Values for the OP_Variable opcode. */
13137  char **azVar;           /* Name of variables */
13138  ynVar nVar;             /* Number of entries in aVar[] */
13139  ynVar nzVar;            /* Number of entries in azVar[] */
13140  u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13141  int pc;                 /* The program counter */
13142  int rc;                 /* Value to return */
13143  u8 errorAction;         /* Recovery action to do in case of an error */
13144  u8 explain;             /* True if EXPLAIN present on SQL command */
13145  u8 changeCntOn;         /* True to update the change-counter */
13146  u8 expired;             /* True if the VM needs to be recompiled */
13147  u8 runOnlyOnce;         /* Automatically expire on reset */
13148  u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13149  u8 inVtabMethod;        /* See comments above */
13150  u8 usesStmtJournal;     /* True if uses a statement journal */
13151  u8 readOnly;            /* True for read-only statements */
13152  u8 isPrepareV2;         /* True if prepared with prepare_v2() */
13153  int nChange;            /* Number of db changes made since last reset */
13154  yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13155  yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13156  int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13157  int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
13158#ifndef SQLITE_OMIT_TRACE
13159  i64 startTime;          /* Time when query started - used for profiling */
13160#endif
13161  i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13162  i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13163  char *zSql;             /* Text of the SQL statement that generated this */
13164  void *pFree;            /* Free this when deleting the vdbe */
13165#ifdef SQLITE_DEBUG
13166  FILE *trace;            /* Write an execution trace here, if not NULL */
13167#endif
13168#ifdef SQLITE_ENABLE_TREE_EXPLAIN
13169  Explain *pExplain;      /* The explainer */
13170  char *zExplain;         /* Explanation of data structures */
13171#endif
13172  VdbeFrame *pFrame;      /* Parent frame */
13173  VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13174  int nFrame;             /* Number of frames in pFrame list */
13175  u32 expmask;            /* Binding to these vars invalidates VM */
13176  SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13177  int nOnceFlag;          /* Size of array aOnceFlag[] */
13178  u8 *aOnceFlag;          /* Flags for OP_Once */
13179};
13180
13181/*
13182** The following are allowed values for Vdbe.magic
13183*/
13184#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13185#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13186#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13187#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13188
13189/*
13190** Function prototypes
13191*/
13192SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13193void sqliteVdbePopStack(Vdbe*,int);
13194SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13195#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13196SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13197#endif
13198SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13199SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13200SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13201SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13202SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
13203
13204int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13205SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13206SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13207SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13208SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13209SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13210SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13211SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13212SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13213SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13214SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13215SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13216SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13217SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13218SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13219#ifdef SQLITE_OMIT_FLOATING_POINT
13220# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13221#else
13222SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13223#endif
13224SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13225SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13226SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13227SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13228SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13229SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13230SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13231SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13232SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13233SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13234SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13235SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13236SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13237SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13238#define VdbeMemRelease(X)  \
13239  if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13240    sqlite3VdbeMemReleaseExternal(X);
13241SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13242SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13243SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13244SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13245SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13246SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13247SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13248SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13249
13250#ifdef SQLITE_OMIT_MERGE_SORT
13251# define sqlite3VdbeSorterInit(Y,Z)      SQLITE_OK
13252# define sqlite3VdbeSorterWrite(X,Y,Z)   SQLITE_OK
13253# define sqlite3VdbeSorterClose(Y,Z)
13254# define sqlite3VdbeSorterRowkey(Y,Z)    SQLITE_OK
13255# define sqlite3VdbeSorterRewind(X,Y,Z)  SQLITE_OK
13256# define sqlite3VdbeSorterNext(X,Y,Z)    SQLITE_OK
13257# define sqlite3VdbeSorterCompare(X,Y,Z) SQLITE_OK
13258#else
13259SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13260SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13261SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *, Mem *);
13262SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, VdbeCursor *, int *);
13263SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, VdbeCursor *, int *);
13264SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, VdbeCursor *, Mem *);
13265SQLITE_PRIVATE int sqlite3VdbeSorterCompare(VdbeCursor *, Mem *, int *);
13266#endif
13267
13268#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13269SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13270SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13271#else
13272# define sqlite3VdbeEnter(X)
13273# define sqlite3VdbeLeave(X)
13274#endif
13275
13276#ifdef SQLITE_DEBUG
13277SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13278#endif
13279
13280#ifndef SQLITE_OMIT_FOREIGN_KEY
13281SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13282#else
13283# define sqlite3VdbeCheckFk(p,i) 0
13284#endif
13285
13286SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13287#ifdef SQLITE_DEBUG
13288SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13289SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13290#endif
13291SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13292
13293#ifndef SQLITE_OMIT_INCRBLOB
13294SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13295  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13296#else
13297  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13298  #define ExpandBlob(P) SQLITE_OK
13299#endif
13300
13301#endif /* !defined(_VDBEINT_H_) */
13302
13303/************** End of vdbeInt.h *********************************************/
13304/************** Continuing where we left off in status.c *********************/
13305
13306/*
13307** Variables in which to record status information.
13308*/
13309typedef struct sqlite3StatType sqlite3StatType;
13310static SQLITE_WSD struct sqlite3StatType {
13311  int nowValue[10];         /* Current value */
13312  int mxValue[10];          /* Maximum value */
13313} sqlite3Stat = { {0,}, {0,} };
13314
13315
13316/* The "wsdStat" macro will resolve to the status information
13317** state vector.  If writable static data is unsupported on the target,
13318** we have to locate the state vector at run-time.  In the more common
13319** case where writable static data is supported, wsdStat can refer directly
13320** to the "sqlite3Stat" state vector declared above.
13321*/
13322#ifdef SQLITE_OMIT_WSD
13323# define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13324# define wsdStat x[0]
13325#else
13326# define wsdStatInit
13327# define wsdStat sqlite3Stat
13328#endif
13329
13330/*
13331** Return the current value of a status parameter.
13332*/
13333SQLITE_PRIVATE int sqlite3StatusValue(int op){
13334  wsdStatInit;
13335  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13336  return wsdStat.nowValue[op];
13337}
13338
13339/*
13340** Add N to the value of a status record.  It is assumed that the
13341** caller holds appropriate locks.
13342*/
13343SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13344  wsdStatInit;
13345  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13346  wsdStat.nowValue[op] += N;
13347  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13348    wsdStat.mxValue[op] = wsdStat.nowValue[op];
13349  }
13350}
13351
13352/*
13353** Set the value of a status to X.
13354*/
13355SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13356  wsdStatInit;
13357  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13358  wsdStat.nowValue[op] = X;
13359  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13360    wsdStat.mxValue[op] = wsdStat.nowValue[op];
13361  }
13362}
13363
13364/*
13365** Query status information.
13366**
13367** This implementation assumes that reading or writing an aligned
13368** 32-bit integer is an atomic operation.  If that assumption is not true,
13369** then this routine is not threadsafe.
13370*/
13371SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13372  wsdStatInit;
13373  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13374    return SQLITE_MISUSE_BKPT;
13375  }
13376  *pCurrent = wsdStat.nowValue[op];
13377  *pHighwater = wsdStat.mxValue[op];
13378  if( resetFlag ){
13379    wsdStat.mxValue[op] = wsdStat.nowValue[op];
13380  }
13381  return SQLITE_OK;
13382}
13383
13384/*
13385** Query status information for a single database connection
13386*/
13387SQLITE_API int sqlite3_db_status(
13388  sqlite3 *db,          /* The database connection whose status is desired */
13389  int op,               /* Status verb */
13390  int *pCurrent,        /* Write current value here */
13391  int *pHighwater,      /* Write high-water mark here */
13392  int resetFlag         /* Reset high-water mark if true */
13393){
13394  int rc = SQLITE_OK;   /* Return code */
13395  sqlite3_mutex_enter(db->mutex);
13396  switch( op ){
13397    case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13398      *pCurrent = db->lookaside.nOut;
13399      *pHighwater = db->lookaside.mxOut;
13400      if( resetFlag ){
13401        db->lookaside.mxOut = db->lookaside.nOut;
13402      }
13403      break;
13404    }
13405
13406    case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13407    case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13408    case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13409      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13410      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13411      testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13412      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13413      assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13414      *pCurrent = 0;
13415      *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13416      if( resetFlag ){
13417        db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13418      }
13419      break;
13420    }
13421
13422    /*
13423    ** Return an approximation for the amount of memory currently used
13424    ** by all pagers associated with the given database connection.  The
13425    ** highwater mark is meaningless and is returned as zero.
13426    */
13427    case SQLITE_DBSTATUS_CACHE_USED: {
13428      int totalUsed = 0;
13429      int i;
13430      sqlite3BtreeEnterAll(db);
13431      for(i=0; i<db->nDb; i++){
13432        Btree *pBt = db->aDb[i].pBt;
13433        if( pBt ){
13434          Pager *pPager = sqlite3BtreePager(pBt);
13435          totalUsed += sqlite3PagerMemUsed(pPager);
13436        }
13437      }
13438      sqlite3BtreeLeaveAll(db);
13439      *pCurrent = totalUsed;
13440      *pHighwater = 0;
13441      break;
13442    }
13443
13444    /*
13445    ** *pCurrent gets an accurate estimate of the amount of memory used
13446    ** to store the schema for all databases (main, temp, and any ATTACHed
13447    ** databases.  *pHighwater is set to zero.
13448    */
13449    case SQLITE_DBSTATUS_SCHEMA_USED: {
13450      int i;                      /* Used to iterate through schemas */
13451      int nByte = 0;              /* Used to accumulate return value */
13452
13453      sqlite3BtreeEnterAll(db);
13454      db->pnBytesFreed = &nByte;
13455      for(i=0; i<db->nDb; i++){
13456        Schema *pSchema = db->aDb[i].pSchema;
13457        if( ALWAYS(pSchema!=0) ){
13458          HashElem *p;
13459
13460          nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13461              pSchema->tblHash.count
13462            + pSchema->trigHash.count
13463            + pSchema->idxHash.count
13464            + pSchema->fkeyHash.count
13465          );
13466          nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13467          nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13468          nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13469          nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13470
13471          for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13472            sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13473          }
13474          for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13475            sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13476          }
13477        }
13478      }
13479      db->pnBytesFreed = 0;
13480      sqlite3BtreeLeaveAll(db);
13481
13482      *pHighwater = 0;
13483      *pCurrent = nByte;
13484      break;
13485    }
13486
13487    /*
13488    ** *pCurrent gets an accurate estimate of the amount of memory used
13489    ** to store all prepared statements.
13490    ** *pHighwater is set to zero.
13491    */
13492    case SQLITE_DBSTATUS_STMT_USED: {
13493      struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13494      int nByte = 0;              /* Used to accumulate return value */
13495
13496      db->pnBytesFreed = &nByte;
13497      for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13498        sqlite3VdbeDeleteObject(db, pVdbe);
13499      }
13500      db->pnBytesFreed = 0;
13501
13502      *pHighwater = 0;
13503      *pCurrent = nByte;
13504
13505      break;
13506    }
13507
13508    /*
13509    ** Set *pCurrent to the total cache hits or misses encountered by all
13510    ** pagers the database handle is connected to. *pHighwater is always set
13511    ** to zero.
13512    */
13513    case SQLITE_DBSTATUS_CACHE_HIT:
13514    case SQLITE_DBSTATUS_CACHE_MISS: {
13515      int i;
13516      int nRet = 0;
13517      assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13518
13519      for(i=0; i<db->nDb; i++){
13520        if( db->aDb[i].pBt ){
13521          Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13522          sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13523        }
13524      }
13525      *pHighwater = 0;
13526      *pCurrent = nRet;
13527      break;
13528    }
13529
13530    default: {
13531      rc = SQLITE_ERROR;
13532    }
13533  }
13534  sqlite3_mutex_leave(db->mutex);
13535  return rc;
13536}
13537
13538/************** End of status.c **********************************************/
13539/************** Begin file date.c ********************************************/
13540/*
13541** 2003 October 31
13542**
13543** The author disclaims copyright to this source code.  In place of
13544** a legal notice, here is a blessing:
13545**
13546**    May you do good and not evil.
13547**    May you find forgiveness for yourself and forgive others.
13548**    May you share freely, never taking more than you give.
13549**
13550*************************************************************************
13551** This file contains the C functions that implement date and time
13552** functions for SQLite.
13553**
13554** There is only one exported symbol in this file - the function
13555** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13556** All other code has file scope.
13557**
13558** SQLite processes all times and dates as Julian Day numbers.  The
13559** dates and times are stored as the number of days since noon
13560** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13561** calendar system.
13562**
13563** 1970-01-01 00:00:00 is JD 2440587.5
13564** 2000-01-01 00:00:00 is JD 2451544.5
13565**
13566** This implemention requires years to be expressed as a 4-digit number
13567** which means that only dates between 0000-01-01 and 9999-12-31 can
13568** be represented, even though julian day numbers allow a much wider
13569** range of dates.
13570**
13571** The Gregorian calendar system is used for all dates and times,
13572** even those that predate the Gregorian calendar.  Historians usually
13573** use the Julian calendar for dates prior to 1582-10-15 and for some
13574** dates afterwards, depending on locale.  Beware of this difference.
13575**
13576** The conversion algorithms are implemented based on descriptions
13577** in the following text:
13578**
13579**      Jean Meeus
13580**      Astronomical Algorithms, 2nd Edition, 1998
13581**      ISBM 0-943396-61-1
13582**      Willmann-Bell, Inc
13583**      Richmond, Virginia (USA)
13584*/
13585/* #include <stdlib.h> */
13586/* #include <assert.h> */
13587#include <time.h>
13588
13589#ifndef SQLITE_OMIT_DATETIME_FUNCS
13590
13591
13592/*
13593** A structure for holding a single date and time.
13594*/
13595typedef struct DateTime DateTime;
13596struct DateTime {
13597  sqlite3_int64 iJD; /* The julian day number times 86400000 */
13598  int Y, M, D;       /* Year, month, and day */
13599  int h, m;          /* Hour and minutes */
13600  int tz;            /* Timezone offset in minutes */
13601  double s;          /* Seconds */
13602  char validYMD;     /* True (1) if Y,M,D are valid */
13603  char validHMS;     /* True (1) if h,m,s are valid */
13604  char validJD;      /* True (1) if iJD is valid */
13605  char validTZ;      /* True (1) if tz is valid */
13606};
13607
13608
13609/*
13610** Convert zDate into one or more integers.  Additional arguments
13611** come in groups of 5 as follows:
13612**
13613**       N       number of digits in the integer
13614**       min     minimum allowed value of the integer
13615**       max     maximum allowed value of the integer
13616**       nextC   first character after the integer
13617**       pVal    where to write the integers value.
13618**
13619** Conversions continue until one with nextC==0 is encountered.
13620** The function returns the number of successful conversions.
13621*/
13622static int getDigits(const char *zDate, ...){
13623  va_list ap;
13624  int val;
13625  int N;
13626  int min;
13627  int max;
13628  int nextC;
13629  int *pVal;
13630  int cnt = 0;
13631  va_start(ap, zDate);
13632  do{
13633    N = va_arg(ap, int);
13634    min = va_arg(ap, int);
13635    max = va_arg(ap, int);
13636    nextC = va_arg(ap, int);
13637    pVal = va_arg(ap, int*);
13638    val = 0;
13639    while( N-- ){
13640      if( !sqlite3Isdigit(*zDate) ){
13641        goto end_getDigits;
13642      }
13643      val = val*10 + *zDate - '0';
13644      zDate++;
13645    }
13646    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
13647      goto end_getDigits;
13648    }
13649    *pVal = val;
13650    zDate++;
13651    cnt++;
13652  }while( nextC );
13653end_getDigits:
13654  va_end(ap);
13655  return cnt;
13656}
13657
13658/*
13659** Parse a timezone extension on the end of a date-time.
13660** The extension is of the form:
13661**
13662**        (+/-)HH:MM
13663**
13664** Or the "zulu" notation:
13665**
13666**        Z
13667**
13668** If the parse is successful, write the number of minutes
13669** of change in p->tz and return 0.  If a parser error occurs,
13670** return non-zero.
13671**
13672** A missing specifier is not considered an error.
13673*/
13674static int parseTimezone(const char *zDate, DateTime *p){
13675  int sgn = 0;
13676  int nHr, nMn;
13677  int c;
13678  while( sqlite3Isspace(*zDate) ){ zDate++; }
13679  p->tz = 0;
13680  c = *zDate;
13681  if( c=='-' ){
13682    sgn = -1;
13683  }else if( c=='+' ){
13684    sgn = +1;
13685  }else if( c=='Z' || c=='z' ){
13686    zDate++;
13687    goto zulu_time;
13688  }else{
13689    return c!=0;
13690  }
13691  zDate++;
13692  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
13693    return 1;
13694  }
13695  zDate += 5;
13696  p->tz = sgn*(nMn + nHr*60);
13697zulu_time:
13698  while( sqlite3Isspace(*zDate) ){ zDate++; }
13699  return *zDate!=0;
13700}
13701
13702/*
13703** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
13704** The HH, MM, and SS must each be exactly 2 digits.  The
13705** fractional seconds FFFF can be one or more digits.
13706**
13707** Return 1 if there is a parsing error and 0 on success.
13708*/
13709static int parseHhMmSs(const char *zDate, DateTime *p){
13710  int h, m, s;
13711  double ms = 0.0;
13712  if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
13713    return 1;
13714  }
13715  zDate += 5;
13716  if( *zDate==':' ){
13717    zDate++;
13718    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
13719      return 1;
13720    }
13721    zDate += 2;
13722    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
13723      double rScale = 1.0;
13724      zDate++;
13725      while( sqlite3Isdigit(*zDate) ){
13726        ms = ms*10.0 + *zDate - '0';
13727        rScale *= 10.0;
13728        zDate++;
13729      }
13730      ms /= rScale;
13731    }
13732  }else{
13733    s = 0;
13734  }
13735  p->validJD = 0;
13736  p->validHMS = 1;
13737  p->h = h;
13738  p->m = m;
13739  p->s = s + ms;
13740  if( parseTimezone(zDate, p) ) return 1;
13741  p->validTZ = (p->tz!=0)?1:0;
13742  return 0;
13743}
13744
13745/*
13746** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
13747** that the YYYY-MM-DD is according to the Gregorian calendar.
13748**
13749** Reference:  Meeus page 61
13750*/
13751static void computeJD(DateTime *p){
13752  int Y, M, D, A, B, X1, X2;
13753
13754  if( p->validJD ) return;
13755  if( p->validYMD ){
13756    Y = p->Y;
13757    M = p->M;
13758    D = p->D;
13759  }else{
13760    Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
13761    M = 1;
13762    D = 1;
13763  }
13764  if( M<=2 ){
13765    Y--;
13766    M += 12;
13767  }
13768  A = Y/100;
13769  B = 2 - A + (A/4);
13770  X1 = 36525*(Y+4716)/100;
13771  X2 = 306001*(M+1)/10000;
13772  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
13773  p->validJD = 1;
13774  if( p->validHMS ){
13775    p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
13776    if( p->validTZ ){
13777      p->iJD -= p->tz*60000;
13778      p->validYMD = 0;
13779      p->validHMS = 0;
13780      p->validTZ = 0;
13781    }
13782  }
13783}
13784
13785/*
13786** Parse dates of the form
13787**
13788**     YYYY-MM-DD HH:MM:SS.FFF
13789**     YYYY-MM-DD HH:MM:SS
13790**     YYYY-MM-DD HH:MM
13791**     YYYY-MM-DD
13792**
13793** Write the result into the DateTime structure and return 0
13794** on success and 1 if the input string is not a well-formed
13795** date.
13796*/
13797static int parseYyyyMmDd(const char *zDate, DateTime *p){
13798  int Y, M, D, neg;
13799
13800  if( zDate[0]=='-' ){
13801    zDate++;
13802    neg = 1;
13803  }else{
13804    neg = 0;
13805  }
13806  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
13807    return 1;
13808  }
13809  zDate += 10;
13810  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
13811  if( parseHhMmSs(zDate, p)==0 ){
13812    /* We got the time */
13813  }else if( *zDate==0 ){
13814    p->validHMS = 0;
13815  }else{
13816    return 1;
13817  }
13818  p->validJD = 0;
13819  p->validYMD = 1;
13820  p->Y = neg ? -Y : Y;
13821  p->M = M;
13822  p->D = D;
13823  if( p->validTZ ){
13824    computeJD(p);
13825  }
13826  return 0;
13827}
13828
13829/*
13830** Set the time to the current time reported by the VFS.
13831**
13832** Return the number of errors.
13833*/
13834static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
13835  sqlite3 *db = sqlite3_context_db_handle(context);
13836  if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
13837    p->validJD = 1;
13838    return 0;
13839  }else{
13840    return 1;
13841  }
13842}
13843
13844/*
13845** Attempt to parse the given string into a Julian Day Number.  Return
13846** the number of errors.
13847**
13848** The following are acceptable forms for the input string:
13849**
13850**      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
13851**      DDDD.DD
13852**      now
13853**
13854** In the first form, the +/-HH:MM is always optional.  The fractional
13855** seconds extension (the ".FFF") is optional.  The seconds portion
13856** (":SS.FFF") is option.  The year and date can be omitted as long
13857** as there is a time string.  The time string can be omitted as long
13858** as there is a year and date.
13859*/
13860static int parseDateOrTime(
13861  sqlite3_context *context,
13862  const char *zDate,
13863  DateTime *p
13864){
13865  double r;
13866  if( parseYyyyMmDd(zDate,p)==0 ){
13867    return 0;
13868  }else if( parseHhMmSs(zDate, p)==0 ){
13869    return 0;
13870  }else if( sqlite3StrICmp(zDate,"now")==0){
13871    return setDateTimeToCurrent(context, p);
13872  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
13873    p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
13874    p->validJD = 1;
13875    return 0;
13876  }
13877  return 1;
13878}
13879
13880/*
13881** Compute the Year, Month, and Day from the julian day number.
13882*/
13883static void computeYMD(DateTime *p){
13884  int Z, A, B, C, D, E, X1;
13885  if( p->validYMD ) return;
13886  if( !p->validJD ){
13887    p->Y = 2000;
13888    p->M = 1;
13889    p->D = 1;
13890  }else{
13891    Z = (int)((p->iJD + 43200000)/86400000);
13892    A = (int)((Z - 1867216.25)/36524.25);
13893    A = Z + 1 + A - (A/4);
13894    B = A + 1524;
13895    C = (int)((B - 122.1)/365.25);
13896    D = (36525*C)/100;
13897    E = (int)((B-D)/30.6001);
13898    X1 = (int)(30.6001*E);
13899    p->D = B - D - X1;
13900    p->M = E<14 ? E-1 : E-13;
13901    p->Y = p->M>2 ? C - 4716 : C - 4715;
13902  }
13903  p->validYMD = 1;
13904}
13905
13906/*
13907** Compute the Hour, Minute, and Seconds from the julian day number.
13908*/
13909static void computeHMS(DateTime *p){
13910  int s;
13911  if( p->validHMS ) return;
13912  computeJD(p);
13913  s = (int)((p->iJD + 43200000) % 86400000);
13914  p->s = s/1000.0;
13915  s = (int)p->s;
13916  p->s -= s;
13917  p->h = s/3600;
13918  s -= p->h*3600;
13919  p->m = s/60;
13920  p->s += s - p->m*60;
13921  p->validHMS = 1;
13922}
13923
13924/*
13925** Compute both YMD and HMS
13926*/
13927static void computeYMD_HMS(DateTime *p){
13928  computeYMD(p);
13929  computeHMS(p);
13930}
13931
13932/*
13933** Clear the YMD and HMS and the TZ
13934*/
13935static void clearYMD_HMS_TZ(DateTime *p){
13936  p->validYMD = 0;
13937  p->validHMS = 0;
13938  p->validTZ = 0;
13939}
13940
13941/*
13942** On recent Windows platforms, the localtime_s() function is available
13943** as part of the "Secure CRT". It is essentially equivalent to
13944** localtime_r() available under most POSIX platforms, except that the
13945** order of the parameters is reversed.
13946**
13947** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
13948**
13949** If the user has not indicated to use localtime_r() or localtime_s()
13950** already, check for an MSVC build environment that provides
13951** localtime_s().
13952*/
13953#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
13954     defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
13955#define HAVE_LOCALTIME_S 1
13956#endif
13957
13958#ifndef SQLITE_OMIT_LOCALTIME
13959/*
13960** The following routine implements the rough equivalent of localtime_r()
13961** using whatever operating-system specific localtime facility that
13962** is available.  This routine returns 0 on success and
13963** non-zero on any kind of error.
13964**
13965** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
13966** routine will always fail.
13967*/
13968static int osLocaltime(time_t *t, struct tm *pTm){
13969  int rc;
13970#if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
13971      && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
13972  struct tm *pX;
13973#if SQLITE_THREADSAFE>0
13974  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
13975#endif
13976  sqlite3_mutex_enter(mutex);
13977  pX = localtime(t);
13978#ifndef SQLITE_OMIT_BUILTIN_TEST
13979  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
13980#endif
13981  if( pX ) *pTm = *pX;
13982  sqlite3_mutex_leave(mutex);
13983  rc = pX==0;
13984#else
13985#ifndef SQLITE_OMIT_BUILTIN_TEST
13986  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
13987#endif
13988#if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
13989  rc = localtime_r(t, pTm)==0;
13990#else
13991  rc = localtime_s(pTm, t);
13992#endif /* HAVE_LOCALTIME_R */
13993#endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
13994  return rc;
13995}
13996#endif /* SQLITE_OMIT_LOCALTIME */
13997
13998
13999#ifndef SQLITE_OMIT_LOCALTIME
14000/*
14001** Compute the difference (in milliseconds) between localtime and UTC
14002** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14003** return this value and set *pRc to SQLITE_OK.
14004**
14005** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14006** is undefined in this case.
14007*/
14008static sqlite3_int64 localtimeOffset(
14009  DateTime *p,                    /* Date at which to calculate offset */
14010  sqlite3_context *pCtx,          /* Write error here if one occurs */
14011  int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14012){
14013  DateTime x, y;
14014  time_t t;
14015  struct tm sLocal;
14016
14017  /* Initialize the contents of sLocal to avoid a compiler warning. */
14018  memset(&sLocal, 0, sizeof(sLocal));
14019
14020  x = *p;
14021  computeYMD_HMS(&x);
14022  if( x.Y<1971 || x.Y>=2038 ){
14023    x.Y = 2000;
14024    x.M = 1;
14025    x.D = 1;
14026    x.h = 0;
14027    x.m = 0;
14028    x.s = 0.0;
14029  } else {
14030    int s = (int)(x.s + 0.5);
14031    x.s = s;
14032  }
14033  x.tz = 0;
14034  x.validJD = 0;
14035  computeJD(&x);
14036  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14037  if( osLocaltime(&t, &sLocal) ){
14038    sqlite3_result_error(pCtx, "local time unavailable", -1);
14039    *pRc = SQLITE_ERROR;
14040    return 0;
14041  }
14042  y.Y = sLocal.tm_year + 1900;
14043  y.M = sLocal.tm_mon + 1;
14044  y.D = sLocal.tm_mday;
14045  y.h = sLocal.tm_hour;
14046  y.m = sLocal.tm_min;
14047  y.s = sLocal.tm_sec;
14048  y.validYMD = 1;
14049  y.validHMS = 1;
14050  y.validJD = 0;
14051  y.validTZ = 0;
14052  computeJD(&y);
14053  *pRc = SQLITE_OK;
14054  return y.iJD - x.iJD;
14055}
14056#endif /* SQLITE_OMIT_LOCALTIME */
14057
14058/*
14059** Process a modifier to a date-time stamp.  The modifiers are
14060** as follows:
14061**
14062**     NNN days
14063**     NNN hours
14064**     NNN minutes
14065**     NNN.NNNN seconds
14066**     NNN months
14067**     NNN years
14068**     start of month
14069**     start of year
14070**     start of week
14071**     start of day
14072**     weekday N
14073**     unixepoch
14074**     localtime
14075**     utc
14076**
14077** Return 0 on success and 1 if there is any kind of error. If the error
14078** is in a system call (i.e. localtime()), then an error message is written
14079** to context pCtx. If the error is an unrecognized modifier, no error is
14080** written to pCtx.
14081*/
14082static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14083  int rc = 1;
14084  int n;
14085  double r;
14086  char *z, zBuf[30];
14087  z = zBuf;
14088  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14089    z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14090  }
14091  z[n] = 0;
14092  switch( z[0] ){
14093#ifndef SQLITE_OMIT_LOCALTIME
14094    case 'l': {
14095      /*    localtime
14096      **
14097      ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14098      ** show local time.
14099      */
14100      if( strcmp(z, "localtime")==0 ){
14101        computeJD(p);
14102        p->iJD += localtimeOffset(p, pCtx, &rc);
14103        clearYMD_HMS_TZ(p);
14104      }
14105      break;
14106    }
14107#endif
14108    case 'u': {
14109      /*
14110      **    unixepoch
14111      **
14112      ** Treat the current value of p->iJD as the number of
14113      ** seconds since 1970.  Convert to a real julian day number.
14114      */
14115      if( strcmp(z, "unixepoch")==0 && p->validJD ){
14116        p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14117        clearYMD_HMS_TZ(p);
14118        rc = 0;
14119      }
14120#ifndef SQLITE_OMIT_LOCALTIME
14121      else if( strcmp(z, "utc")==0 ){
14122        sqlite3_int64 c1;
14123        computeJD(p);
14124        c1 = localtimeOffset(p, pCtx, &rc);
14125        if( rc==SQLITE_OK ){
14126          p->iJD -= c1;
14127          clearYMD_HMS_TZ(p);
14128          p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14129        }
14130      }
14131#endif
14132      break;
14133    }
14134    case 'w': {
14135      /*
14136      **    weekday N
14137      **
14138      ** Move the date to the same time on the next occurrence of
14139      ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14140      ** date is already on the appropriate weekday, this is a no-op.
14141      */
14142      if( strncmp(z, "weekday ", 8)==0
14143               && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14144               && (n=(int)r)==r && n>=0 && r<7 ){
14145        sqlite3_int64 Z;
14146        computeYMD_HMS(p);
14147        p->validTZ = 0;
14148        p->validJD = 0;
14149        computeJD(p);
14150        Z = ((p->iJD + 129600000)/86400000) % 7;
14151        if( Z>n ) Z -= 7;
14152        p->iJD += (n - Z)*86400000;
14153        clearYMD_HMS_TZ(p);
14154        rc = 0;
14155      }
14156      break;
14157    }
14158    case 's': {
14159      /*
14160      **    start of TTTTT
14161      **
14162      ** Move the date backwards to the beginning of the current day,
14163      ** or month or year.
14164      */
14165      if( strncmp(z, "start of ", 9)!=0 ) break;
14166      z += 9;
14167      computeYMD(p);
14168      p->validHMS = 1;
14169      p->h = p->m = 0;
14170      p->s = 0.0;
14171      p->validTZ = 0;
14172      p->validJD = 0;
14173      if( strcmp(z,"month")==0 ){
14174        p->D = 1;
14175        rc = 0;
14176      }else if( strcmp(z,"year")==0 ){
14177        computeYMD(p);
14178        p->M = 1;
14179        p->D = 1;
14180        rc = 0;
14181      }else if( strcmp(z,"day")==0 ){
14182        rc = 0;
14183      }
14184      break;
14185    }
14186    case '+':
14187    case '-':
14188    case '0':
14189    case '1':
14190    case '2':
14191    case '3':
14192    case '4':
14193    case '5':
14194    case '6':
14195    case '7':
14196    case '8':
14197    case '9': {
14198      double rRounder;
14199      for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14200      if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14201        rc = 1;
14202        break;
14203      }
14204      if( z[n]==':' ){
14205        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14206        ** specified number of hours, minutes, seconds, and fractional seconds
14207        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14208        ** omitted.
14209        */
14210        const char *z2 = z;
14211        DateTime tx;
14212        sqlite3_int64 day;
14213        if( !sqlite3Isdigit(*z2) ) z2++;
14214        memset(&tx, 0, sizeof(tx));
14215        if( parseHhMmSs(z2, &tx) ) break;
14216        computeJD(&tx);
14217        tx.iJD -= 43200000;
14218        day = tx.iJD/86400000;
14219        tx.iJD -= day*86400000;
14220        if( z[0]=='-' ) tx.iJD = -tx.iJD;
14221        computeJD(p);
14222        clearYMD_HMS_TZ(p);
14223        p->iJD += tx.iJD;
14224        rc = 0;
14225        break;
14226      }
14227      z += n;
14228      while( sqlite3Isspace(*z) ) z++;
14229      n = sqlite3Strlen30(z);
14230      if( n>10 || n<3 ) break;
14231      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14232      computeJD(p);
14233      rc = 0;
14234      rRounder = r<0 ? -0.5 : +0.5;
14235      if( n==3 && strcmp(z,"day")==0 ){
14236        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14237      }else if( n==4 && strcmp(z,"hour")==0 ){
14238        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14239      }else if( n==6 && strcmp(z,"minute")==0 ){
14240        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14241      }else if( n==6 && strcmp(z,"second")==0 ){
14242        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14243      }else if( n==5 && strcmp(z,"month")==0 ){
14244        int x, y;
14245        computeYMD_HMS(p);
14246        p->M += (int)r;
14247        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14248        p->Y += x;
14249        p->M -= x*12;
14250        p->validJD = 0;
14251        computeJD(p);
14252        y = (int)r;
14253        if( y!=r ){
14254          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14255        }
14256      }else if( n==4 && strcmp(z,"year")==0 ){
14257        int y = (int)r;
14258        computeYMD_HMS(p);
14259        p->Y += y;
14260        p->validJD = 0;
14261        computeJD(p);
14262        if( y!=r ){
14263          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14264        }
14265      }else{
14266        rc = 1;
14267      }
14268      clearYMD_HMS_TZ(p);
14269      break;
14270    }
14271    default: {
14272      break;
14273    }
14274  }
14275  return rc;
14276}
14277
14278/*
14279** Process time function arguments.  argv[0] is a date-time stamp.
14280** argv[1] and following are modifiers.  Parse them all and write
14281** the resulting time into the DateTime structure p.  Return 0
14282** on success and 1 if there are any errors.
14283**
14284** If there are zero parameters (if even argv[0] is undefined)
14285** then assume a default value of "now" for argv[0].
14286*/
14287static int isDate(
14288  sqlite3_context *context,
14289  int argc,
14290  sqlite3_value **argv,
14291  DateTime *p
14292){
14293  int i;
14294  const unsigned char *z;
14295  int eType;
14296  memset(p, 0, sizeof(*p));
14297  if( argc==0 ){
14298    return setDateTimeToCurrent(context, p);
14299  }
14300  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14301                   || eType==SQLITE_INTEGER ){
14302    p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14303    p->validJD = 1;
14304  }else{
14305    z = sqlite3_value_text(argv[0]);
14306    if( !z || parseDateOrTime(context, (char*)z, p) ){
14307      return 1;
14308    }
14309  }
14310  for(i=1; i<argc; i++){
14311    z = sqlite3_value_text(argv[i]);
14312    if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14313  }
14314  return 0;
14315}
14316
14317
14318/*
14319** The following routines implement the various date and time functions
14320** of SQLite.
14321*/
14322
14323/*
14324**    julianday( TIMESTRING, MOD, MOD, ...)
14325**
14326** Return the julian day number of the date specified in the arguments
14327*/
14328static void juliandayFunc(
14329  sqlite3_context *context,
14330  int argc,
14331  sqlite3_value **argv
14332){
14333  DateTime x;
14334  if( isDate(context, argc, argv, &x)==0 ){
14335    computeJD(&x);
14336    sqlite3_result_double(context, x.iJD/86400000.0);
14337  }
14338}
14339
14340/*
14341**    datetime( TIMESTRING, MOD, MOD, ...)
14342**
14343** Return YYYY-MM-DD HH:MM:SS
14344*/
14345static void datetimeFunc(
14346  sqlite3_context *context,
14347  int argc,
14348  sqlite3_value **argv
14349){
14350  DateTime x;
14351  if( isDate(context, argc, argv, &x)==0 ){
14352    char zBuf[100];
14353    computeYMD_HMS(&x);
14354    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14355                     x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14356    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14357  }
14358}
14359
14360/*
14361**    time( TIMESTRING, MOD, MOD, ...)
14362**
14363** Return HH:MM:SS
14364*/
14365static void timeFunc(
14366  sqlite3_context *context,
14367  int argc,
14368  sqlite3_value **argv
14369){
14370  DateTime x;
14371  if( isDate(context, argc, argv, &x)==0 ){
14372    char zBuf[100];
14373    computeHMS(&x);
14374    sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14375    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14376  }
14377}
14378
14379/*
14380**    date( TIMESTRING, MOD, MOD, ...)
14381**
14382** Return YYYY-MM-DD
14383*/
14384static void dateFunc(
14385  sqlite3_context *context,
14386  int argc,
14387  sqlite3_value **argv
14388){
14389  DateTime x;
14390  if( isDate(context, argc, argv, &x)==0 ){
14391    char zBuf[100];
14392    computeYMD(&x);
14393    sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14394    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14395  }
14396}
14397
14398/*
14399**    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14400**
14401** Return a string described by FORMAT.  Conversions as follows:
14402**
14403**   %d  day of month
14404**   %f  ** fractional seconds  SS.SSS
14405**   %H  hour 00-24
14406**   %j  day of year 000-366
14407**   %J  ** Julian day number
14408**   %m  month 01-12
14409**   %M  minute 00-59
14410**   %s  seconds since 1970-01-01
14411**   %S  seconds 00-59
14412**   %w  day of week 0-6  sunday==0
14413**   %W  week of year 00-53
14414**   %Y  year 0000-9999
14415**   %%  %
14416*/
14417static void strftimeFunc(
14418  sqlite3_context *context,
14419  int argc,
14420  sqlite3_value **argv
14421){
14422  DateTime x;
14423  u64 n;
14424  size_t i,j;
14425  char *z;
14426  sqlite3 *db;
14427  const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14428  char zBuf[100];
14429  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14430  db = sqlite3_context_db_handle(context);
14431  for(i=0, n=1; zFmt[i]; i++, n++){
14432    if( zFmt[i]=='%' ){
14433      switch( zFmt[i+1] ){
14434        case 'd':
14435        case 'H':
14436        case 'm':
14437        case 'M':
14438        case 'S':
14439        case 'W':
14440          n++;
14441          /* fall thru */
14442        case 'w':
14443        case '%':
14444          break;
14445        case 'f':
14446          n += 8;
14447          break;
14448        case 'j':
14449          n += 3;
14450          break;
14451        case 'Y':
14452          n += 8;
14453          break;
14454        case 's':
14455        case 'J':
14456          n += 50;
14457          break;
14458        default:
14459          return;  /* ERROR.  return a NULL */
14460      }
14461      i++;
14462    }
14463  }
14464  testcase( n==sizeof(zBuf)-1 );
14465  testcase( n==sizeof(zBuf) );
14466  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14467  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14468  if( n<sizeof(zBuf) ){
14469    z = zBuf;
14470  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14471    sqlite3_result_error_toobig(context);
14472    return;
14473  }else{
14474    z = sqlite3DbMallocRaw(db, (int)n);
14475    if( z==0 ){
14476      sqlite3_result_error_nomem(context);
14477      return;
14478    }
14479  }
14480  computeJD(&x);
14481  computeYMD_HMS(&x);
14482  for(i=j=0; zFmt[i]; i++){
14483    if( zFmt[i]!='%' ){
14484      z[j++] = zFmt[i];
14485    }else{
14486      i++;
14487      switch( zFmt[i] ){
14488        case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14489        case 'f': {
14490          double s = x.s;
14491          if( s>59.999 ) s = 59.999;
14492          sqlite3_snprintf(7, &z[j],"%06.3f", s);
14493          j += sqlite3Strlen30(&z[j]);
14494          break;
14495        }
14496        case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14497        case 'W': /* Fall thru */
14498        case 'j': {
14499          int nDay;             /* Number of days since 1st day of year */
14500          DateTime y = x;
14501          y.validJD = 0;
14502          y.M = 1;
14503          y.D = 1;
14504          computeJD(&y);
14505          nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14506          if( zFmt[i]=='W' ){
14507            int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14508            wd = (int)(((x.iJD+43200000)/86400000)%7);
14509            sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14510            j += 2;
14511          }else{
14512            sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14513            j += 3;
14514          }
14515          break;
14516        }
14517        case 'J': {
14518          sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14519          j+=sqlite3Strlen30(&z[j]);
14520          break;
14521        }
14522        case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14523        case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14524        case 's': {
14525          sqlite3_snprintf(30,&z[j],"%lld",
14526                           (i64)(x.iJD/1000 - 21086676*(i64)10000));
14527          j += sqlite3Strlen30(&z[j]);
14528          break;
14529        }
14530        case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14531        case 'w': {
14532          z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14533          break;
14534        }
14535        case 'Y': {
14536          sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14537          break;
14538        }
14539        default:   z[j++] = '%'; break;
14540      }
14541    }
14542  }
14543  z[j] = 0;
14544  sqlite3_result_text(context, z, -1,
14545                      z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14546}
14547
14548/*
14549** current_time()
14550**
14551** This function returns the same value as time('now').
14552*/
14553static void ctimeFunc(
14554  sqlite3_context *context,
14555  int NotUsed,
14556  sqlite3_value **NotUsed2
14557){
14558  UNUSED_PARAMETER2(NotUsed, NotUsed2);
14559  timeFunc(context, 0, 0);
14560}
14561
14562/*
14563** current_date()
14564**
14565** This function returns the same value as date('now').
14566*/
14567static void cdateFunc(
14568  sqlite3_context *context,
14569  int NotUsed,
14570  sqlite3_value **NotUsed2
14571){
14572  UNUSED_PARAMETER2(NotUsed, NotUsed2);
14573  dateFunc(context, 0, 0);
14574}
14575
14576/*
14577** current_timestamp()
14578**
14579** This function returns the same value as datetime('now').
14580*/
14581static void ctimestampFunc(
14582  sqlite3_context *context,
14583  int NotUsed,
14584  sqlite3_value **NotUsed2
14585){
14586  UNUSED_PARAMETER2(NotUsed, NotUsed2);
14587  datetimeFunc(context, 0, 0);
14588}
14589#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
14590
14591#ifdef SQLITE_OMIT_DATETIME_FUNCS
14592/*
14593** If the library is compiled to omit the full-scale date and time
14594** handling (to get a smaller binary), the following minimal version
14595** of the functions current_time(), current_date() and current_timestamp()
14596** are included instead. This is to support column declarations that
14597** include "DEFAULT CURRENT_TIME" etc.
14598**
14599** This function uses the C-library functions time(), gmtime()
14600** and strftime(). The format string to pass to strftime() is supplied
14601** as the user-data for the function.
14602*/
14603static void currentTimeFunc(
14604  sqlite3_context *context,
14605  int argc,
14606  sqlite3_value **argv
14607){
14608  time_t t;
14609  char *zFormat = (char *)sqlite3_user_data(context);
14610  sqlite3 *db;
14611  sqlite3_int64 iT;
14612  struct tm *pTm;
14613  struct tm sNow;
14614  char zBuf[20];
14615
14616  UNUSED_PARAMETER(argc);
14617  UNUSED_PARAMETER(argv);
14618
14619  db = sqlite3_context_db_handle(context);
14620  if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
14621  t = iT/1000 - 10000*(sqlite3_int64)21086676;
14622#ifdef HAVE_GMTIME_R
14623  pTm = gmtime_r(&t, &sNow);
14624#else
14625  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14626  pTm = gmtime(&t);
14627  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
14628  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
14629#endif
14630  if( pTm ){
14631    strftime(zBuf, 20, zFormat, &sNow);
14632    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14633  }
14634}
14635#endif
14636
14637/*
14638** This function registered all of the above C functions as SQL
14639** functions.  This should be the only routine in this file with
14640** external linkage.
14641*/
14642SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
14643  static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
14644#ifndef SQLITE_OMIT_DATETIME_FUNCS
14645    FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
14646    FUNCTION(date,             -1, 0, 0, dateFunc      ),
14647    FUNCTION(time,             -1, 0, 0, timeFunc      ),
14648    FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
14649    FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
14650    FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
14651    FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
14652    FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
14653#else
14654    STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
14655    STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
14656    STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
14657#endif
14658  };
14659  int i;
14660  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
14661  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
14662
14663  for(i=0; i<ArraySize(aDateTimeFuncs); i++){
14664    sqlite3FuncDefInsert(pHash, &aFunc[i]);
14665  }
14666}
14667
14668/************** End of date.c ************************************************/
14669/************** Begin file os.c **********************************************/
14670/*
14671** 2005 November 29
14672**
14673** The author disclaims copyright to this source code.  In place of
14674** a legal notice, here is a blessing:
14675**
14676**    May you do good and not evil.
14677**    May you find forgiveness for yourself and forgive others.
14678**    May you share freely, never taking more than you give.
14679**
14680******************************************************************************
14681**
14682** This file contains OS interface code that is common to all
14683** architectures.
14684*/
14685#define _SQLITE_OS_C_ 1
14686#undef _SQLITE_OS_C_
14687
14688/*
14689** The default SQLite sqlite3_vfs implementations do not allocate
14690** memory (actually, os_unix.c allocates a small amount of memory
14691** from within OsOpen()), but some third-party implementations may.
14692** So we test the effects of a malloc() failing and the sqlite3OsXXX()
14693** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
14694**
14695** The following functions are instrumented for malloc() failure
14696** testing:
14697**
14698**     sqlite3OsRead()
14699**     sqlite3OsWrite()
14700**     sqlite3OsSync()
14701**     sqlite3OsFileSize()
14702**     sqlite3OsLock()
14703**     sqlite3OsCheckReservedLock()
14704**     sqlite3OsFileControl()
14705**     sqlite3OsShmMap()
14706**     sqlite3OsOpen()
14707**     sqlite3OsDelete()
14708**     sqlite3OsAccess()
14709**     sqlite3OsFullPathname()
14710**
14711*/
14712#if defined(SQLITE_TEST)
14713SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
14714  #define DO_OS_MALLOC_TEST(x)                                       \
14715  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
14716    void *pTstAlloc = sqlite3Malloc(10);                             \
14717    if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
14718    sqlite3_free(pTstAlloc);                                         \
14719  }
14720#else
14721  #define DO_OS_MALLOC_TEST(x)
14722#endif
14723
14724/*
14725** The following routines are convenience wrappers around methods
14726** of the sqlite3_file object.  This is mostly just syntactic sugar. All
14727** of this would be completely automatic if SQLite were coded using
14728** C++ instead of plain old C.
14729*/
14730SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
14731  int rc = SQLITE_OK;
14732  if( pId->pMethods ){
14733    rc = pId->pMethods->xClose(pId);
14734    pId->pMethods = 0;
14735  }
14736  return rc;
14737}
14738SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
14739  DO_OS_MALLOC_TEST(id);
14740  return id->pMethods->xRead(id, pBuf, amt, offset);
14741}
14742SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
14743  DO_OS_MALLOC_TEST(id);
14744  return id->pMethods->xWrite(id, pBuf, amt, offset);
14745}
14746SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
14747  return id->pMethods->xTruncate(id, size);
14748}
14749SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
14750  DO_OS_MALLOC_TEST(id);
14751  return id->pMethods->xSync(id, flags);
14752}
14753SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
14754  DO_OS_MALLOC_TEST(id);
14755  return id->pMethods->xFileSize(id, pSize);
14756}
14757SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
14758  DO_OS_MALLOC_TEST(id);
14759  return id->pMethods->xLock(id, lockType);
14760}
14761SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
14762  return id->pMethods->xUnlock(id, lockType);
14763}
14764SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
14765  DO_OS_MALLOC_TEST(id);
14766  return id->pMethods->xCheckReservedLock(id, pResOut);
14767}
14768
14769/*
14770** Use sqlite3OsFileControl() when we are doing something that might fail
14771** and we need to know about the failures.  Use sqlite3OsFileControlHint()
14772** when simply tossing information over the wall to the VFS and we do not
14773** really care if the VFS receives and understands the information since it
14774** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
14775** routine has no return value since the return value would be meaningless.
14776*/
14777SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
14778  DO_OS_MALLOC_TEST(id);
14779  return id->pMethods->xFileControl(id, op, pArg);
14780}
14781SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
14782  (void)id->pMethods->xFileControl(id, op, pArg);
14783}
14784
14785SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
14786  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
14787  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
14788}
14789SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
14790  return id->pMethods->xDeviceCharacteristics(id);
14791}
14792SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
14793  return id->pMethods->xShmLock(id, offset, n, flags);
14794}
14795SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
14796  id->pMethods->xShmBarrier(id);
14797}
14798SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
14799  return id->pMethods->xShmUnmap(id, deleteFlag);
14800}
14801SQLITE_PRIVATE int sqlite3OsShmMap(
14802  sqlite3_file *id,               /* Database file handle */
14803  int iPage,
14804  int pgsz,
14805  int bExtend,                    /* True to extend file if necessary */
14806  void volatile **pp              /* OUT: Pointer to mapping */
14807){
14808  DO_OS_MALLOC_TEST(id);
14809  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
14810}
14811
14812/*
14813** The next group of routines are convenience wrappers around the
14814** VFS methods.
14815*/
14816SQLITE_PRIVATE int sqlite3OsOpen(
14817  sqlite3_vfs *pVfs,
14818  const char *zPath,
14819  sqlite3_file *pFile,
14820  int flags,
14821  int *pFlagsOut
14822){
14823  int rc;
14824  DO_OS_MALLOC_TEST(0);
14825  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
14826  ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
14827  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
14828  ** reaching the VFS. */
14829  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
14830  assert( rc==SQLITE_OK || pFile->pMethods==0 );
14831  return rc;
14832}
14833SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
14834  DO_OS_MALLOC_TEST(0);
14835  assert( dirSync==0 || dirSync==1 );
14836  return pVfs->xDelete(pVfs, zPath, dirSync);
14837}
14838SQLITE_PRIVATE int sqlite3OsAccess(
14839  sqlite3_vfs *pVfs,
14840  const char *zPath,
14841  int flags,
14842  int *pResOut
14843){
14844  DO_OS_MALLOC_TEST(0);
14845  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
14846}
14847SQLITE_PRIVATE int sqlite3OsFullPathname(
14848  sqlite3_vfs *pVfs,
14849  const char *zPath,
14850  int nPathOut,
14851  char *zPathOut
14852){
14853  DO_OS_MALLOC_TEST(0);
14854  zPathOut[0] = 0;
14855  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
14856}
14857#ifndef SQLITE_OMIT_LOAD_EXTENSION
14858SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
14859  return pVfs->xDlOpen(pVfs, zPath);
14860}
14861SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14862  pVfs->xDlError(pVfs, nByte, zBufOut);
14863}
14864SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
14865  return pVfs->xDlSym(pVfs, pHdle, zSym);
14866}
14867SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
14868  pVfs->xDlClose(pVfs, pHandle);
14869}
14870#endif /* SQLITE_OMIT_LOAD_EXTENSION */
14871SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
14872  return pVfs->xRandomness(pVfs, nByte, zBufOut);
14873}
14874SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
14875  return pVfs->xSleep(pVfs, nMicro);
14876}
14877SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
14878  int rc;
14879  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
14880  ** method to get the current date and time if that method is available
14881  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
14882  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
14883  ** unavailable.
14884  */
14885  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
14886    rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
14887  }else{
14888    double r;
14889    rc = pVfs->xCurrentTime(pVfs, &r);
14890    *pTimeOut = (sqlite3_int64)(r*86400000.0);
14891  }
14892  return rc;
14893}
14894
14895SQLITE_PRIVATE int sqlite3OsOpenMalloc(
14896  sqlite3_vfs *pVfs,
14897  const char *zFile,
14898  sqlite3_file **ppFile,
14899  int flags,
14900  int *pOutFlags
14901){
14902  int rc = SQLITE_NOMEM;
14903  sqlite3_file *pFile;
14904  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
14905  if( pFile ){
14906    rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
14907    if( rc!=SQLITE_OK ){
14908      sqlite3_free(pFile);
14909    }else{
14910      *ppFile = pFile;
14911    }
14912  }
14913  return rc;
14914}
14915SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
14916  int rc = SQLITE_OK;
14917  assert( pFile );
14918  rc = sqlite3OsClose(pFile);
14919  sqlite3_free(pFile);
14920  return rc;
14921}
14922
14923/*
14924** This function is a wrapper around the OS specific implementation of
14925** sqlite3_os_init(). The purpose of the wrapper is to provide the
14926** ability to simulate a malloc failure, so that the handling of an
14927** error in sqlite3_os_init() by the upper layers can be tested.
14928*/
14929SQLITE_PRIVATE int sqlite3OsInit(void){
14930  void *p = sqlite3_malloc(10);
14931  if( p==0 ) return SQLITE_NOMEM;
14932  sqlite3_free(p);
14933  return sqlite3_os_init();
14934}
14935
14936/*
14937** The list of all registered VFS implementations.
14938*/
14939static sqlite3_vfs * SQLITE_WSD vfsList = 0;
14940#define vfsList GLOBAL(sqlite3_vfs *, vfsList)
14941
14942/*
14943** Locate a VFS by name.  If no name is given, simply return the
14944** first VFS on the list.
14945*/
14946SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
14947  sqlite3_vfs *pVfs = 0;
14948#if SQLITE_THREADSAFE
14949  sqlite3_mutex *mutex;
14950#endif
14951#ifndef SQLITE_OMIT_AUTOINIT
14952  int rc = sqlite3_initialize();
14953  if( rc ) return 0;
14954#endif
14955#if SQLITE_THREADSAFE
14956  mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14957#endif
14958  sqlite3_mutex_enter(mutex);
14959  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
14960    if( zVfs==0 ) break;
14961    if( strcmp(zVfs, pVfs->zName)==0 ) break;
14962  }
14963  sqlite3_mutex_leave(mutex);
14964  return pVfs;
14965}
14966
14967/*
14968** Unlink a VFS from the linked list
14969*/
14970static void vfsUnlink(sqlite3_vfs *pVfs){
14971  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
14972  if( pVfs==0 ){
14973    /* No-op */
14974  }else if( vfsList==pVfs ){
14975    vfsList = pVfs->pNext;
14976  }else if( vfsList ){
14977    sqlite3_vfs *p = vfsList;
14978    while( p->pNext && p->pNext!=pVfs ){
14979      p = p->pNext;
14980    }
14981    if( p->pNext==pVfs ){
14982      p->pNext = pVfs->pNext;
14983    }
14984  }
14985}
14986
14987/*
14988** Register a VFS with the system.  It is harmless to register the same
14989** VFS multiple times.  The new VFS becomes the default if makeDflt is
14990** true.
14991*/
14992SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
14993  MUTEX_LOGIC(sqlite3_mutex *mutex;)
14994#ifndef SQLITE_OMIT_AUTOINIT
14995  int rc = sqlite3_initialize();
14996  if( rc ) return rc;
14997#endif
14998  MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
14999  sqlite3_mutex_enter(mutex);
15000  vfsUnlink(pVfs);
15001  if( makeDflt || vfsList==0 ){
15002    pVfs->pNext = vfsList;
15003    vfsList = pVfs;
15004  }else{
15005    pVfs->pNext = vfsList->pNext;
15006    vfsList->pNext = pVfs;
15007  }
15008  assert(vfsList);
15009  sqlite3_mutex_leave(mutex);
15010  return SQLITE_OK;
15011}
15012
15013/*
15014** Unregister a VFS so that it is no longer accessible.
15015*/
15016SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15017#if SQLITE_THREADSAFE
15018  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15019#endif
15020  sqlite3_mutex_enter(mutex);
15021  vfsUnlink(pVfs);
15022  sqlite3_mutex_leave(mutex);
15023  return SQLITE_OK;
15024}
15025
15026/************** End of os.c **************************************************/
15027/************** Begin file fault.c *******************************************/
15028/*
15029** 2008 Jan 22
15030**
15031** The author disclaims copyright to this source code.  In place of
15032** a legal notice, here is a blessing:
15033**
15034**    May you do good and not evil.
15035**    May you find forgiveness for yourself and forgive others.
15036**    May you share freely, never taking more than you give.
15037**
15038*************************************************************************
15039**
15040** This file contains code to support the concept of "benign"
15041** malloc failures (when the xMalloc() or xRealloc() method of the
15042** sqlite3_mem_methods structure fails to allocate a block of memory
15043** and returns 0).
15044**
15045** Most malloc failures are non-benign. After they occur, SQLite
15046** abandons the current operation and returns an error code (usually
15047** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15048** fatal. For example, if a malloc fails while resizing a hash table, this
15049** is completely recoverable simply by not carrying out the resize. The
15050** hash table will continue to function normally.  So a malloc failure
15051** during a hash table resize is a benign fault.
15052*/
15053
15054
15055#ifndef SQLITE_OMIT_BUILTIN_TEST
15056
15057/*
15058** Global variables.
15059*/
15060typedef struct BenignMallocHooks BenignMallocHooks;
15061static SQLITE_WSD struct BenignMallocHooks {
15062  void (*xBenignBegin)(void);
15063  void (*xBenignEnd)(void);
15064} sqlite3Hooks = { 0, 0 };
15065
15066/* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15067** structure.  If writable static data is unsupported on the target,
15068** we have to locate the state vector at run-time.  In the more common
15069** case where writable static data is supported, wsdHooks can refer directly
15070** to the "sqlite3Hooks" state vector declared above.
15071*/
15072#ifdef SQLITE_OMIT_WSD
15073# define wsdHooksInit \
15074  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15075# define wsdHooks x[0]
15076#else
15077# define wsdHooksInit
15078# define wsdHooks sqlite3Hooks
15079#endif
15080
15081
15082/*
15083** Register hooks to call when sqlite3BeginBenignMalloc() and
15084** sqlite3EndBenignMalloc() are called, respectively.
15085*/
15086SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15087  void (*xBenignBegin)(void),
15088  void (*xBenignEnd)(void)
15089){
15090  wsdHooksInit;
15091  wsdHooks.xBenignBegin = xBenignBegin;
15092  wsdHooks.xBenignEnd = xBenignEnd;
15093}
15094
15095/*
15096** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15097** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15098** indicates that subsequent malloc failures are non-benign.
15099*/
15100SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15101  wsdHooksInit;
15102  if( wsdHooks.xBenignBegin ){
15103    wsdHooks.xBenignBegin();
15104  }
15105}
15106SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15107  wsdHooksInit;
15108  if( wsdHooks.xBenignEnd ){
15109    wsdHooks.xBenignEnd();
15110  }
15111}
15112
15113#endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15114
15115/************** End of fault.c ***********************************************/
15116/************** Begin file mem0.c ********************************************/
15117/*
15118** 2008 October 28
15119**
15120** The author disclaims copyright to this source code.  In place of
15121** a legal notice, here is a blessing:
15122**
15123**    May you do good and not evil.
15124**    May you find forgiveness for yourself and forgive others.
15125**    May you share freely, never taking more than you give.
15126**
15127*************************************************************************
15128**
15129** This file contains a no-op memory allocation drivers for use when
15130** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15131** here always fail.  SQLite will not operate with these drivers.  These
15132** are merely placeholders.  Real drivers must be substituted using
15133** sqlite3_config() before SQLite will operate.
15134*/
15135
15136/*
15137** This version of the memory allocator is the default.  It is
15138** used when no other memory allocator is specified using compile-time
15139** macros.
15140*/
15141#ifdef SQLITE_ZERO_MALLOC
15142
15143/*
15144** No-op versions of all memory allocation routines
15145*/
15146static void *sqlite3MemMalloc(int nByte){ return 0; }
15147static void sqlite3MemFree(void *pPrior){ return; }
15148static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15149static int sqlite3MemSize(void *pPrior){ return 0; }
15150static int sqlite3MemRoundup(int n){ return n; }
15151static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15152static void sqlite3MemShutdown(void *NotUsed){ return; }
15153
15154/*
15155** This routine is the only routine in this file with external linkage.
15156**
15157** Populate the low-level memory allocation function pointers in
15158** sqlite3GlobalConfig.m with pointers to the routines in this file.
15159*/
15160SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15161  static const sqlite3_mem_methods defaultMethods = {
15162     sqlite3MemMalloc,
15163     sqlite3MemFree,
15164     sqlite3MemRealloc,
15165     sqlite3MemSize,
15166     sqlite3MemRoundup,
15167     sqlite3MemInit,
15168     sqlite3MemShutdown,
15169     0
15170  };
15171  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15172}
15173
15174#endif /* SQLITE_ZERO_MALLOC */
15175
15176/************** End of mem0.c ************************************************/
15177/************** Begin file mem1.c ********************************************/
15178/*
15179** 2007 August 14
15180**
15181** The author disclaims copyright to this source code.  In place of
15182** a legal notice, here is a blessing:
15183**
15184**    May you do good and not evil.
15185**    May you find forgiveness for yourself and forgive others.
15186**    May you share freely, never taking more than you give.
15187**
15188*************************************************************************
15189**
15190** This file contains low-level memory allocation drivers for when
15191** SQLite will use the standard C-library malloc/realloc/free interface
15192** to obtain the memory it needs.
15193**
15194** This file contains implementations of the low-level memory allocation
15195** routines specified in the sqlite3_mem_methods object.  The content of
15196** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15197** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15198** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15199** default configuration is to use memory allocation routines in this
15200** file.
15201**
15202** C-preprocessor macro summary:
15203**
15204**    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15205**                                the malloc_usable_size() interface exists
15206**                                on the target platform.  Or, this symbol
15207**                                can be set manually, if desired.
15208**                                If an equivalent interface exists by
15209**                                a different name, using a separate -D
15210**                                option to rename it.
15211**
15212**    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15213**                                memory allocator.  Set this symbol to enable
15214**                                building on older macs.
15215**
15216**    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15217**                                _msize() on windows systems.  This might
15218**                                be necessary when compiling for Delphi,
15219**                                for example.
15220*/
15221
15222/*
15223** This version of the memory allocator is the default.  It is
15224** used when no other memory allocator is specified using compile-time
15225** macros.
15226*/
15227#ifdef SQLITE_SYSTEM_MALLOC
15228
15229/*
15230** The MSVCRT has malloc_usable_size() but it is called _msize().
15231** The use of _msize() is automatic, but can be disabled by compiling
15232** with -DSQLITE_WITHOUT_MSIZE
15233*/
15234#if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15235# define SQLITE_MALLOCSIZE _msize
15236#endif
15237
15238#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15239
15240/*
15241** Use the zone allocator available on apple products unless the
15242** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15243*/
15244#include <sys/sysctl.h>
15245#include <malloc/malloc.h>
15246#include <libkern/OSAtomic.h>
15247static malloc_zone_t* _sqliteZone_;
15248#define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15249#define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15250#define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15251#define SQLITE_MALLOCSIZE(x) \
15252        (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15253
15254#else /* if not __APPLE__ */
15255
15256/*
15257** Use standard C library malloc and free on non-Apple systems.
15258** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15259*/
15260#define SQLITE_MALLOC(x)    malloc(x)
15261#define SQLITE_FREE(x)      free(x)
15262#define SQLITE_REALLOC(x,y) realloc((x),(y))
15263
15264#if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15265      || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15266# include <malloc.h>    /* Needed for malloc_usable_size on linux */
15267#endif
15268#ifdef HAVE_MALLOC_USABLE_SIZE
15269# ifndef SQLITE_MALLOCSIZE
15270#  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15271# endif
15272#else
15273# undef SQLITE_MALLOCSIZE
15274#endif
15275
15276#endif /* __APPLE__ or not __APPLE__ */
15277
15278/*
15279** Like malloc(), but remember the size of the allocation
15280** so that we can find it later using sqlite3MemSize().
15281**
15282** For this low-level routine, we are guaranteed that nByte>0 because
15283** cases of nByte<=0 will be intercepted and dealt with by higher level
15284** routines.
15285*/
15286static void *sqlite3MemMalloc(int nByte){
15287#ifdef SQLITE_MALLOCSIZE
15288  void *p = SQLITE_MALLOC( nByte );
15289  if( p==0 ){
15290    testcase( sqlite3GlobalConfig.xLog!=0 );
15291    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15292  }
15293  return p;
15294#else
15295  sqlite3_int64 *p;
15296  assert( nByte>0 );
15297  nByte = ROUND8(nByte);
15298  p = SQLITE_MALLOC( nByte+8 );
15299  if( p ){
15300    p[0] = nByte;
15301    p++;
15302  }else{
15303    testcase( sqlite3GlobalConfig.xLog!=0 );
15304    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15305  }
15306  return (void *)p;
15307#endif
15308}
15309
15310/*
15311** Like free() but works for allocations obtained from sqlite3MemMalloc()
15312** or sqlite3MemRealloc().
15313**
15314** For this low-level routine, we already know that pPrior!=0 since
15315** cases where pPrior==0 will have been intecepted and dealt with
15316** by higher-level routines.
15317*/
15318static void sqlite3MemFree(void *pPrior){
15319#ifdef SQLITE_MALLOCSIZE
15320  SQLITE_FREE(pPrior);
15321#else
15322  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15323  assert( pPrior!=0 );
15324  p--;
15325  SQLITE_FREE(p);
15326#endif
15327}
15328
15329/*
15330** Report the allocated size of a prior return from xMalloc()
15331** or xRealloc().
15332*/
15333static int sqlite3MemSize(void *pPrior){
15334#ifdef SQLITE_MALLOCSIZE
15335  return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15336#else
15337  sqlite3_int64 *p;
15338  if( pPrior==0 ) return 0;
15339  p = (sqlite3_int64*)pPrior;
15340  p--;
15341  return (int)p[0];
15342#endif
15343}
15344
15345/*
15346** Like realloc().  Resize an allocation previously obtained from
15347** sqlite3MemMalloc().
15348**
15349** For this low-level interface, we know that pPrior!=0.  Cases where
15350** pPrior==0 while have been intercepted by higher-level routine and
15351** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
15352** cases where nByte<=0 will have been intercepted by higher-level
15353** routines and redirected to xFree.
15354*/
15355static void *sqlite3MemRealloc(void *pPrior, int nByte){
15356#ifdef SQLITE_MALLOCSIZE
15357  void *p = SQLITE_REALLOC(pPrior, nByte);
15358  if( p==0 ){
15359    testcase( sqlite3GlobalConfig.xLog!=0 );
15360    sqlite3_log(SQLITE_NOMEM,
15361      "failed memory resize %u to %u bytes",
15362      SQLITE_MALLOCSIZE(pPrior), nByte);
15363  }
15364  return p;
15365#else
15366  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15367  assert( pPrior!=0 && nByte>0 );
15368  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15369  p--;
15370  p = SQLITE_REALLOC(p, nByte+8 );
15371  if( p ){
15372    p[0] = nByte;
15373    p++;
15374  }else{
15375    testcase( sqlite3GlobalConfig.xLog!=0 );
15376    sqlite3_log(SQLITE_NOMEM,
15377      "failed memory resize %u to %u bytes",
15378      sqlite3MemSize(pPrior), nByte);
15379  }
15380  return (void*)p;
15381#endif
15382}
15383
15384/*
15385** Round up a request size to the next valid allocation size.
15386*/
15387static int sqlite3MemRoundup(int n){
15388  return ROUND8(n);
15389}
15390
15391/*
15392** Initialize this module.
15393*/
15394static int sqlite3MemInit(void *NotUsed){
15395#if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15396  int cpuCount;
15397  size_t len;
15398  if( _sqliteZone_ ){
15399    return SQLITE_OK;
15400  }
15401  len = sizeof(cpuCount);
15402  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15403  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15404  if( cpuCount>1 ){
15405    /* defer MT decisions to system malloc */
15406    _sqliteZone_ = malloc_default_zone();
15407  }else{
15408    /* only 1 core, use our own zone to contention over global locks,
15409    ** e.g. we have our own dedicated locks */
15410    bool success;
15411    malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15412    malloc_set_zone_name(newzone, "Sqlite_Heap");
15413    do{
15414      success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
15415                                 (void * volatile *)&_sqliteZone_);
15416    }while(!_sqliteZone_);
15417    if( !success ){
15418      /* somebody registered a zone first */
15419      malloc_destroy_zone(newzone);
15420    }
15421  }
15422#endif
15423  UNUSED_PARAMETER(NotUsed);
15424  return SQLITE_OK;
15425}
15426
15427/*
15428** Deinitialize this module.
15429*/
15430static void sqlite3MemShutdown(void *NotUsed){
15431  UNUSED_PARAMETER(NotUsed);
15432  return;
15433}
15434
15435/*
15436** This routine is the only routine in this file with external linkage.
15437**
15438** Populate the low-level memory allocation function pointers in
15439** sqlite3GlobalConfig.m with pointers to the routines in this file.
15440*/
15441SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15442  static const sqlite3_mem_methods defaultMethods = {
15443     sqlite3MemMalloc,
15444     sqlite3MemFree,
15445     sqlite3MemRealloc,
15446     sqlite3MemSize,
15447     sqlite3MemRoundup,
15448     sqlite3MemInit,
15449     sqlite3MemShutdown,
15450     0
15451  };
15452  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15453}
15454
15455#endif /* SQLITE_SYSTEM_MALLOC */
15456
15457/************** End of mem1.c ************************************************/
15458/************** Begin file mem2.c ********************************************/
15459/*
15460** 2007 August 15
15461**
15462** The author disclaims copyright to this source code.  In place of
15463** a legal notice, here is a blessing:
15464**
15465**    May you do good and not evil.
15466**    May you find forgiveness for yourself and forgive others.
15467**    May you share freely, never taking more than you give.
15468**
15469*************************************************************************
15470**
15471** This file contains low-level memory allocation drivers for when
15472** SQLite will use the standard C-library malloc/realloc/free interface
15473** to obtain the memory it needs while adding lots of additional debugging
15474** information to each allocation in order to help detect and fix memory
15475** leaks and memory usage errors.
15476**
15477** This file contains implementations of the low-level memory allocation
15478** routines specified in the sqlite3_mem_methods object.
15479*/
15480
15481/*
15482** This version of the memory allocator is used only if the
15483** SQLITE_MEMDEBUG macro is defined
15484*/
15485#ifdef SQLITE_MEMDEBUG
15486
15487/*
15488** The backtrace functionality is only available with GLIBC
15489*/
15490#ifdef __GLIBC__
15491  extern int backtrace(void**,int);
15492  extern void backtrace_symbols_fd(void*const*,int,int);
15493#else
15494# define backtrace(A,B) 1
15495# define backtrace_symbols_fd(A,B,C)
15496#endif
15497/* #include <stdio.h> */
15498
15499/*
15500** Each memory allocation looks like this:
15501**
15502**  ------------------------------------------------------------------------
15503**  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15504**  ------------------------------------------------------------------------
15505**
15506** The application code sees only a pointer to the allocation.  We have
15507** to back up from the allocation pointer to find the MemBlockHdr.  The
15508** MemBlockHdr tells us the size of the allocation and the number of
15509** backtrace pointers.  There is also a guard word at the end of the
15510** MemBlockHdr.
15511*/
15512struct MemBlockHdr {
15513  i64 iSize;                          /* Size of this allocation */
15514  struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15515  char nBacktrace;                    /* Number of backtraces on this alloc */
15516  char nBacktraceSlots;               /* Available backtrace slots */
15517  u8 nTitle;                          /* Bytes of title; includes '\0' */
15518  u8 eType;                           /* Allocation type code */
15519  int iForeGuard;                     /* Guard word for sanity */
15520};
15521
15522/*
15523** Guard words
15524*/
15525#define FOREGUARD 0x80F5E153
15526#define REARGUARD 0xE4676B53
15527
15528/*
15529** Number of malloc size increments to track.
15530*/
15531#define NCSIZE  1000
15532
15533/*
15534** All of the static variables used by this module are collected
15535** into a single structure named "mem".  This is to keep the
15536** static variables organized and to reduce namespace pollution
15537** when this module is combined with other in the amalgamation.
15538*/
15539static struct {
15540
15541  /*
15542  ** Mutex to control access to the memory allocation subsystem.
15543  */
15544  sqlite3_mutex *mutex;
15545
15546  /*
15547  ** Head and tail of a linked list of all outstanding allocations
15548  */
15549  struct MemBlockHdr *pFirst;
15550  struct MemBlockHdr *pLast;
15551
15552  /*
15553  ** The number of levels of backtrace to save in new allocations.
15554  */
15555  int nBacktrace;
15556  void (*xBacktrace)(int, int, void **);
15557
15558  /*
15559  ** Title text to insert in front of each block
15560  */
15561  int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
15562  char zTitle[100];  /* The title text */
15563
15564  /*
15565  ** sqlite3MallocDisallow() increments the following counter.
15566  ** sqlite3MallocAllow() decrements it.
15567  */
15568  int disallow; /* Do not allow memory allocation */
15569
15570  /*
15571  ** Gather statistics on the sizes of memory allocations.
15572  ** nAlloc[i] is the number of allocation attempts of i*8
15573  ** bytes.  i==NCSIZE is the number of allocation attempts for
15574  ** sizes more than NCSIZE*8 bytes.
15575  */
15576  int nAlloc[NCSIZE];      /* Total number of allocations */
15577  int nCurrent[NCSIZE];    /* Current number of allocations */
15578  int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
15579
15580} mem;
15581
15582
15583/*
15584** Adjust memory usage statistics
15585*/
15586static void adjustStats(int iSize, int increment){
15587  int i = ROUND8(iSize)/8;
15588  if( i>NCSIZE-1 ){
15589    i = NCSIZE - 1;
15590  }
15591  if( increment>0 ){
15592    mem.nAlloc[i]++;
15593    mem.nCurrent[i]++;
15594    if( mem.nCurrent[i]>mem.mxCurrent[i] ){
15595      mem.mxCurrent[i] = mem.nCurrent[i];
15596    }
15597  }else{
15598    mem.nCurrent[i]--;
15599    assert( mem.nCurrent[i]>=0 );
15600  }
15601}
15602
15603/*
15604** Given an allocation, find the MemBlockHdr for that allocation.
15605**
15606** This routine checks the guards at either end of the allocation and
15607** if they are incorrect it asserts.
15608*/
15609static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
15610  struct MemBlockHdr *p;
15611  int *pInt;
15612  u8 *pU8;
15613  int nReserve;
15614
15615  p = (struct MemBlockHdr*)pAllocation;
15616  p--;
15617  assert( p->iForeGuard==(int)FOREGUARD );
15618  nReserve = ROUND8(p->iSize);
15619  pInt = (int*)pAllocation;
15620  pU8 = (u8*)pAllocation;
15621  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
15622  /* This checks any of the "extra" bytes allocated due
15623  ** to rounding up to an 8 byte boundary to ensure
15624  ** they haven't been overwritten.
15625  */
15626  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
15627  return p;
15628}
15629
15630/*
15631** Return the number of bytes currently allocated at address p.
15632*/
15633static int sqlite3MemSize(void *p){
15634  struct MemBlockHdr *pHdr;
15635  if( !p ){
15636    return 0;
15637  }
15638  pHdr = sqlite3MemsysGetHeader(p);
15639  return pHdr->iSize;
15640}
15641
15642/*
15643** Initialize the memory allocation subsystem.
15644*/
15645static int sqlite3MemInit(void *NotUsed){
15646  UNUSED_PARAMETER(NotUsed);
15647  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
15648  if( !sqlite3GlobalConfig.bMemstat ){
15649    /* If memory status is enabled, then the malloc.c wrapper will already
15650    ** hold the STATIC_MEM mutex when the routines here are invoked. */
15651    mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
15652  }
15653  return SQLITE_OK;
15654}
15655
15656/*
15657** Deinitialize the memory allocation subsystem.
15658*/
15659static void sqlite3MemShutdown(void *NotUsed){
15660  UNUSED_PARAMETER(NotUsed);
15661  mem.mutex = 0;
15662}
15663
15664/*
15665** Round up a request size to the next valid allocation size.
15666*/
15667static int sqlite3MemRoundup(int n){
15668  return ROUND8(n);
15669}
15670
15671/*
15672** Fill a buffer with pseudo-random bytes.  This is used to preset
15673** the content of a new memory allocation to unpredictable values and
15674** to clear the content of a freed allocation to unpredictable values.
15675*/
15676static void randomFill(char *pBuf, int nByte){
15677  unsigned int x, y, r;
15678  x = SQLITE_PTR_TO_INT(pBuf);
15679  y = nByte | 1;
15680  while( nByte >= 4 ){
15681    x = (x>>1) ^ (-(x&1) & 0xd0000001);
15682    y = y*1103515245 + 12345;
15683    r = x ^ y;
15684    *(int*)pBuf = r;
15685    pBuf += 4;
15686    nByte -= 4;
15687  }
15688  while( nByte-- > 0 ){
15689    x = (x>>1) ^ (-(x&1) & 0xd0000001);
15690    y = y*1103515245 + 12345;
15691    r = x ^ y;
15692    *(pBuf++) = r & 0xff;
15693  }
15694}
15695
15696/*
15697** Allocate nByte bytes of memory.
15698*/
15699static void *sqlite3MemMalloc(int nByte){
15700  struct MemBlockHdr *pHdr;
15701  void **pBt;
15702  char *z;
15703  int *pInt;
15704  void *p = 0;
15705  int totalSize;
15706  int nReserve;
15707  sqlite3_mutex_enter(mem.mutex);
15708  assert( mem.disallow==0 );
15709  nReserve = ROUND8(nByte);
15710  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
15711               mem.nBacktrace*sizeof(void*) + mem.nTitle;
15712  p = malloc(totalSize);
15713  if( p ){
15714    z = p;
15715    pBt = (void**)&z[mem.nTitle];
15716    pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
15717    pHdr->pNext = 0;
15718    pHdr->pPrev = mem.pLast;
15719    if( mem.pLast ){
15720      mem.pLast->pNext = pHdr;
15721    }else{
15722      mem.pFirst = pHdr;
15723    }
15724    mem.pLast = pHdr;
15725    pHdr->iForeGuard = FOREGUARD;
15726    pHdr->eType = MEMTYPE_HEAP;
15727    pHdr->nBacktraceSlots = mem.nBacktrace;
15728    pHdr->nTitle = mem.nTitle;
15729    if( mem.nBacktrace ){
15730      void *aAddr[40];
15731      pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
15732      memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
15733      assert(pBt[0]);
15734      if( mem.xBacktrace ){
15735        mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
15736      }
15737    }else{
15738      pHdr->nBacktrace = 0;
15739    }
15740    if( mem.nTitle ){
15741      memcpy(z, mem.zTitle, mem.nTitle);
15742    }
15743    pHdr->iSize = nByte;
15744    adjustStats(nByte, +1);
15745    pInt = (int*)&pHdr[1];
15746    pInt[nReserve/sizeof(int)] = REARGUARD;
15747    randomFill((char*)pInt, nByte);
15748    memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
15749    p = (void*)pInt;
15750  }
15751  sqlite3_mutex_leave(mem.mutex);
15752  return p;
15753}
15754
15755/*
15756** Free memory.
15757*/
15758static void sqlite3MemFree(void *pPrior){
15759  struct MemBlockHdr *pHdr;
15760  void **pBt;
15761  char *z;
15762  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
15763       || mem.mutex!=0 );
15764  pHdr = sqlite3MemsysGetHeader(pPrior);
15765  pBt = (void**)pHdr;
15766  pBt -= pHdr->nBacktraceSlots;
15767  sqlite3_mutex_enter(mem.mutex);
15768  if( pHdr->pPrev ){
15769    assert( pHdr->pPrev->pNext==pHdr );
15770    pHdr->pPrev->pNext = pHdr->pNext;
15771  }else{
15772    assert( mem.pFirst==pHdr );
15773    mem.pFirst = pHdr->pNext;
15774  }
15775  if( pHdr->pNext ){
15776    assert( pHdr->pNext->pPrev==pHdr );
15777    pHdr->pNext->pPrev = pHdr->pPrev;
15778  }else{
15779    assert( mem.pLast==pHdr );
15780    mem.pLast = pHdr->pPrev;
15781  }
15782  z = (char*)pBt;
15783  z -= pHdr->nTitle;
15784  adjustStats(pHdr->iSize, -1);
15785  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
15786                pHdr->iSize + sizeof(int) + pHdr->nTitle);
15787  free(z);
15788  sqlite3_mutex_leave(mem.mutex);
15789}
15790
15791/*
15792** Change the size of an existing memory allocation.
15793**
15794** For this debugging implementation, we *always* make a copy of the
15795** allocation into a new place in memory.  In this way, if the
15796** higher level code is using pointer to the old allocation, it is
15797** much more likely to break and we are much more liking to find
15798** the error.
15799*/
15800static void *sqlite3MemRealloc(void *pPrior, int nByte){
15801  struct MemBlockHdr *pOldHdr;
15802  void *pNew;
15803  assert( mem.disallow==0 );
15804  assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
15805  pOldHdr = sqlite3MemsysGetHeader(pPrior);
15806  pNew = sqlite3MemMalloc(nByte);
15807  if( pNew ){
15808    memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
15809    if( nByte>pOldHdr->iSize ){
15810      randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
15811    }
15812    sqlite3MemFree(pPrior);
15813  }
15814  return pNew;
15815}
15816
15817/*
15818** Populate the low-level memory allocation function pointers in
15819** sqlite3GlobalConfig.m with pointers to the routines in this file.
15820*/
15821SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15822  static const sqlite3_mem_methods defaultMethods = {
15823     sqlite3MemMalloc,
15824     sqlite3MemFree,
15825     sqlite3MemRealloc,
15826     sqlite3MemSize,
15827     sqlite3MemRoundup,
15828     sqlite3MemInit,
15829     sqlite3MemShutdown,
15830     0
15831  };
15832  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15833}
15834
15835/*
15836** Set the "type" of an allocation.
15837*/
15838SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
15839  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15840    struct MemBlockHdr *pHdr;
15841    pHdr = sqlite3MemsysGetHeader(p);
15842    assert( pHdr->iForeGuard==FOREGUARD );
15843    pHdr->eType = eType;
15844  }
15845}
15846
15847/*
15848** Return TRUE if the mask of type in eType matches the type of the
15849** allocation p.  Also return true if p==NULL.
15850**
15851** This routine is designed for use within an assert() statement, to
15852** verify the type of an allocation.  For example:
15853**
15854**     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
15855*/
15856SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
15857  int rc = 1;
15858  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15859    struct MemBlockHdr *pHdr;
15860    pHdr = sqlite3MemsysGetHeader(p);
15861    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15862    if( (pHdr->eType&eType)==0 ){
15863      rc = 0;
15864    }
15865  }
15866  return rc;
15867}
15868
15869/*
15870** Return TRUE if the mask of type in eType matches no bits of the type of the
15871** allocation p.  Also return true if p==NULL.
15872**
15873** This routine is designed for use within an assert() statement, to
15874** verify the type of an allocation.  For example:
15875**
15876**     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
15877*/
15878SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
15879  int rc = 1;
15880  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
15881    struct MemBlockHdr *pHdr;
15882    pHdr = sqlite3MemsysGetHeader(p);
15883    assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
15884    if( (pHdr->eType&eType)!=0 ){
15885      rc = 0;
15886    }
15887  }
15888  return rc;
15889}
15890
15891/*
15892** Set the number of backtrace levels kept for each allocation.
15893** A value of zero turns off backtracing.  The number is always rounded
15894** up to a multiple of 2.
15895*/
15896SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
15897  if( depth<0 ){ depth = 0; }
15898  if( depth>20 ){ depth = 20; }
15899  depth = (depth+1)&0xfe;
15900  mem.nBacktrace = depth;
15901}
15902
15903SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
15904  mem.xBacktrace = xBacktrace;
15905}
15906
15907/*
15908** Set the title string for subsequent allocations.
15909*/
15910SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
15911  unsigned int n = sqlite3Strlen30(zTitle) + 1;
15912  sqlite3_mutex_enter(mem.mutex);
15913  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
15914  memcpy(mem.zTitle, zTitle, n);
15915  mem.zTitle[n] = 0;
15916  mem.nTitle = ROUND8(n);
15917  sqlite3_mutex_leave(mem.mutex);
15918}
15919
15920SQLITE_PRIVATE void sqlite3MemdebugSync(){
15921  struct MemBlockHdr *pHdr;
15922  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15923    void **pBt = (void**)pHdr;
15924    pBt -= pHdr->nBacktraceSlots;
15925    mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
15926  }
15927}
15928
15929/*
15930** Open the file indicated and write a log of all unfreed memory
15931** allocations into that log.
15932*/
15933SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
15934  FILE *out;
15935  struct MemBlockHdr *pHdr;
15936  void **pBt;
15937  int i;
15938  out = fopen(zFilename, "w");
15939  if( out==0 ){
15940    fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
15941                    zFilename);
15942    return;
15943  }
15944  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
15945    char *z = (char*)pHdr;
15946    z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
15947    fprintf(out, "**** %lld bytes at %p from %s ****\n",
15948            pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
15949    if( pHdr->nBacktrace ){
15950      fflush(out);
15951      pBt = (void**)pHdr;
15952      pBt -= pHdr->nBacktraceSlots;
15953      backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
15954      fprintf(out, "\n");
15955    }
15956  }
15957  fprintf(out, "COUNTS:\n");
15958  for(i=0; i<NCSIZE-1; i++){
15959    if( mem.nAlloc[i] ){
15960      fprintf(out, "   %5d: %10d %10d %10d\n",
15961            i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
15962    }
15963  }
15964  if( mem.nAlloc[NCSIZE-1] ){
15965    fprintf(out, "   %5d: %10d %10d %10d\n",
15966             NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
15967             mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
15968  }
15969  fclose(out);
15970}
15971
15972/*
15973** Return the number of times sqlite3MemMalloc() has been called.
15974*/
15975SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
15976  int i;
15977  int nTotal = 0;
15978  for(i=0; i<NCSIZE; i++){
15979    nTotal += mem.nAlloc[i];
15980  }
15981  return nTotal;
15982}
15983
15984
15985#endif /* SQLITE_MEMDEBUG */
15986
15987/************** End of mem2.c ************************************************/
15988/************** Begin file mem3.c ********************************************/
15989/*
15990** 2007 October 14
15991**
15992** The author disclaims copyright to this source code.  In place of
15993** a legal notice, here is a blessing:
15994**
15995**    May you do good and not evil.
15996**    May you find forgiveness for yourself and forgive others.
15997**    May you share freely, never taking more than you give.
15998**
15999*************************************************************************
16000** This file contains the C functions that implement a memory
16001** allocation subsystem for use by SQLite.
16002**
16003** This version of the memory allocation subsystem omits all
16004** use of malloc(). The SQLite user supplies a block of memory
16005** before calling sqlite3_initialize() from which allocations
16006** are made and returned by the xMalloc() and xRealloc()
16007** implementations. Once sqlite3_initialize() has been called,
16008** the amount of memory available to SQLite is fixed and cannot
16009** be changed.
16010**
16011** This version of the memory allocation subsystem is included
16012** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16013*/
16014
16015/*
16016** This version of the memory allocator is only built into the library
16017** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16018** mean that the library will use a memory-pool by default, just that
16019** it is available. The mempool allocator is activated by calling
16020** sqlite3_config().
16021*/
16022#ifdef SQLITE_ENABLE_MEMSYS3
16023
16024/*
16025** Maximum size (in Mem3Blocks) of a "small" chunk.
16026*/
16027#define MX_SMALL 10
16028
16029
16030/*
16031** Number of freelist hash slots
16032*/
16033#define N_HASH  61
16034
16035/*
16036** A memory allocation (also called a "chunk") consists of two or
16037** more blocks where each block is 8 bytes.  The first 8 bytes are
16038** a header that is not returned to the user.
16039**
16040** A chunk is two or more blocks that is either checked out or
16041** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16042** size of the allocation in blocks if the allocation is free.
16043** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16044** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16045** is true if the previous chunk is checked out and false if the
16046** previous chunk is free.  The u.hdr.prevSize field is the size of
16047** the previous chunk in blocks if the previous chunk is on the
16048** freelist. If the previous chunk is checked out, then
16049** u.hdr.prevSize can be part of the data for that chunk and should
16050** not be read or written.
16051**
16052** We often identify a chunk by its index in mem3.aPool[].  When
16053** this is done, the chunk index refers to the second block of
16054** the chunk.  In this way, the first chunk has an index of 1.
16055** A chunk index of 0 means "no such chunk" and is the equivalent
16056** of a NULL pointer.
16057**
16058** The second block of free chunks is of the form u.list.  The
16059** two fields form a double-linked list of chunks of related sizes.
16060** Pointers to the head of the list are stored in mem3.aiSmall[]
16061** for smaller chunks and mem3.aiHash[] for larger chunks.
16062**
16063** The second block of a chunk is user data if the chunk is checked
16064** out.  If a chunk is checked out, the user data may extend into
16065** the u.hdr.prevSize value of the following chunk.
16066*/
16067typedef struct Mem3Block Mem3Block;
16068struct Mem3Block {
16069  union {
16070    struct {
16071      u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16072      u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16073    } hdr;
16074    struct {
16075      u32 next;       /* Index in mem3.aPool[] of next free chunk */
16076      u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16077    } list;
16078  } u;
16079};
16080
16081/*
16082** All of the static variables used by this module are collected
16083** into a single structure named "mem3".  This is to keep the
16084** static variables organized and to reduce namespace pollution
16085** when this module is combined with other in the amalgamation.
16086*/
16087static SQLITE_WSD struct Mem3Global {
16088  /*
16089  ** Memory available for allocation. nPool is the size of the array
16090  ** (in Mem3Blocks) pointed to by aPool less 2.
16091  */
16092  u32 nPool;
16093  Mem3Block *aPool;
16094
16095  /*
16096  ** True if we are evaluating an out-of-memory callback.
16097  */
16098  int alarmBusy;
16099
16100  /*
16101  ** Mutex to control access to the memory allocation subsystem.
16102  */
16103  sqlite3_mutex *mutex;
16104
16105  /*
16106  ** The minimum amount of free space that we have seen.
16107  */
16108  u32 mnMaster;
16109
16110  /*
16111  ** iMaster is the index of the master chunk.  Most new allocations
16112  ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16113  ** of the current master.  iMaster is 0 if there is not master chunk.
16114  ** The master chunk is not in either the aiHash[] or aiSmall[].
16115  */
16116  u32 iMaster;
16117  u32 szMaster;
16118
16119  /*
16120  ** Array of lists of free blocks according to the block size
16121  ** for smaller chunks, or a hash on the block size for larger
16122  ** chunks.
16123  */
16124  u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16125  u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16126} mem3 = { 97535575 };
16127
16128#define mem3 GLOBAL(struct Mem3Global, mem3)
16129
16130/*
16131** Unlink the chunk at mem3.aPool[i] from list it is currently
16132** on.  *pRoot is the list that i is a member of.
16133*/
16134static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16135  u32 next = mem3.aPool[i].u.list.next;
16136  u32 prev = mem3.aPool[i].u.list.prev;
16137  assert( sqlite3_mutex_held(mem3.mutex) );
16138  if( prev==0 ){
16139    *pRoot = next;
16140  }else{
16141    mem3.aPool[prev].u.list.next = next;
16142  }
16143  if( next ){
16144    mem3.aPool[next].u.list.prev = prev;
16145  }
16146  mem3.aPool[i].u.list.next = 0;
16147  mem3.aPool[i].u.list.prev = 0;
16148}
16149
16150/*
16151** Unlink the chunk at index i from
16152** whatever list is currently a member of.
16153*/
16154static void memsys3Unlink(u32 i){
16155  u32 size, hash;
16156  assert( sqlite3_mutex_held(mem3.mutex) );
16157  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16158  assert( i>=1 );
16159  size = mem3.aPool[i-1].u.hdr.size4x/4;
16160  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16161  assert( size>=2 );
16162  if( size <= MX_SMALL ){
16163    memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16164  }else{
16165    hash = size % N_HASH;
16166    memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16167  }
16168}
16169
16170/*
16171** Link the chunk at mem3.aPool[i] so that is on the list rooted
16172** at *pRoot.
16173*/
16174static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16175  assert( sqlite3_mutex_held(mem3.mutex) );
16176  mem3.aPool[i].u.list.next = *pRoot;
16177  mem3.aPool[i].u.list.prev = 0;
16178  if( *pRoot ){
16179    mem3.aPool[*pRoot].u.list.prev = i;
16180  }
16181  *pRoot = i;
16182}
16183
16184/*
16185** Link the chunk at index i into either the appropriate
16186** small chunk list, or into the large chunk hash table.
16187*/
16188static void memsys3Link(u32 i){
16189  u32 size, hash;
16190  assert( sqlite3_mutex_held(mem3.mutex) );
16191  assert( i>=1 );
16192  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16193  size = mem3.aPool[i-1].u.hdr.size4x/4;
16194  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16195  assert( size>=2 );
16196  if( size <= MX_SMALL ){
16197    memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16198  }else{
16199    hash = size % N_HASH;
16200    memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16201  }
16202}
16203
16204/*
16205** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16206** will already be held (obtained by code in malloc.c) if
16207** sqlite3GlobalConfig.bMemStat is true.
16208*/
16209static void memsys3Enter(void){
16210  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16211    mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16212  }
16213  sqlite3_mutex_enter(mem3.mutex);
16214}
16215static void memsys3Leave(void){
16216  sqlite3_mutex_leave(mem3.mutex);
16217}
16218
16219/*
16220** Called when we are unable to satisfy an allocation of nBytes.
16221*/
16222static void memsys3OutOfMemory(int nByte){
16223  if( !mem3.alarmBusy ){
16224    mem3.alarmBusy = 1;
16225    assert( sqlite3_mutex_held(mem3.mutex) );
16226    sqlite3_mutex_leave(mem3.mutex);
16227    sqlite3_release_memory(nByte);
16228    sqlite3_mutex_enter(mem3.mutex);
16229    mem3.alarmBusy = 0;
16230  }
16231}
16232
16233
16234/*
16235** Chunk i is a free chunk that has been unlinked.  Adjust its
16236** size parameters for check-out and return a pointer to the
16237** user portion of the chunk.
16238*/
16239static void *memsys3Checkout(u32 i, u32 nBlock){
16240  u32 x;
16241  assert( sqlite3_mutex_held(mem3.mutex) );
16242  assert( i>=1 );
16243  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16244  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16245  x = mem3.aPool[i-1].u.hdr.size4x;
16246  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16247  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16248  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16249  return &mem3.aPool[i];
16250}
16251
16252/*
16253** Carve a piece off of the end of the mem3.iMaster free chunk.
16254** Return a pointer to the new allocation.  Or, if the master chunk
16255** is not large enough, return 0.
16256*/
16257static void *memsys3FromMaster(u32 nBlock){
16258  assert( sqlite3_mutex_held(mem3.mutex) );
16259  assert( mem3.szMaster>=nBlock );
16260  if( nBlock>=mem3.szMaster-1 ){
16261    /* Use the entire master */
16262    void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16263    mem3.iMaster = 0;
16264    mem3.szMaster = 0;
16265    mem3.mnMaster = 0;
16266    return p;
16267  }else{
16268    /* Split the master block.  Return the tail. */
16269    u32 newi, x;
16270    newi = mem3.iMaster + mem3.szMaster - nBlock;
16271    assert( newi > mem3.iMaster+1 );
16272    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16273    mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16274    mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16275    mem3.szMaster -= nBlock;
16276    mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16277    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16278    mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16279    if( mem3.szMaster < mem3.mnMaster ){
16280      mem3.mnMaster = mem3.szMaster;
16281    }
16282    return (void*)&mem3.aPool[newi];
16283  }
16284}
16285
16286/*
16287** *pRoot is the head of a list of free chunks of the same size
16288** or same size hash.  In other words, *pRoot is an entry in either
16289** mem3.aiSmall[] or mem3.aiHash[].
16290**
16291** This routine examines all entries on the given list and tries
16292** to coalesce each entries with adjacent free chunks.
16293**
16294** If it sees a chunk that is larger than mem3.iMaster, it replaces
16295** the current mem3.iMaster with the new larger chunk.  In order for
16296** this mem3.iMaster replacement to work, the master chunk must be
16297** linked into the hash tables.  That is not the normal state of
16298** affairs, of course.  The calling routine must link the master
16299** chunk before invoking this routine, then must unlink the (possibly
16300** changed) master chunk once this routine has finished.
16301*/
16302static void memsys3Merge(u32 *pRoot){
16303  u32 iNext, prev, size, i, x;
16304
16305  assert( sqlite3_mutex_held(mem3.mutex) );
16306  for(i=*pRoot; i>0; i=iNext){
16307    iNext = mem3.aPool[i].u.list.next;
16308    size = mem3.aPool[i-1].u.hdr.size4x;
16309    assert( (size&1)==0 );
16310    if( (size&2)==0 ){
16311      memsys3UnlinkFromList(i, pRoot);
16312      assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16313      prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16314      if( prev==iNext ){
16315        iNext = mem3.aPool[prev].u.list.next;
16316      }
16317      memsys3Unlink(prev);
16318      size = i + size/4 - prev;
16319      x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16320      mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16321      mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16322      memsys3Link(prev);
16323      i = prev;
16324    }else{
16325      size /= 4;
16326    }
16327    if( size>mem3.szMaster ){
16328      mem3.iMaster = i;
16329      mem3.szMaster = size;
16330    }
16331  }
16332}
16333
16334/*
16335** Return a block of memory of at least nBytes in size.
16336** Return NULL if unable.
16337**
16338** This function assumes that the necessary mutexes, if any, are
16339** already held by the caller. Hence "Unsafe".
16340*/
16341static void *memsys3MallocUnsafe(int nByte){
16342  u32 i;
16343  u32 nBlock;
16344  u32 toFree;
16345
16346  assert( sqlite3_mutex_held(mem3.mutex) );
16347  assert( sizeof(Mem3Block)==8 );
16348  if( nByte<=12 ){
16349    nBlock = 2;
16350  }else{
16351    nBlock = (nByte + 11)/8;
16352  }
16353  assert( nBlock>=2 );
16354
16355  /* STEP 1:
16356  ** Look for an entry of the correct size in either the small
16357  ** chunk table or in the large chunk hash table.  This is
16358  ** successful most of the time (about 9 times out of 10).
16359  */
16360  if( nBlock <= MX_SMALL ){
16361    i = mem3.aiSmall[nBlock-2];
16362    if( i>0 ){
16363      memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16364      return memsys3Checkout(i, nBlock);
16365    }
16366  }else{
16367    int hash = nBlock % N_HASH;
16368    for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16369      if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16370        memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16371        return memsys3Checkout(i, nBlock);
16372      }
16373    }
16374  }
16375
16376  /* STEP 2:
16377  ** Try to satisfy the allocation by carving a piece off of the end
16378  ** of the master chunk.  This step usually works if step 1 fails.
16379  */
16380  if( mem3.szMaster>=nBlock ){
16381    return memsys3FromMaster(nBlock);
16382  }
16383
16384
16385  /* STEP 3:
16386  ** Loop through the entire memory pool.  Coalesce adjacent free
16387  ** chunks.  Recompute the master chunk as the largest free chunk.
16388  ** Then try again to satisfy the allocation by carving a piece off
16389  ** of the end of the master chunk.  This step happens very
16390  ** rarely (we hope!)
16391  */
16392  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16393    memsys3OutOfMemory(toFree);
16394    if( mem3.iMaster ){
16395      memsys3Link(mem3.iMaster);
16396      mem3.iMaster = 0;
16397      mem3.szMaster = 0;
16398    }
16399    for(i=0; i<N_HASH; i++){
16400      memsys3Merge(&mem3.aiHash[i]);
16401    }
16402    for(i=0; i<MX_SMALL-1; i++){
16403      memsys3Merge(&mem3.aiSmall[i]);
16404    }
16405    if( mem3.szMaster ){
16406      memsys3Unlink(mem3.iMaster);
16407      if( mem3.szMaster>=nBlock ){
16408        return memsys3FromMaster(nBlock);
16409      }
16410    }
16411  }
16412
16413  /* If none of the above worked, then we fail. */
16414  return 0;
16415}
16416
16417/*
16418** Free an outstanding memory allocation.
16419**
16420** This function assumes that the necessary mutexes, if any, are
16421** already held by the caller. Hence "Unsafe".
16422*/
16423static void memsys3FreeUnsafe(void *pOld){
16424  Mem3Block *p = (Mem3Block*)pOld;
16425  int i;
16426  u32 size, x;
16427  assert( sqlite3_mutex_held(mem3.mutex) );
16428  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16429  i = p - mem3.aPool;
16430  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16431  size = mem3.aPool[i-1].u.hdr.size4x/4;
16432  assert( i+size<=mem3.nPool+1 );
16433  mem3.aPool[i-1].u.hdr.size4x &= ~1;
16434  mem3.aPool[i+size-1].u.hdr.prevSize = size;
16435  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16436  memsys3Link(i);
16437
16438  /* Try to expand the master using the newly freed chunk */
16439  if( mem3.iMaster ){
16440    while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16441      size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16442      mem3.iMaster -= size;
16443      mem3.szMaster += size;
16444      memsys3Unlink(mem3.iMaster);
16445      x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16446      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16447      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16448    }
16449    x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16450    while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16451      memsys3Unlink(mem3.iMaster+mem3.szMaster);
16452      mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16453      mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16454      mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16455    }
16456  }
16457}
16458
16459/*
16460** Return the size of an outstanding allocation, in bytes.  The
16461** size returned omits the 8-byte header overhead.  This only
16462** works for chunks that are currently checked out.
16463*/
16464static int memsys3Size(void *p){
16465  Mem3Block *pBlock;
16466  if( p==0 ) return 0;
16467  pBlock = (Mem3Block*)p;
16468  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16469  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16470}
16471
16472/*
16473** Round up a request size to the next valid allocation size.
16474*/
16475static int memsys3Roundup(int n){
16476  if( n<=12 ){
16477    return 12;
16478  }else{
16479    return ((n+11)&~7) - 4;
16480  }
16481}
16482
16483/*
16484** Allocate nBytes of memory.
16485*/
16486static void *memsys3Malloc(int nBytes){
16487  sqlite3_int64 *p;
16488  assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
16489  memsys3Enter();
16490  p = memsys3MallocUnsafe(nBytes);
16491  memsys3Leave();
16492  return (void*)p;
16493}
16494
16495/*
16496** Free memory.
16497*/
16498static void memsys3Free(void *pPrior){
16499  assert( pPrior );
16500  memsys3Enter();
16501  memsys3FreeUnsafe(pPrior);
16502  memsys3Leave();
16503}
16504
16505/*
16506** Change the size of an existing memory allocation
16507*/
16508static void *memsys3Realloc(void *pPrior, int nBytes){
16509  int nOld;
16510  void *p;
16511  if( pPrior==0 ){
16512    return sqlite3_malloc(nBytes);
16513  }
16514  if( nBytes<=0 ){
16515    sqlite3_free(pPrior);
16516    return 0;
16517  }
16518  nOld = memsys3Size(pPrior);
16519  if( nBytes<=nOld && nBytes>=nOld-128 ){
16520    return pPrior;
16521  }
16522  memsys3Enter();
16523  p = memsys3MallocUnsafe(nBytes);
16524  if( p ){
16525    if( nOld<nBytes ){
16526      memcpy(p, pPrior, nOld);
16527    }else{
16528      memcpy(p, pPrior, nBytes);
16529    }
16530    memsys3FreeUnsafe(pPrior);
16531  }
16532  memsys3Leave();
16533  return p;
16534}
16535
16536/*
16537** Initialize this module.
16538*/
16539static int memsys3Init(void *NotUsed){
16540  UNUSED_PARAMETER(NotUsed);
16541  if( !sqlite3GlobalConfig.pHeap ){
16542    return SQLITE_ERROR;
16543  }
16544
16545  /* Store a pointer to the memory block in global structure mem3. */
16546  assert( sizeof(Mem3Block)==8 );
16547  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16548  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16549
16550  /* Initialize the master block. */
16551  mem3.szMaster = mem3.nPool;
16552  mem3.mnMaster = mem3.szMaster;
16553  mem3.iMaster = 1;
16554  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
16555  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
16556  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
16557
16558  return SQLITE_OK;
16559}
16560
16561/*
16562** Deinitialize this module.
16563*/
16564static void memsys3Shutdown(void *NotUsed){
16565  UNUSED_PARAMETER(NotUsed);
16566  mem3.mutex = 0;
16567  return;
16568}
16569
16570
16571
16572/*
16573** Open the file indicated and write a log of all unfreed memory
16574** allocations into that log.
16575*/
16576SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
16577#ifdef SQLITE_DEBUG
16578  FILE *out;
16579  u32 i, j;
16580  u32 size;
16581  if( zFilename==0 || zFilename[0]==0 ){
16582    out = stdout;
16583  }else{
16584    out = fopen(zFilename, "w");
16585    if( out==0 ){
16586      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16587                      zFilename);
16588      return;
16589    }
16590  }
16591  memsys3Enter();
16592  fprintf(out, "CHUNKS:\n");
16593  for(i=1; i<=mem3.nPool; i+=size/4){
16594    size = mem3.aPool[i-1].u.hdr.size4x;
16595    if( size/4<=1 ){
16596      fprintf(out, "%p size error\n", &mem3.aPool[i]);
16597      assert( 0 );
16598      break;
16599    }
16600    if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
16601      fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
16602      assert( 0 );
16603      break;
16604    }
16605    if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
16606      fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
16607      assert( 0 );
16608      break;
16609    }
16610    if( size&1 ){
16611      fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
16612    }else{
16613      fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
16614                  i==mem3.iMaster ? " **master**" : "");
16615    }
16616  }
16617  for(i=0; i<MX_SMALL-1; i++){
16618    if( mem3.aiSmall[i]==0 ) continue;
16619    fprintf(out, "small(%2d):", i);
16620    for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
16621      fprintf(out, " %p(%d)", &mem3.aPool[j],
16622              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16623    }
16624    fprintf(out, "\n");
16625  }
16626  for(i=0; i<N_HASH; i++){
16627    if( mem3.aiHash[i]==0 ) continue;
16628    fprintf(out, "hash(%2d):", i);
16629    for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
16630      fprintf(out, " %p(%d)", &mem3.aPool[j],
16631              (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
16632    }
16633    fprintf(out, "\n");
16634  }
16635  fprintf(out, "master=%d\n", mem3.iMaster);
16636  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
16637  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
16638  sqlite3_mutex_leave(mem3.mutex);
16639  if( out==stdout ){
16640    fflush(stdout);
16641  }else{
16642    fclose(out);
16643  }
16644#else
16645  UNUSED_PARAMETER(zFilename);
16646#endif
16647}
16648
16649/*
16650** This routine is the only routine in this file with external
16651** linkage.
16652**
16653** Populate the low-level memory allocation function pointers in
16654** sqlite3GlobalConfig.m with pointers to the routines in this file. The
16655** arguments specify the block of memory to manage.
16656**
16657** This routine is only called by sqlite3_config(), and therefore
16658** is not required to be threadsafe (it is not).
16659*/
16660SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
16661  static const sqlite3_mem_methods mempoolMethods = {
16662     memsys3Malloc,
16663     memsys3Free,
16664     memsys3Realloc,
16665     memsys3Size,
16666     memsys3Roundup,
16667     memsys3Init,
16668     memsys3Shutdown,
16669     0
16670  };
16671  return &mempoolMethods;
16672}
16673
16674#endif /* SQLITE_ENABLE_MEMSYS3 */
16675
16676/************** End of mem3.c ************************************************/
16677/************** Begin file mem5.c ********************************************/
16678/*
16679** 2007 October 14
16680**
16681** The author disclaims copyright to this source code.  In place of
16682** a legal notice, here is a blessing:
16683**
16684**    May you do good and not evil.
16685**    May you find forgiveness for yourself and forgive others.
16686**    May you share freely, never taking more than you give.
16687**
16688*************************************************************************
16689** This file contains the C functions that implement a memory
16690** allocation subsystem for use by SQLite.
16691**
16692** This version of the memory allocation subsystem omits all
16693** use of malloc(). The application gives SQLite a block of memory
16694** before calling sqlite3_initialize() from which allocations
16695** are made and returned by the xMalloc() and xRealloc()
16696** implementations. Once sqlite3_initialize() has been called,
16697** the amount of memory available to SQLite is fixed and cannot
16698** be changed.
16699**
16700** This version of the memory allocation subsystem is included
16701** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
16702**
16703** This memory allocator uses the following algorithm:
16704**
16705**   1.  All memory allocations sizes are rounded up to a power of 2.
16706**
16707**   2.  If two adjacent free blocks are the halves of a larger block,
16708**       then the two blocks are coalesed into the single larger block.
16709**
16710**   3.  New memory is allocated from the first available free block.
16711**
16712** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
16713** Concerning Dynamic Storage Allocation". Journal of the Association for
16714** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
16715**
16716** Let n be the size of the largest allocation divided by the minimum
16717** allocation size (after rounding all sizes up to a power of 2.)  Let M
16718** be the maximum amount of memory ever outstanding at one time.  Let
16719** N be the total amount of memory available for allocation.  Robson
16720** proved that this memory allocator will never breakdown due to
16721** fragmentation as long as the following constraint holds:
16722**
16723**      N >=  M*(1 + log2(n)/2) - n + 1
16724**
16725** The sqlite3_status() logic tracks the maximum values of n and M so
16726** that an application can, at any time, verify this constraint.
16727*/
16728
16729/*
16730** This version of the memory allocator is used only when
16731** SQLITE_ENABLE_MEMSYS5 is defined.
16732*/
16733#ifdef SQLITE_ENABLE_MEMSYS5
16734
16735/*
16736** A minimum allocation is an instance of the following structure.
16737** Larger allocations are an array of these structures where the
16738** size of the array is a power of 2.
16739**
16740** The size of this object must be a power of two.  That fact is
16741** verified in memsys5Init().
16742*/
16743typedef struct Mem5Link Mem5Link;
16744struct Mem5Link {
16745  int next;       /* Index of next free chunk */
16746  int prev;       /* Index of previous free chunk */
16747};
16748
16749/*
16750** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
16751** mem5.szAtom is always at least 8 and 32-bit integers are used,
16752** it is not actually possible to reach this limit.
16753*/
16754#define LOGMAX 30
16755
16756/*
16757** Masks used for mem5.aCtrl[] elements.
16758*/
16759#define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
16760#define CTRL_FREE     0x20    /* True if not checked out */
16761
16762/*
16763** All of the static variables used by this module are collected
16764** into a single structure named "mem5".  This is to keep the
16765** static variables organized and to reduce namespace pollution
16766** when this module is combined with other in the amalgamation.
16767*/
16768static SQLITE_WSD struct Mem5Global {
16769  /*
16770  ** Memory available for allocation
16771  */
16772  int szAtom;      /* Smallest possible allocation in bytes */
16773  int nBlock;      /* Number of szAtom sized blocks in zPool */
16774  u8 *zPool;       /* Memory available to be allocated */
16775
16776  /*
16777  ** Mutex to control access to the memory allocation subsystem.
16778  */
16779  sqlite3_mutex *mutex;
16780
16781  /*
16782  ** Performance statistics
16783  */
16784  u64 nAlloc;         /* Total number of calls to malloc */
16785  u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
16786  u64 totalExcess;    /* Total internal fragmentation */
16787  u32 currentOut;     /* Current checkout, including internal fragmentation */
16788  u32 currentCount;   /* Current number of distinct checkouts */
16789  u32 maxOut;         /* Maximum instantaneous currentOut */
16790  u32 maxCount;       /* Maximum instantaneous currentCount */
16791  u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
16792
16793  /*
16794  ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
16795  ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
16796  ** and so forth.
16797  */
16798  int aiFreelist[LOGMAX+1];
16799
16800  /*
16801  ** Space for tracking which blocks are checked out and the size
16802  ** of each block.  One byte per block.
16803  */
16804  u8 *aCtrl;
16805
16806} mem5;
16807
16808/*
16809** Access the static variable through a macro for SQLITE_OMIT_WSD
16810*/
16811#define mem5 GLOBAL(struct Mem5Global, mem5)
16812
16813/*
16814** Assuming mem5.zPool is divided up into an array of Mem5Link
16815** structures, return a pointer to the idx-th such lik.
16816*/
16817#define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
16818
16819/*
16820** Unlink the chunk at mem5.aPool[i] from list it is currently
16821** on.  It should be found on mem5.aiFreelist[iLogsize].
16822*/
16823static void memsys5Unlink(int i, int iLogsize){
16824  int next, prev;
16825  assert( i>=0 && i<mem5.nBlock );
16826  assert( iLogsize>=0 && iLogsize<=LOGMAX );
16827  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16828
16829  next = MEM5LINK(i)->next;
16830  prev = MEM5LINK(i)->prev;
16831  if( prev<0 ){
16832    mem5.aiFreelist[iLogsize] = next;
16833  }else{
16834    MEM5LINK(prev)->next = next;
16835  }
16836  if( next>=0 ){
16837    MEM5LINK(next)->prev = prev;
16838  }
16839}
16840
16841/*
16842** Link the chunk at mem5.aPool[i] so that is on the iLogsize
16843** free list.
16844*/
16845static void memsys5Link(int i, int iLogsize){
16846  int x;
16847  assert( sqlite3_mutex_held(mem5.mutex) );
16848  assert( i>=0 && i<mem5.nBlock );
16849  assert( iLogsize>=0 && iLogsize<=LOGMAX );
16850  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
16851
16852  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
16853  MEM5LINK(i)->prev = -1;
16854  if( x>=0 ){
16855    assert( x<mem5.nBlock );
16856    MEM5LINK(x)->prev = i;
16857  }
16858  mem5.aiFreelist[iLogsize] = i;
16859}
16860
16861/*
16862** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16863** will already be held (obtained by code in malloc.c) if
16864** sqlite3GlobalConfig.bMemStat is true.
16865*/
16866static void memsys5Enter(void){
16867  sqlite3_mutex_enter(mem5.mutex);
16868}
16869static void memsys5Leave(void){
16870  sqlite3_mutex_leave(mem5.mutex);
16871}
16872
16873/*
16874** Return the size of an outstanding allocation, in bytes.  The
16875** size returned omits the 8-byte header overhead.  This only
16876** works for chunks that are currently checked out.
16877*/
16878static int memsys5Size(void *p){
16879  int iSize = 0;
16880  if( p ){
16881    int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
16882    assert( i>=0 && i<mem5.nBlock );
16883    iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
16884  }
16885  return iSize;
16886}
16887
16888/*
16889** Find the first entry on the freelist iLogsize.  Unlink that
16890** entry and return its index.
16891*/
16892static int memsys5UnlinkFirst(int iLogsize){
16893  int i;
16894  int iFirst;
16895
16896  assert( iLogsize>=0 && iLogsize<=LOGMAX );
16897  i = iFirst = mem5.aiFreelist[iLogsize];
16898  assert( iFirst>=0 );
16899  while( i>0 ){
16900    if( i<iFirst ) iFirst = i;
16901    i = MEM5LINK(i)->next;
16902  }
16903  memsys5Unlink(iFirst, iLogsize);
16904  return iFirst;
16905}
16906
16907/*
16908** Return a block of memory of at least nBytes in size.
16909** Return NULL if unable.  Return NULL if nBytes==0.
16910**
16911** The caller guarantees that nByte positive.
16912**
16913** The caller has obtained a mutex prior to invoking this
16914** routine so there is never any chance that two or more
16915** threads can be in this routine at the same time.
16916*/
16917static void *memsys5MallocUnsafe(int nByte){
16918  int i;           /* Index of a mem5.aPool[] slot */
16919  int iBin;        /* Index into mem5.aiFreelist[] */
16920  int iFullSz;     /* Size of allocation rounded up to power of 2 */
16921  int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
16922
16923  /* nByte must be a positive */
16924  assert( nByte>0 );
16925
16926  /* Keep track of the maximum allocation request.  Even unfulfilled
16927  ** requests are counted */
16928  if( (u32)nByte>mem5.maxRequest ){
16929    mem5.maxRequest = nByte;
16930  }
16931
16932  /* Abort if the requested allocation size is larger than the largest
16933  ** power of two that we can represent using 32-bit signed integers.
16934  */
16935  if( nByte > 0x40000000 ){
16936    return 0;
16937  }
16938
16939  /* Round nByte up to the next valid power of two */
16940  for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
16941
16942  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
16943  ** block.  If not, then split a block of the next larger power of
16944  ** two in order to create a new free block of size iLogsize.
16945  */
16946  for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
16947  if( iBin>LOGMAX ){
16948    testcase( sqlite3GlobalConfig.xLog!=0 );
16949    sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
16950    return 0;
16951  }
16952  i = memsys5UnlinkFirst(iBin);
16953  while( iBin>iLogsize ){
16954    int newSize;
16955
16956    iBin--;
16957    newSize = 1 << iBin;
16958    mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
16959    memsys5Link(i+newSize, iBin);
16960  }
16961  mem5.aCtrl[i] = iLogsize;
16962
16963  /* Update allocator performance statistics. */
16964  mem5.nAlloc++;
16965  mem5.totalAlloc += iFullSz;
16966  mem5.totalExcess += iFullSz - nByte;
16967  mem5.currentCount++;
16968  mem5.currentOut += iFullSz;
16969  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
16970  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
16971
16972  /* Return a pointer to the allocated memory. */
16973  return (void*)&mem5.zPool[i*mem5.szAtom];
16974}
16975
16976/*
16977** Free an outstanding memory allocation.
16978*/
16979static void memsys5FreeUnsafe(void *pOld){
16980  u32 size, iLogsize;
16981  int iBlock;
16982
16983  /* Set iBlock to the index of the block pointed to by pOld in
16984  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
16985  */
16986  iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
16987
16988  /* Check that the pointer pOld points to a valid, non-free block. */
16989  assert( iBlock>=0 && iBlock<mem5.nBlock );
16990  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
16991  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
16992
16993  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
16994  size = 1<<iLogsize;
16995  assert( iBlock+size-1<(u32)mem5.nBlock );
16996
16997  mem5.aCtrl[iBlock] |= CTRL_FREE;
16998  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
16999  assert( mem5.currentCount>0 );
17000  assert( mem5.currentOut>=(size*mem5.szAtom) );
17001  mem5.currentCount--;
17002  mem5.currentOut -= size*mem5.szAtom;
17003  assert( mem5.currentOut>0 || mem5.currentCount==0 );
17004  assert( mem5.currentCount>0 || mem5.currentOut==0 );
17005
17006  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17007  while( ALWAYS(iLogsize<LOGMAX) ){
17008    int iBuddy;
17009    if( (iBlock>>iLogsize) & 1 ){
17010      iBuddy = iBlock - size;
17011    }else{
17012      iBuddy = iBlock + size;
17013    }
17014    assert( iBuddy>=0 );
17015    if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17016    if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17017    memsys5Unlink(iBuddy, iLogsize);
17018    iLogsize++;
17019    if( iBuddy<iBlock ){
17020      mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17021      mem5.aCtrl[iBlock] = 0;
17022      iBlock = iBuddy;
17023    }else{
17024      mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17025      mem5.aCtrl[iBuddy] = 0;
17026    }
17027    size *= 2;
17028  }
17029  memsys5Link(iBlock, iLogsize);
17030}
17031
17032/*
17033** Allocate nBytes of memory
17034*/
17035static void *memsys5Malloc(int nBytes){
17036  sqlite3_int64 *p = 0;
17037  if( nBytes>0 ){
17038    memsys5Enter();
17039    p = memsys5MallocUnsafe(nBytes);
17040    memsys5Leave();
17041  }
17042  return (void*)p;
17043}
17044
17045/*
17046** Free memory.
17047**
17048** The outer layer memory allocator prevents this routine from
17049** being called with pPrior==0.
17050*/
17051static void memsys5Free(void *pPrior){
17052  assert( pPrior!=0 );
17053  memsys5Enter();
17054  memsys5FreeUnsafe(pPrior);
17055  memsys5Leave();
17056}
17057
17058/*
17059** Change the size of an existing memory allocation.
17060**
17061** The outer layer memory allocator prevents this routine from
17062** being called with pPrior==0.
17063**
17064** nBytes is always a value obtained from a prior call to
17065** memsys5Round().  Hence nBytes is always a non-negative power
17066** of two.  If nBytes==0 that means that an oversize allocation
17067** (an allocation larger than 0x40000000) was requested and this
17068** routine should return 0 without freeing pPrior.
17069*/
17070static void *memsys5Realloc(void *pPrior, int nBytes){
17071  int nOld;
17072  void *p;
17073  assert( pPrior!=0 );
17074  assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17075  assert( nBytes>=0 );
17076  if( nBytes==0 ){
17077    return 0;
17078  }
17079  nOld = memsys5Size(pPrior);
17080  if( nBytes<=nOld ){
17081    return pPrior;
17082  }
17083  memsys5Enter();
17084  p = memsys5MallocUnsafe(nBytes);
17085  if( p ){
17086    memcpy(p, pPrior, nOld);
17087    memsys5FreeUnsafe(pPrior);
17088  }
17089  memsys5Leave();
17090  return p;
17091}
17092
17093/*
17094** Round up a request size to the next valid allocation size.  If
17095** the allocation is too large to be handled by this allocation system,
17096** return 0.
17097**
17098** All allocations must be a power of two and must be expressed by a
17099** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17100** or 1073741824 bytes.
17101*/
17102static int memsys5Roundup(int n){
17103  int iFullSz;
17104  if( n > 0x40000000 ) return 0;
17105  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17106  return iFullSz;
17107}
17108
17109/*
17110** Return the ceiling of the logarithm base 2 of iValue.
17111**
17112** Examples:   memsys5Log(1) -> 0
17113**             memsys5Log(2) -> 1
17114**             memsys5Log(4) -> 2
17115**             memsys5Log(5) -> 3
17116**             memsys5Log(8) -> 3
17117**             memsys5Log(9) -> 4
17118*/
17119static int memsys5Log(int iValue){
17120  int iLog;
17121  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17122  return iLog;
17123}
17124
17125/*
17126** Initialize the memory allocator.
17127**
17128** This routine is not threadsafe.  The caller must be holding a mutex
17129** to prevent multiple threads from entering at the same time.
17130*/
17131static int memsys5Init(void *NotUsed){
17132  int ii;            /* Loop counter */
17133  int nByte;         /* Number of bytes of memory available to this allocator */
17134  u8 *zByte;         /* Memory usable by this allocator */
17135  int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17136  int iOffset;       /* An offset into mem5.aCtrl[] */
17137
17138  UNUSED_PARAMETER(NotUsed);
17139
17140  /* For the purposes of this routine, disable the mutex */
17141  mem5.mutex = 0;
17142
17143  /* The size of a Mem5Link object must be a power of two.  Verify that
17144  ** this is case.
17145  */
17146  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17147
17148  nByte = sqlite3GlobalConfig.nHeap;
17149  zByte = (u8*)sqlite3GlobalConfig.pHeap;
17150  assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17151
17152  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17153  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17154  mem5.szAtom = (1<<nMinLog);
17155  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17156    mem5.szAtom = mem5.szAtom << 1;
17157  }
17158
17159  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17160  mem5.zPool = zByte;
17161  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17162
17163  for(ii=0; ii<=LOGMAX; ii++){
17164    mem5.aiFreelist[ii] = -1;
17165  }
17166
17167  iOffset = 0;
17168  for(ii=LOGMAX; ii>=0; ii--){
17169    int nAlloc = (1<<ii);
17170    if( (iOffset+nAlloc)<=mem5.nBlock ){
17171      mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17172      memsys5Link(iOffset, ii);
17173      iOffset += nAlloc;
17174    }
17175    assert((iOffset+nAlloc)>mem5.nBlock);
17176  }
17177
17178  /* If a mutex is required for normal operation, allocate one */
17179  if( sqlite3GlobalConfig.bMemstat==0 ){
17180    mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17181  }
17182
17183  return SQLITE_OK;
17184}
17185
17186/*
17187** Deinitialize this module.
17188*/
17189static void memsys5Shutdown(void *NotUsed){
17190  UNUSED_PARAMETER(NotUsed);
17191  mem5.mutex = 0;
17192  return;
17193}
17194
17195#ifdef SQLITE_TEST
17196/*
17197** Open the file indicated and write a log of all unfreed memory
17198** allocations into that log.
17199*/
17200SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17201  FILE *out;
17202  int i, j, n;
17203  int nMinLog;
17204
17205  if( zFilename==0 || zFilename[0]==0 ){
17206    out = stdout;
17207  }else{
17208    out = fopen(zFilename, "w");
17209    if( out==0 ){
17210      fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17211                      zFilename);
17212      return;
17213    }
17214  }
17215  memsys5Enter();
17216  nMinLog = memsys5Log(mem5.szAtom);
17217  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17218    for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17219    fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17220  }
17221  fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17222  fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17223  fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17224  fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17225  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17226  fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17227  fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17228  fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17229  memsys5Leave();
17230  if( out==stdout ){
17231    fflush(stdout);
17232  }else{
17233    fclose(out);
17234  }
17235}
17236#endif
17237
17238/*
17239** This routine is the only routine in this file with external
17240** linkage. It returns a pointer to a static sqlite3_mem_methods
17241** struct populated with the memsys5 methods.
17242*/
17243SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17244  static const sqlite3_mem_methods memsys5Methods = {
17245     memsys5Malloc,
17246     memsys5Free,
17247     memsys5Realloc,
17248     memsys5Size,
17249     memsys5Roundup,
17250     memsys5Init,
17251     memsys5Shutdown,
17252     0
17253  };
17254  return &memsys5Methods;
17255}
17256
17257#endif /* SQLITE_ENABLE_MEMSYS5 */
17258
17259/************** End of mem5.c ************************************************/
17260/************** Begin file mutex.c *******************************************/
17261/*
17262** 2007 August 14
17263**
17264** The author disclaims copyright to this source code.  In place of
17265** a legal notice, here is a blessing:
17266**
17267**    May you do good and not evil.
17268**    May you find forgiveness for yourself and forgive others.
17269**    May you share freely, never taking more than you give.
17270**
17271*************************************************************************
17272** This file contains the C functions that implement mutexes.
17273**
17274** This file contains code that is common across all mutex implementations.
17275*/
17276
17277#if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17278/*
17279** For debugging purposes, record when the mutex subsystem is initialized
17280** and uninitialized so that we can assert() if there is an attempt to
17281** allocate a mutex while the system is uninitialized.
17282*/
17283static SQLITE_WSD int mutexIsInit = 0;
17284#endif /* SQLITE_DEBUG */
17285
17286
17287#ifndef SQLITE_MUTEX_OMIT
17288/*
17289** Initialize the mutex system.
17290*/
17291SQLITE_PRIVATE int sqlite3MutexInit(void){
17292  int rc = SQLITE_OK;
17293  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17294    /* If the xMutexAlloc method has not been set, then the user did not
17295    ** install a mutex implementation via sqlite3_config() prior to
17296    ** sqlite3_initialize() being called. This block copies pointers to
17297    ** the default implementation into the sqlite3GlobalConfig structure.
17298    */
17299    sqlite3_mutex_methods const *pFrom;
17300    sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17301
17302    if( sqlite3GlobalConfig.bCoreMutex ){
17303      pFrom = sqlite3DefaultMutex();
17304    }else{
17305      pFrom = sqlite3NoopMutex();
17306    }
17307    memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17308    memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17309           sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17310    pTo->xMutexAlloc = pFrom->xMutexAlloc;
17311  }
17312  rc = sqlite3GlobalConfig.mutex.xMutexInit();
17313
17314#ifdef SQLITE_DEBUG
17315  GLOBAL(int, mutexIsInit) = 1;
17316#endif
17317
17318  return rc;
17319}
17320
17321/*
17322** Shutdown the mutex system. This call frees resources allocated by
17323** sqlite3MutexInit().
17324*/
17325SQLITE_PRIVATE int sqlite3MutexEnd(void){
17326  int rc = SQLITE_OK;
17327  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17328    rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17329  }
17330
17331#ifdef SQLITE_DEBUG
17332  GLOBAL(int, mutexIsInit) = 0;
17333#endif
17334
17335  return rc;
17336}
17337
17338/*
17339** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17340*/
17341SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17342#ifndef SQLITE_OMIT_AUTOINIT
17343  if( sqlite3_initialize() ) return 0;
17344#endif
17345  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17346}
17347
17348SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17349  if( !sqlite3GlobalConfig.bCoreMutex ){
17350    return 0;
17351  }
17352  assert( GLOBAL(int, mutexIsInit) );
17353  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17354}
17355
17356/*
17357** Free a dynamic mutex.
17358*/
17359SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17360  if( p ){
17361    sqlite3GlobalConfig.mutex.xMutexFree(p);
17362  }
17363}
17364
17365/*
17366** Obtain the mutex p. If some other thread already has the mutex, block
17367** until it can be obtained.
17368*/
17369SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17370  if( p ){
17371    sqlite3GlobalConfig.mutex.xMutexEnter(p);
17372  }
17373}
17374
17375/*
17376** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17377** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17378*/
17379SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17380  int rc = SQLITE_OK;
17381  if( p ){
17382    return sqlite3GlobalConfig.mutex.xMutexTry(p);
17383  }
17384  return rc;
17385}
17386
17387/*
17388** The sqlite3_mutex_leave() routine exits a mutex that was previously
17389** entered by the same thread.  The behavior is undefined if the mutex
17390** is not currently entered. If a NULL pointer is passed as an argument
17391** this function is a no-op.
17392*/
17393SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17394  if( p ){
17395    sqlite3GlobalConfig.mutex.xMutexLeave(p);
17396  }
17397}
17398
17399#ifndef NDEBUG
17400/*
17401** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17402** intended for use inside assert() statements.
17403*/
17404SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17405  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17406}
17407SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17408  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17409}
17410#endif
17411
17412#endif /* !defined(SQLITE_MUTEX_OMIT) */
17413
17414/************** End of mutex.c ***********************************************/
17415/************** Begin file mutex_noop.c **************************************/
17416/*
17417** 2008 October 07
17418**
17419** The author disclaims copyright to this source code.  In place of
17420** a legal notice, here is a blessing:
17421**
17422**    May you do good and not evil.
17423**    May you find forgiveness for yourself and forgive others.
17424**    May you share freely, never taking more than you give.
17425**
17426*************************************************************************
17427** This file contains the C functions that implement mutexes.
17428**
17429** This implementation in this file does not provide any mutual
17430** exclusion and is thus suitable for use only in applications
17431** that use SQLite in a single thread.  The routines defined
17432** here are place-holders.  Applications can substitute working
17433** mutex routines at start-time using the
17434**
17435**     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17436**
17437** interface.
17438**
17439** If compiled with SQLITE_DEBUG, then additional logic is inserted
17440** that does error checking on mutexes to make sure they are being
17441** called correctly.
17442*/
17443
17444#ifndef SQLITE_MUTEX_OMIT
17445
17446#ifndef SQLITE_DEBUG
17447/*
17448** Stub routines for all mutex methods.
17449**
17450** This routines provide no mutual exclusion or error checking.
17451*/
17452static int noopMutexInit(void){ return SQLITE_OK; }
17453static int noopMutexEnd(void){ return SQLITE_OK; }
17454static sqlite3_mutex *noopMutexAlloc(int id){
17455  UNUSED_PARAMETER(id);
17456  return (sqlite3_mutex*)8;
17457}
17458static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17459static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17460static int noopMutexTry(sqlite3_mutex *p){
17461  UNUSED_PARAMETER(p);
17462  return SQLITE_OK;
17463}
17464static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17465
17466SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17467  static const sqlite3_mutex_methods sMutex = {
17468    noopMutexInit,
17469    noopMutexEnd,
17470    noopMutexAlloc,
17471    noopMutexFree,
17472    noopMutexEnter,
17473    noopMutexTry,
17474    noopMutexLeave,
17475
17476    0,
17477    0,
17478  };
17479
17480  return &sMutex;
17481}
17482#endif /* !SQLITE_DEBUG */
17483
17484#ifdef SQLITE_DEBUG
17485/*
17486** In this implementation, error checking is provided for testing
17487** and debugging purposes.  The mutexes still do not provide any
17488** mutual exclusion.
17489*/
17490
17491/*
17492** The mutex object
17493*/
17494typedef struct sqlite3_debug_mutex {
17495  int id;     /* The mutex type */
17496  int cnt;    /* Number of entries without a matching leave */
17497} sqlite3_debug_mutex;
17498
17499/*
17500** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17501** intended for use inside assert() statements.
17502*/
17503static int debugMutexHeld(sqlite3_mutex *pX){
17504  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17505  return p==0 || p->cnt>0;
17506}
17507static int debugMutexNotheld(sqlite3_mutex *pX){
17508  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17509  return p==0 || p->cnt==0;
17510}
17511
17512/*
17513** Initialize and deinitialize the mutex subsystem.
17514*/
17515static int debugMutexInit(void){ return SQLITE_OK; }
17516static int debugMutexEnd(void){ return SQLITE_OK; }
17517
17518/*
17519** The sqlite3_mutex_alloc() routine allocates a new
17520** mutex and returns a pointer to it.  If it returns NULL
17521** that means that a mutex could not be allocated.
17522*/
17523static sqlite3_mutex *debugMutexAlloc(int id){
17524  static sqlite3_debug_mutex aStatic[6];
17525  sqlite3_debug_mutex *pNew = 0;
17526  switch( id ){
17527    case SQLITE_MUTEX_FAST:
17528    case SQLITE_MUTEX_RECURSIVE: {
17529      pNew = sqlite3Malloc(sizeof(*pNew));
17530      if( pNew ){
17531        pNew->id = id;
17532        pNew->cnt = 0;
17533      }
17534      break;
17535    }
17536    default: {
17537      assert( id-2 >= 0 );
17538      assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17539      pNew = &aStatic[id-2];
17540      pNew->id = id;
17541      break;
17542    }
17543  }
17544  return (sqlite3_mutex*)pNew;
17545}
17546
17547/*
17548** This routine deallocates a previously allocated mutex.
17549*/
17550static void debugMutexFree(sqlite3_mutex *pX){
17551  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17552  assert( p->cnt==0 );
17553  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17554  sqlite3_free(p);
17555}
17556
17557/*
17558** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17559** to enter a mutex.  If another thread is already within the mutex,
17560** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17561** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17562** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17563** be entered multiple times by the same thread.  In such cases the,
17564** mutex must be exited an equal number of times before another thread
17565** can enter.  If the same thread tries to enter any other kind of mutex
17566** more than once, the behavior is undefined.
17567*/
17568static void debugMutexEnter(sqlite3_mutex *pX){
17569  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17570  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17571  p->cnt++;
17572}
17573static int debugMutexTry(sqlite3_mutex *pX){
17574  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17575  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17576  p->cnt++;
17577  return SQLITE_OK;
17578}
17579
17580/*
17581** The sqlite3_mutex_leave() routine exits a mutex that was
17582** previously entered by the same thread.  The behavior
17583** is undefined if the mutex is not currently entered or
17584** is not currently allocated.  SQLite will never do either.
17585*/
17586static void debugMutexLeave(sqlite3_mutex *pX){
17587  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17588  assert( debugMutexHeld(pX) );
17589  p->cnt--;
17590  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
17591}
17592
17593SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17594  static const sqlite3_mutex_methods sMutex = {
17595    debugMutexInit,
17596    debugMutexEnd,
17597    debugMutexAlloc,
17598    debugMutexFree,
17599    debugMutexEnter,
17600    debugMutexTry,
17601    debugMutexLeave,
17602
17603    debugMutexHeld,
17604    debugMutexNotheld
17605  };
17606
17607  return &sMutex;
17608}
17609#endif /* SQLITE_DEBUG */
17610
17611/*
17612** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
17613** is used regardless of the run-time threadsafety setting.
17614*/
17615#ifdef SQLITE_MUTEX_NOOP
17616SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17617  return sqlite3NoopMutex();
17618}
17619#endif /* defined(SQLITE_MUTEX_NOOP) */
17620#endif /* !defined(SQLITE_MUTEX_OMIT) */
17621
17622/************** End of mutex_noop.c ******************************************/
17623/************** Begin file mutex_os2.c ***************************************/
17624/*
17625** 2007 August 28
17626**
17627** The author disclaims copyright to this source code.  In place of
17628** a legal notice, here is a blessing:
17629**
17630**    May you do good and not evil.
17631**    May you find forgiveness for yourself and forgive others.
17632**    May you share freely, never taking more than you give.
17633**
17634*************************************************************************
17635** This file contains the C functions that implement mutexes for OS/2
17636*/
17637
17638/*
17639** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
17640** See the mutex.h file for details.
17641*/
17642#ifdef SQLITE_MUTEX_OS2
17643
17644/********************** OS/2 Mutex Implementation **********************
17645**
17646** This implementation of mutexes is built using the OS/2 API.
17647*/
17648
17649/*
17650** The mutex object
17651** Each recursive mutex is an instance of the following structure.
17652*/
17653struct sqlite3_mutex {
17654  HMTX mutex;       /* Mutex controlling the lock */
17655  int  id;          /* Mutex type */
17656#ifdef SQLITE_DEBUG
17657 int   trace;       /* True to trace changes */
17658#endif
17659};
17660
17661#ifdef SQLITE_DEBUG
17662#define SQLITE3_MUTEX_INITIALIZER { 0, 0, 0 }
17663#else
17664#define SQLITE3_MUTEX_INITIALIZER { 0, 0 }
17665#endif
17666
17667/*
17668** Initialize and deinitialize the mutex subsystem.
17669*/
17670static int os2MutexInit(void){ return SQLITE_OK; }
17671static int os2MutexEnd(void){ return SQLITE_OK; }
17672
17673/*
17674** The sqlite3_mutex_alloc() routine allocates a new
17675** mutex and returns a pointer to it.  If it returns NULL
17676** that means that a mutex could not be allocated.
17677** SQLite will unwind its stack and return an error.  The argument
17678** to sqlite3_mutex_alloc() is one of these integer constants:
17679**
17680** <ul>
17681** <li>  SQLITE_MUTEX_FAST
17682** <li>  SQLITE_MUTEX_RECURSIVE
17683** <li>  SQLITE_MUTEX_STATIC_MASTER
17684** <li>  SQLITE_MUTEX_STATIC_MEM
17685** <li>  SQLITE_MUTEX_STATIC_MEM2
17686** <li>  SQLITE_MUTEX_STATIC_PRNG
17687** <li>  SQLITE_MUTEX_STATIC_LRU
17688** <li>  SQLITE_MUTEX_STATIC_LRU2
17689** </ul>
17690**
17691** The first two constants cause sqlite3_mutex_alloc() to create
17692** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
17693** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
17694** The mutex implementation does not need to make a distinction
17695** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
17696** not want to.  But SQLite will only request a recursive mutex in
17697** cases where it really needs one.  If a faster non-recursive mutex
17698** implementation is available on the host platform, the mutex subsystem
17699** might return such a mutex in response to SQLITE_MUTEX_FAST.
17700**
17701** The other allowed parameters to sqlite3_mutex_alloc() each return
17702** a pointer to a static preexisting mutex.  Six static mutexes are
17703** used by the current version of SQLite.  Future versions of SQLite
17704** may add additional static mutexes.  Static mutexes are for internal
17705** use by SQLite only.  Applications that use SQLite mutexes should
17706** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
17707** SQLITE_MUTEX_RECURSIVE.
17708**
17709** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
17710** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
17711** returns a different mutex on every call.  But for the static
17712** mutex types, the same mutex is returned on every call that has
17713** the same type number.
17714*/
17715static sqlite3_mutex *os2MutexAlloc(int iType){
17716  sqlite3_mutex *p = NULL;
17717  switch( iType ){
17718    case SQLITE_MUTEX_FAST:
17719    case SQLITE_MUTEX_RECURSIVE: {
17720      p = sqlite3MallocZero( sizeof(*p) );
17721      if( p ){
17722        p->id = iType;
17723        if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
17724          sqlite3_free( p );
17725          p = NULL;
17726        }
17727      }
17728      break;
17729    }
17730    default: {
17731      static volatile int isInit = 0;
17732      static sqlite3_mutex staticMutexes[6] = {
17733        SQLITE3_MUTEX_INITIALIZER,
17734        SQLITE3_MUTEX_INITIALIZER,
17735        SQLITE3_MUTEX_INITIALIZER,
17736        SQLITE3_MUTEX_INITIALIZER,
17737        SQLITE3_MUTEX_INITIALIZER,
17738        SQLITE3_MUTEX_INITIALIZER,
17739      };
17740      if ( !isInit ){
17741        APIRET rc;
17742        PTIB ptib;
17743        PPIB ppib;
17744        HMTX mutex;
17745        char name[32];
17746        DosGetInfoBlocks( &ptib, &ppib );
17747        sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
17748                          ppib->pib_ulpid );
17749        while( !isInit ){
17750          mutex = 0;
17751          rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
17752          if( rc == NO_ERROR ){
17753            unsigned int i;
17754            if( !isInit ){
17755              for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
17756                DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
17757              }
17758              isInit = 1;
17759            }
17760            DosCloseMutexSem( mutex );
17761          }else if( rc == ERROR_DUPLICATE_NAME ){
17762            DosSleep( 1 );
17763          }else{
17764            return p;
17765          }
17766        }
17767      }
17768      assert( iType-2 >= 0 );
17769      assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
17770      p = &staticMutexes[iType-2];
17771      p->id = iType;
17772      break;
17773    }
17774  }
17775  return p;
17776}
17777
17778
17779/*
17780** This routine deallocates a previously allocated mutex.
17781** SQLite is careful to deallocate every mutex that it allocates.
17782*/
17783static void os2MutexFree(sqlite3_mutex *p){
17784#ifdef SQLITE_DEBUG
17785  TID tid;
17786  PID pid;
17787  ULONG ulCount;
17788  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17789  assert( ulCount==0 );
17790  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
17791#endif
17792  DosCloseMutexSem( p->mutex );
17793  sqlite3_free( p );
17794}
17795
17796#ifdef SQLITE_DEBUG
17797/*
17798** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17799** intended for use inside assert() statements.
17800*/
17801static int os2MutexHeld(sqlite3_mutex *p){
17802  TID tid;
17803  PID pid;
17804  ULONG ulCount;
17805  PTIB ptib;
17806  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17807  if( ulCount==0 || ( ulCount>1 && p->id!=SQLITE_MUTEX_RECURSIVE ) )
17808    return 0;
17809  DosGetInfoBlocks(&ptib, NULL);
17810  return tid==ptib->tib_ptib2->tib2_ultid;
17811}
17812static int os2MutexNotheld(sqlite3_mutex *p){
17813  TID tid;
17814  PID pid;
17815  ULONG ulCount;
17816  PTIB ptib;
17817  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17818  if( ulCount==0 )
17819    return 1;
17820  DosGetInfoBlocks(&ptib, NULL);
17821  return tid!=ptib->tib_ptib2->tib2_ultid;
17822}
17823static void os2MutexTrace(sqlite3_mutex *p, char *pAction){
17824  TID   tid;
17825  PID   pid;
17826  ULONG ulCount;
17827  DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
17828  printf("%s mutex %p (%d) with nRef=%ld\n", pAction, (void*)p, p->trace, ulCount);
17829}
17830#endif
17831
17832/*
17833** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
17834** to enter a mutex.  If another thread is already within the mutex,
17835** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
17836** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
17837** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
17838** be entered multiple times by the same thread.  In such cases the,
17839** mutex must be exited an equal number of times before another thread
17840** can enter.  If the same thread tries to enter any other kind of mutex
17841** more than once, the behavior is undefined.
17842*/
17843static void os2MutexEnter(sqlite3_mutex *p){
17844  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17845  DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
17846#ifdef SQLITE_DEBUG
17847  if( p->trace ) os2MutexTrace(p, "enter");
17848#endif
17849}
17850static int os2MutexTry(sqlite3_mutex *p){
17851  int rc = SQLITE_BUSY;
17852  assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
17853  if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR ) {
17854    rc = SQLITE_OK;
17855#ifdef SQLITE_DEBUG
17856    if( p->trace ) os2MutexTrace(p, "try");
17857#endif
17858  }
17859  return rc;
17860}
17861
17862/*
17863** The sqlite3_mutex_leave() routine exits a mutex that was
17864** previously entered by the same thread.  The behavior
17865** is undefined if the mutex is not currently entered or
17866** is not currently allocated.  SQLite will never do either.
17867*/
17868static void os2MutexLeave(sqlite3_mutex *p){
17869  assert( os2MutexHeld(p) );
17870  DosReleaseMutexSem(p->mutex);
17871#ifdef SQLITE_DEBUG
17872  if( p->trace ) os2MutexTrace(p, "leave");
17873#endif
17874}
17875
17876SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
17877  static const sqlite3_mutex_methods sMutex = {
17878    os2MutexInit,
17879    os2MutexEnd,
17880    os2MutexAlloc,
17881    os2MutexFree,
17882    os2MutexEnter,
17883    os2MutexTry,
17884    os2MutexLeave,
17885#ifdef SQLITE_DEBUG
17886    os2MutexHeld,
17887    os2MutexNotheld
17888#else
17889    0,
17890    0
17891#endif
17892  };
17893
17894  return &sMutex;
17895}
17896#endif /* SQLITE_MUTEX_OS2 */
17897
17898/************** End of mutex_os2.c *******************************************/
17899/************** Begin file mutex_unix.c **************************************/
17900/*
17901** 2007 August 28
17902**
17903** The author disclaims copyright to this source code.  In place of
17904** a legal notice, here is a blessing:
17905**
17906**    May you do good and not evil.
17907**    May you find forgiveness for yourself and forgive others.
17908**    May you share freely, never taking more than you give.
17909**
17910*************************************************************************
17911** This file contains the C functions that implement mutexes for pthreads
17912*/
17913
17914/*
17915** The code in this file is only used if we are compiling threadsafe
17916** under unix with pthreads.
17917**
17918** Note that this implementation requires a version of pthreads that
17919** supports recursive mutexes.
17920*/
17921#ifdef SQLITE_MUTEX_PTHREADS
17922
17923#include <pthread.h>
17924
17925/*
17926** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
17927** are necessary under two condidtions:  (1) Debug builds and (2) using
17928** home-grown mutexes.  Encapsulate these conditions into a single #define.
17929*/
17930#if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
17931# define SQLITE_MUTEX_NREF 1
17932#else
17933# define SQLITE_MUTEX_NREF 0
17934#endif
17935
17936/*
17937** Each recursive mutex is an instance of the following structure.
17938*/
17939struct sqlite3_mutex {
17940  pthread_mutex_t mutex;     /* Mutex controlling the lock */
17941#if SQLITE_MUTEX_NREF
17942  int id;                    /* Mutex type */
17943  volatile int nRef;         /* Number of entrances */
17944  volatile pthread_t owner;  /* Thread that is within this mutex */
17945  int trace;                 /* True to trace changes */
17946#endif
17947};
17948#if SQLITE_MUTEX_NREF
17949#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
17950#else
17951#define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
17952#endif
17953
17954/*
17955** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17956** intended for use only inside assert() statements.  On some platforms,
17957** there might be race conditions that can cause these routines to
17958** deliver incorrect results.  In particular, if pthread_equal() is
17959** not an atomic operation, then these routines might delivery
17960** incorrect results.  On most platforms, pthread_equal() is a
17961** comparison of two integers and is therefore atomic.  But we are
17962** told that HPUX is not such a platform.  If so, then these routines
17963** will not always work correctly on HPUX.
17964**
17965** On those platforms where pthread_equal() is not atomic, SQLite
17966** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
17967** make sure no assert() statements are evaluated and hence these
17968** routines are never called.
17969*/
17970#if !defined(NDEBUG) || defined(SQLITE_DEBUG)
17971static int pthreadMutexHeld(sqlite3_mutex *p){
17972  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
17973}
17974static int pthreadMutexNotheld(sqlite3_mutex *p){
17975  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
17976}
17977#endif
17978
17979/*
17980** Initialize and deinitialize the mutex subsystem.
17981*/
17982static int pthreadMutexInit(void){ return SQLITE_OK; }
17983static int pthreadMutexEnd(void){ return SQLITE_OK; }
17984
17985/*
17986** The sqlite3_mutex_alloc() routine allocates a new
17987** mutex and returns a pointer to it.  If it returns NULL
17988** that means that a mutex could not be allocated.  SQLite
17989** will unwind its stack and return an error.  The argument
17990** to sqlite3_mutex_alloc() is one of these integer constants:
17991**
17992** <ul>
17993** <li>  SQLITE_MUTEX_FAST
17994** <li>  SQLITE_MUTEX_RECURSIVE
17995** <li>  SQLITE_MUTEX_STATIC_MASTER
17996** <li>  SQLITE_MUTEX_STATIC_MEM
17997** <li>  SQLITE_MUTEX_STATIC_MEM2
17998** <li>  SQLITE_MUTEX_STATIC_PRNG
17999** <li>  SQLITE_MUTEX_STATIC_LRU
18000** <li>  SQLITE_MUTEX_STATIC_PMEM
18001** </ul>
18002**
18003** The first two constants cause sqlite3_mutex_alloc() to create
18004** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18005** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18006** The mutex implementation does not need to make a distinction
18007** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18008** not want to.  But SQLite will only request a recursive mutex in
18009** cases where it really needs one.  If a faster non-recursive mutex
18010** implementation is available on the host platform, the mutex subsystem
18011** might return such a mutex in response to SQLITE_MUTEX_FAST.
18012**
18013** The other allowed parameters to sqlite3_mutex_alloc() each return
18014** a pointer to a static preexisting mutex.  Six static mutexes are
18015** used by the current version of SQLite.  Future versions of SQLite
18016** may add additional static mutexes.  Static mutexes are for internal
18017** use by SQLite only.  Applications that use SQLite mutexes should
18018** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18019** SQLITE_MUTEX_RECURSIVE.
18020**
18021** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18022** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18023** returns a different mutex on every call.  But for the static
18024** mutex types, the same mutex is returned on every call that has
18025** the same type number.
18026*/
18027static sqlite3_mutex *pthreadMutexAlloc(int iType){
18028  static sqlite3_mutex staticMutexes[] = {
18029    SQLITE3_MUTEX_INITIALIZER,
18030    SQLITE3_MUTEX_INITIALIZER,
18031    SQLITE3_MUTEX_INITIALIZER,
18032    SQLITE3_MUTEX_INITIALIZER,
18033    SQLITE3_MUTEX_INITIALIZER,
18034    SQLITE3_MUTEX_INITIALIZER
18035  };
18036  sqlite3_mutex *p;
18037  switch( iType ){
18038    case SQLITE_MUTEX_RECURSIVE: {
18039      p = sqlite3MallocZero( sizeof(*p) );
18040      if( p ){
18041#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18042        /* If recursive mutexes are not available, we will have to
18043        ** build our own.  See below. */
18044        pthread_mutex_init(&p->mutex, 0);
18045#else
18046        /* Use a recursive mutex if it is available */
18047        pthread_mutexattr_t recursiveAttr;
18048        pthread_mutexattr_init(&recursiveAttr);
18049        pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18050        pthread_mutex_init(&p->mutex, &recursiveAttr);
18051        pthread_mutexattr_destroy(&recursiveAttr);
18052#endif
18053#if SQLITE_MUTEX_NREF
18054        p->id = iType;
18055#endif
18056      }
18057      break;
18058    }
18059    case SQLITE_MUTEX_FAST: {
18060      p = sqlite3MallocZero( sizeof(*p) );
18061      if( p ){
18062#if SQLITE_MUTEX_NREF
18063        p->id = iType;
18064#endif
18065        pthread_mutex_init(&p->mutex, 0);
18066      }
18067      break;
18068    }
18069    default: {
18070      assert( iType-2 >= 0 );
18071      assert( iType-2 < ArraySize(staticMutexes) );
18072      p = &staticMutexes[iType-2];
18073#if SQLITE_MUTEX_NREF
18074      p->id = iType;
18075#endif
18076      break;
18077    }
18078  }
18079  return p;
18080}
18081
18082
18083/*
18084** This routine deallocates a previously
18085** allocated mutex.  SQLite is careful to deallocate every
18086** mutex that it allocates.
18087*/
18088static void pthreadMutexFree(sqlite3_mutex *p){
18089  assert( p->nRef==0 );
18090  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18091  pthread_mutex_destroy(&p->mutex);
18092  sqlite3_free(p);
18093}
18094
18095/*
18096** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18097** to enter a mutex.  If another thread is already within the mutex,
18098** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18099** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18100** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18101** be entered multiple times by the same thread.  In such cases the,
18102** mutex must be exited an equal number of times before another thread
18103** can enter.  If the same thread tries to enter any other kind of mutex
18104** more than once, the behavior is undefined.
18105*/
18106static void pthreadMutexEnter(sqlite3_mutex *p){
18107  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18108
18109#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18110  /* If recursive mutexes are not available, then we have to grow
18111  ** our own.  This implementation assumes that pthread_equal()
18112  ** is atomic - that it cannot be deceived into thinking self
18113  ** and p->owner are equal if p->owner changes between two values
18114  ** that are not equal to self while the comparison is taking place.
18115  ** This implementation also assumes a coherent cache - that
18116  ** separate processes cannot read different values from the same
18117  ** address at the same time.  If either of these two conditions
18118  ** are not met, then the mutexes will fail and problems will result.
18119  */
18120  {
18121    pthread_t self = pthread_self();
18122    if( p->nRef>0 && pthread_equal(p->owner, self) ){
18123      p->nRef++;
18124    }else{
18125      pthread_mutex_lock(&p->mutex);
18126      assert( p->nRef==0 );
18127      p->owner = self;
18128      p->nRef = 1;
18129    }
18130  }
18131#else
18132  /* Use the built-in recursive mutexes if they are available.
18133  */
18134  pthread_mutex_lock(&p->mutex);
18135#if SQLITE_MUTEX_NREF
18136  assert( p->nRef>0 || p->owner==0 );
18137  p->owner = pthread_self();
18138  p->nRef++;
18139#endif
18140#endif
18141
18142#ifdef SQLITE_DEBUG
18143  if( p->trace ){
18144    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18145  }
18146#endif
18147}
18148static int pthreadMutexTry(sqlite3_mutex *p){
18149  int rc;
18150  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18151
18152#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18153  /* If recursive mutexes are not available, then we have to grow
18154  ** our own.  This implementation assumes that pthread_equal()
18155  ** is atomic - that it cannot be deceived into thinking self
18156  ** and p->owner are equal if p->owner changes between two values
18157  ** that are not equal to self while the comparison is taking place.
18158  ** This implementation also assumes a coherent cache - that
18159  ** separate processes cannot read different values from the same
18160  ** address at the same time.  If either of these two conditions
18161  ** are not met, then the mutexes will fail and problems will result.
18162  */
18163  {
18164    pthread_t self = pthread_self();
18165    if( p->nRef>0 && pthread_equal(p->owner, self) ){
18166      p->nRef++;
18167      rc = SQLITE_OK;
18168    }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18169      assert( p->nRef==0 );
18170      p->owner = self;
18171      p->nRef = 1;
18172      rc = SQLITE_OK;
18173    }else{
18174      rc = SQLITE_BUSY;
18175    }
18176  }
18177#else
18178  /* Use the built-in recursive mutexes if they are available.
18179  */
18180  if( pthread_mutex_trylock(&p->mutex)==0 ){
18181#if SQLITE_MUTEX_NREF
18182    p->owner = pthread_self();
18183    p->nRef++;
18184#endif
18185    rc = SQLITE_OK;
18186  }else{
18187    rc = SQLITE_BUSY;
18188  }
18189#endif
18190
18191#ifdef SQLITE_DEBUG
18192  if( rc==SQLITE_OK && p->trace ){
18193    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18194  }
18195#endif
18196  return rc;
18197}
18198
18199/*
18200** The sqlite3_mutex_leave() routine exits a mutex that was
18201** previously entered by the same thread.  The behavior
18202** is undefined if the mutex is not currently entered or
18203** is not currently allocated.  SQLite will never do either.
18204*/
18205static void pthreadMutexLeave(sqlite3_mutex *p){
18206  assert( pthreadMutexHeld(p) );
18207#if SQLITE_MUTEX_NREF
18208  p->nRef--;
18209  if( p->nRef==0 ) p->owner = 0;
18210#endif
18211  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18212
18213#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18214  if( p->nRef==0 ){
18215    pthread_mutex_unlock(&p->mutex);
18216  }
18217#else
18218  pthread_mutex_unlock(&p->mutex);
18219#endif
18220
18221#ifdef SQLITE_DEBUG
18222  if( p->trace ){
18223    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18224  }
18225#endif
18226}
18227
18228SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18229  static const sqlite3_mutex_methods sMutex = {
18230    pthreadMutexInit,
18231    pthreadMutexEnd,
18232    pthreadMutexAlloc,
18233    pthreadMutexFree,
18234    pthreadMutexEnter,
18235    pthreadMutexTry,
18236    pthreadMutexLeave,
18237#ifdef SQLITE_DEBUG
18238    pthreadMutexHeld,
18239    pthreadMutexNotheld
18240#else
18241    0,
18242    0
18243#endif
18244  };
18245
18246  return &sMutex;
18247}
18248
18249#endif /* SQLITE_MUTEX_PTHREADS */
18250
18251/************** End of mutex_unix.c ******************************************/
18252/************** Begin file mutex_w32.c ***************************************/
18253/*
18254** 2007 August 14
18255**
18256** The author disclaims copyright to this source code.  In place of
18257** a legal notice, here is a blessing:
18258**
18259**    May you do good and not evil.
18260**    May you find forgiveness for yourself and forgive others.
18261**    May you share freely, never taking more than you give.
18262**
18263*************************************************************************
18264** This file contains the C functions that implement mutexes for win32
18265*/
18266
18267/*
18268** The code in this file is only used if we are compiling multithreaded
18269** on a win32 system.
18270*/
18271#ifdef SQLITE_MUTEX_W32
18272
18273/*
18274** Each recursive mutex is an instance of the following structure.
18275*/
18276struct sqlite3_mutex {
18277  CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18278  int id;                    /* Mutex type */
18279#ifdef SQLITE_DEBUG
18280  volatile int nRef;         /* Number of enterances */
18281  volatile DWORD owner;      /* Thread holding this mutex */
18282  int trace;                 /* True to trace changes */
18283#endif
18284};
18285#define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18286#ifdef SQLITE_DEBUG
18287#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18288#else
18289#define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18290#endif
18291
18292/*
18293** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18294** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18295**
18296** Here is an interesting observation:  Win95, Win98, and WinME lack
18297** the LockFileEx() API.  But we can still statically link against that
18298** API as long as we don't call it win running Win95/98/ME.  A call to
18299** this routine is used to determine if the host is Win95/98/ME or
18300** WinNT/2K/XP so that we will know whether or not we can safely call
18301** the LockFileEx() API.
18302**
18303** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18304** which is only available if your application was compiled with
18305** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18306** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
18307** this out as well.
18308*/
18309#if 0
18310#if SQLITE_OS_WINCE
18311# define mutexIsNT()  (1)
18312#else
18313  static int mutexIsNT(void){
18314    static int osType = 0;
18315    if( osType==0 ){
18316      OSVERSIONINFO sInfo;
18317      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18318      GetVersionEx(&sInfo);
18319      osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18320    }
18321    return osType==2;
18322  }
18323#endif /* SQLITE_OS_WINCE */
18324#endif
18325
18326#ifdef SQLITE_DEBUG
18327/*
18328** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18329** intended for use only inside assert() statements.
18330*/
18331static int winMutexHeld(sqlite3_mutex *p){
18332  return p->nRef!=0 && p->owner==GetCurrentThreadId();
18333}
18334static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18335  return p->nRef==0 || p->owner!=tid;
18336}
18337static int winMutexNotheld(sqlite3_mutex *p){
18338  DWORD tid = GetCurrentThreadId();
18339  return winMutexNotheld2(p, tid);
18340}
18341#endif
18342
18343
18344/*
18345** Initialize and deinitialize the mutex subsystem.
18346*/
18347static sqlite3_mutex winMutex_staticMutexes[6] = {
18348  SQLITE3_MUTEX_INITIALIZER,
18349  SQLITE3_MUTEX_INITIALIZER,
18350  SQLITE3_MUTEX_INITIALIZER,
18351  SQLITE3_MUTEX_INITIALIZER,
18352  SQLITE3_MUTEX_INITIALIZER,
18353  SQLITE3_MUTEX_INITIALIZER
18354};
18355static int winMutex_isInit = 0;
18356/* As winMutexInit() and winMutexEnd() are called as part
18357** of the sqlite3_initialize and sqlite3_shutdown()
18358** processing, the "interlocked" magic is probably not
18359** strictly necessary.
18360*/
18361static long winMutex_lock = 0;
18362
18363static int winMutexInit(void){
18364  /* The first to increment to 1 does actual initialization */
18365  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18366    int i;
18367    for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18368      InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18369    }
18370    winMutex_isInit = 1;
18371  }else{
18372    /* Someone else is in the process of initing the static mutexes */
18373    while( !winMutex_isInit ){
18374      Sleep(1);
18375    }
18376  }
18377  return SQLITE_OK;
18378}
18379
18380static int winMutexEnd(void){
18381  /* The first to decrement to 0 does actual shutdown
18382  ** (which should be the last to shutdown.) */
18383  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18384    if( winMutex_isInit==1 ){
18385      int i;
18386      for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18387        DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18388      }
18389      winMutex_isInit = 0;
18390    }
18391  }
18392  return SQLITE_OK;
18393}
18394
18395/*
18396** The sqlite3_mutex_alloc() routine allocates a new
18397** mutex and returns a pointer to it.  If it returns NULL
18398** that means that a mutex could not be allocated.  SQLite
18399** will unwind its stack and return an error.  The argument
18400** to sqlite3_mutex_alloc() is one of these integer constants:
18401**
18402** <ul>
18403** <li>  SQLITE_MUTEX_FAST
18404** <li>  SQLITE_MUTEX_RECURSIVE
18405** <li>  SQLITE_MUTEX_STATIC_MASTER
18406** <li>  SQLITE_MUTEX_STATIC_MEM
18407** <li>  SQLITE_MUTEX_STATIC_MEM2
18408** <li>  SQLITE_MUTEX_STATIC_PRNG
18409** <li>  SQLITE_MUTEX_STATIC_LRU
18410** <li>  SQLITE_MUTEX_STATIC_PMEM
18411** </ul>
18412**
18413** The first two constants cause sqlite3_mutex_alloc() to create
18414** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18415** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18416** The mutex implementation does not need to make a distinction
18417** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18418** not want to.  But SQLite will only request a recursive mutex in
18419** cases where it really needs one.  If a faster non-recursive mutex
18420** implementation is available on the host platform, the mutex subsystem
18421** might return such a mutex in response to SQLITE_MUTEX_FAST.
18422**
18423** The other allowed parameters to sqlite3_mutex_alloc() each return
18424** a pointer to a static preexisting mutex.  Six static mutexes are
18425** used by the current version of SQLite.  Future versions of SQLite
18426** may add additional static mutexes.  Static mutexes are for internal
18427** use by SQLite only.  Applications that use SQLite mutexes should
18428** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18429** SQLITE_MUTEX_RECURSIVE.
18430**
18431** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18432** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18433** returns a different mutex on every call.  But for the static
18434** mutex types, the same mutex is returned on every call that has
18435** the same type number.
18436*/
18437static sqlite3_mutex *winMutexAlloc(int iType){
18438  sqlite3_mutex *p;
18439
18440  switch( iType ){
18441    case SQLITE_MUTEX_FAST:
18442    case SQLITE_MUTEX_RECURSIVE: {
18443      p = sqlite3MallocZero( sizeof(*p) );
18444      if( p ){
18445#ifdef SQLITE_DEBUG
18446        p->id = iType;
18447#endif
18448        InitializeCriticalSection(&p->mutex);
18449      }
18450      break;
18451    }
18452    default: {
18453      assert( winMutex_isInit==1 );
18454      assert( iType-2 >= 0 );
18455      assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18456      p = &winMutex_staticMutexes[iType-2];
18457#ifdef SQLITE_DEBUG
18458      p->id = iType;
18459#endif
18460      break;
18461    }
18462  }
18463  return p;
18464}
18465
18466
18467/*
18468** This routine deallocates a previously
18469** allocated mutex.  SQLite is careful to deallocate every
18470** mutex that it allocates.
18471*/
18472static void winMutexFree(sqlite3_mutex *p){
18473  assert( p );
18474  assert( p->nRef==0 && p->owner==0 );
18475  assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18476  DeleteCriticalSection(&p->mutex);
18477  sqlite3_free(p);
18478}
18479
18480/*
18481** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18482** to enter a mutex.  If another thread is already within the mutex,
18483** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18484** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18485** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18486** be entered multiple times by the same thread.  In such cases the,
18487** mutex must be exited an equal number of times before another thread
18488** can enter.  If the same thread tries to enter any other kind of mutex
18489** more than once, the behavior is undefined.
18490*/
18491static void winMutexEnter(sqlite3_mutex *p){
18492#ifdef SQLITE_DEBUG
18493  DWORD tid = GetCurrentThreadId();
18494  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18495#endif
18496  EnterCriticalSection(&p->mutex);
18497#ifdef SQLITE_DEBUG
18498  assert( p->nRef>0 || p->owner==0 );
18499  p->owner = tid;
18500  p->nRef++;
18501  if( p->trace ){
18502    printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18503  }
18504#endif
18505}
18506static int winMutexTry(sqlite3_mutex *p){
18507#ifndef NDEBUG
18508  DWORD tid = GetCurrentThreadId();
18509#endif
18510  int rc = SQLITE_BUSY;
18511  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18512  /*
18513  ** The sqlite3_mutex_try() routine is very rarely used, and when it
18514  ** is used it is merely an optimization.  So it is OK for it to always
18515  ** fail.
18516  **
18517  ** The TryEnterCriticalSection() interface is only available on WinNT.
18518  ** And some windows compilers complain if you try to use it without
18519  ** first doing some #defines that prevent SQLite from building on Win98.
18520  ** For that reason, we will omit this optimization for now.  See
18521  ** ticket #2685.
18522  */
18523#if 0
18524  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18525    p->owner = tid;
18526    p->nRef++;
18527    rc = SQLITE_OK;
18528  }
18529#else
18530  UNUSED_PARAMETER(p);
18531#endif
18532#ifdef SQLITE_DEBUG
18533  if( rc==SQLITE_OK && p->trace ){
18534    printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18535  }
18536#endif
18537  return rc;
18538}
18539
18540/*
18541** The sqlite3_mutex_leave() routine exits a mutex that was
18542** previously entered by the same thread.  The behavior
18543** is undefined if the mutex is not currently entered or
18544** is not currently allocated.  SQLite will never do either.
18545*/
18546static void winMutexLeave(sqlite3_mutex *p){
18547#ifndef NDEBUG
18548  DWORD tid = GetCurrentThreadId();
18549  assert( p->nRef>0 );
18550  assert( p->owner==tid );
18551  p->nRef--;
18552  if( p->nRef==0 ) p->owner = 0;
18553  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18554#endif
18555  LeaveCriticalSection(&p->mutex);
18556#ifdef SQLITE_DEBUG
18557  if( p->trace ){
18558    printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18559  }
18560#endif
18561}
18562
18563SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18564  static const sqlite3_mutex_methods sMutex = {
18565    winMutexInit,
18566    winMutexEnd,
18567    winMutexAlloc,
18568    winMutexFree,
18569    winMutexEnter,
18570    winMutexTry,
18571    winMutexLeave,
18572#ifdef SQLITE_DEBUG
18573    winMutexHeld,
18574    winMutexNotheld
18575#else
18576    0,
18577    0
18578#endif
18579  };
18580
18581  return &sMutex;
18582}
18583#endif /* SQLITE_MUTEX_W32 */
18584
18585/************** End of mutex_w32.c *******************************************/
18586/************** Begin file malloc.c ******************************************/
18587/*
18588** 2001 September 15
18589**
18590** The author disclaims copyright to this source code.  In place of
18591** a legal notice, here is a blessing:
18592**
18593**    May you do good and not evil.
18594**    May you find forgiveness for yourself and forgive others.
18595**    May you share freely, never taking more than you give.
18596**
18597*************************************************************************
18598**
18599** Memory allocation functions used throughout sqlite.
18600*/
18601/* #include <stdarg.h> */
18602
18603/*
18604** Attempt to release up to n bytes of non-essential memory currently
18605** held by SQLite. An example of non-essential memory is memory used to
18606** cache database pages that are not currently in use.
18607*/
18608SQLITE_API int sqlite3_release_memory(int n){
18609#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18610  return sqlite3PcacheReleaseMemory(n);
18611#else
18612  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18613  ** is a no-op returning zero if SQLite is not compiled with
18614  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18615  UNUSED_PARAMETER(n);
18616  return 0;
18617#endif
18618}
18619
18620/*
18621** An instance of the following object records the location of
18622** each unused scratch buffer.
18623*/
18624typedef struct ScratchFreeslot {
18625  struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18626} ScratchFreeslot;
18627
18628/*
18629** State information local to the memory allocation subsystem.
18630*/
18631static SQLITE_WSD struct Mem0Global {
18632  sqlite3_mutex *mutex;         /* Mutex to serialize access */
18633
18634  /*
18635  ** The alarm callback and its arguments.  The mem0.mutex lock will
18636  ** be held while the callback is running.  Recursive calls into
18637  ** the memory subsystem are allowed, but no new callbacks will be
18638  ** issued.
18639  */
18640  sqlite3_int64 alarmThreshold;
18641  void (*alarmCallback)(void*, sqlite3_int64,int);
18642  void *alarmArg;
18643
18644  /*
18645  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18646  ** (so that a range test can be used to determine if an allocation
18647  ** being freed came from pScratch) and a pointer to the list of
18648  ** unused scratch allocations.
18649  */
18650  void *pScratchEnd;
18651  ScratchFreeslot *pScratchFree;
18652  u32 nScratchFree;
18653
18654  /*
18655  ** True if heap is nearly "full" where "full" is defined by the
18656  ** sqlite3_soft_heap_limit() setting.
18657  */
18658  int nearlyFull;
18659} mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18660
18661#define mem0 GLOBAL(struct Mem0Global, mem0)
18662
18663/*
18664** This routine runs when the memory allocator sees that the
18665** total memory allocation is about to exceed the soft heap
18666** limit.
18667*/
18668static void softHeapLimitEnforcer(
18669  void *NotUsed,
18670  sqlite3_int64 NotUsed2,
18671  int allocSize
18672){
18673  UNUSED_PARAMETER2(NotUsed, NotUsed2);
18674  sqlite3_release_memory(allocSize);
18675}
18676
18677/*
18678** Change the alarm callback
18679*/
18680static int sqlite3MemoryAlarm(
18681  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18682  void *pArg,
18683  sqlite3_int64 iThreshold
18684){
18685  int nUsed;
18686  sqlite3_mutex_enter(mem0.mutex);
18687  mem0.alarmCallback = xCallback;
18688  mem0.alarmArg = pArg;
18689  mem0.alarmThreshold = iThreshold;
18690  nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18691  mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18692  sqlite3_mutex_leave(mem0.mutex);
18693  return SQLITE_OK;
18694}
18695
18696#ifndef SQLITE_OMIT_DEPRECATED
18697/*
18698** Deprecated external interface.  Internal/core SQLite code
18699** should call sqlite3MemoryAlarm.
18700*/
18701SQLITE_API int sqlite3_memory_alarm(
18702  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18703  void *pArg,
18704  sqlite3_int64 iThreshold
18705){
18706  return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18707}
18708#endif
18709
18710/*
18711** Set the soft heap-size limit for the library. Passing a zero or
18712** negative value indicates no limit.
18713*/
18714SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18715  sqlite3_int64 priorLimit;
18716  sqlite3_int64 excess;
18717#ifndef SQLITE_OMIT_AUTOINIT
18718  int rc = sqlite3_initialize();
18719  if( rc ) return -1;
18720#endif
18721  sqlite3_mutex_enter(mem0.mutex);
18722  priorLimit = mem0.alarmThreshold;
18723  sqlite3_mutex_leave(mem0.mutex);
18724  if( n<0 ) return priorLimit;
18725  if( n>0 ){
18726    sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18727  }else{
18728    sqlite3MemoryAlarm(0, 0, 0);
18729  }
18730  excess = sqlite3_memory_used() - n;
18731  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18732  return priorLimit;
18733}
18734SQLITE_API void sqlite3_soft_heap_limit(int n){
18735  if( n<0 ) n = 0;
18736  sqlite3_soft_heap_limit64(n);
18737}
18738
18739/*
18740** Initialize the memory allocation subsystem.
18741*/
18742SQLITE_PRIVATE int sqlite3MallocInit(void){
18743  if( sqlite3GlobalConfig.m.xMalloc==0 ){
18744    sqlite3MemSetDefault();
18745  }
18746  memset(&mem0, 0, sizeof(mem0));
18747  if( sqlite3GlobalConfig.bCoreMutex ){
18748    mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18749  }
18750  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18751      && sqlite3GlobalConfig.nScratch>0 ){
18752    int i, n, sz;
18753    ScratchFreeslot *pSlot;
18754    sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18755    sqlite3GlobalConfig.szScratch = sz;
18756    pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18757    n = sqlite3GlobalConfig.nScratch;
18758    mem0.pScratchFree = pSlot;
18759    mem0.nScratchFree = n;
18760    for(i=0; i<n-1; i++){
18761      pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18762      pSlot = pSlot->pNext;
18763    }
18764    pSlot->pNext = 0;
18765    mem0.pScratchEnd = (void*)&pSlot[1];
18766  }else{
18767    mem0.pScratchEnd = 0;
18768    sqlite3GlobalConfig.pScratch = 0;
18769    sqlite3GlobalConfig.szScratch = 0;
18770    sqlite3GlobalConfig.nScratch = 0;
18771  }
18772  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18773      || sqlite3GlobalConfig.nPage<1 ){
18774    sqlite3GlobalConfig.pPage = 0;
18775    sqlite3GlobalConfig.szPage = 0;
18776    sqlite3GlobalConfig.nPage = 0;
18777  }
18778  return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18779}
18780
18781/*
18782** Return true if the heap is currently under memory pressure - in other
18783** words if the amount of heap used is close to the limit set by
18784** sqlite3_soft_heap_limit().
18785*/
18786SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18787  return mem0.nearlyFull;
18788}
18789
18790/*
18791** Deinitialize the memory allocation subsystem.
18792*/
18793SQLITE_PRIVATE void sqlite3MallocEnd(void){
18794  if( sqlite3GlobalConfig.m.xShutdown ){
18795    sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18796  }
18797  memset(&mem0, 0, sizeof(mem0));
18798}
18799
18800/*
18801** Return the amount of memory currently checked out.
18802*/
18803SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18804  int n, mx;
18805  sqlite3_int64 res;
18806  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18807  res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18808  return res;
18809}
18810
18811/*
18812** Return the maximum amount of memory that has ever been
18813** checked out since either the beginning of this process
18814** or since the most recent reset.
18815*/
18816SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18817  int n, mx;
18818  sqlite3_int64 res;
18819  sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
18820  res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
18821  return res;
18822}
18823
18824/*
18825** Trigger the alarm
18826*/
18827static void sqlite3MallocAlarm(int nByte){
18828  void (*xCallback)(void*,sqlite3_int64,int);
18829  sqlite3_int64 nowUsed;
18830  void *pArg;
18831  if( mem0.alarmCallback==0 ) return;
18832  xCallback = mem0.alarmCallback;
18833  nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18834  pArg = mem0.alarmArg;
18835  mem0.alarmCallback = 0;
18836  sqlite3_mutex_leave(mem0.mutex);
18837  xCallback(pArg, nowUsed, nByte);
18838  sqlite3_mutex_enter(mem0.mutex);
18839  mem0.alarmCallback = xCallback;
18840  mem0.alarmArg = pArg;
18841}
18842
18843/*
18844** Do a memory allocation with statistics and alarms.  Assume the
18845** lock is already held.
18846*/
18847static int mallocWithAlarm(int n, void **pp){
18848  int nFull;
18849  void *p;
18850  assert( sqlite3_mutex_held(mem0.mutex) );
18851  nFull = sqlite3GlobalConfig.m.xRoundup(n);
18852  sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
18853  if( mem0.alarmCallback!=0 ){
18854    int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18855    if( nUsed >= mem0.alarmThreshold - nFull ){
18856      mem0.nearlyFull = 1;
18857      sqlite3MallocAlarm(nFull);
18858    }else{
18859      mem0.nearlyFull = 0;
18860    }
18861  }
18862  p = sqlite3GlobalConfig.m.xMalloc(nFull);
18863#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18864  if( p==0 && mem0.alarmCallback ){
18865    sqlite3MallocAlarm(nFull);
18866    p = sqlite3GlobalConfig.m.xMalloc(nFull);
18867  }
18868#endif
18869  if( p ){
18870    nFull = sqlite3MallocSize(p);
18871    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
18872    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
18873  }
18874  *pp = p;
18875  return nFull;
18876}
18877
18878/*
18879** Allocate memory.  This routine is like sqlite3_malloc() except that it
18880** assumes the memory subsystem has already been initialized.
18881*/
18882SQLITE_PRIVATE void *sqlite3Malloc(int n){
18883  void *p;
18884  if( n<=0               /* IMP: R-65312-04917 */
18885   || n>=0x7fffff00
18886  ){
18887    /* A memory allocation of a number of bytes which is near the maximum
18888    ** signed integer value might cause an integer overflow inside of the
18889    ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
18890    ** 255 bytes of overhead.  SQLite itself will never use anything near
18891    ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
18892    p = 0;
18893  }else if( sqlite3GlobalConfig.bMemstat ){
18894    sqlite3_mutex_enter(mem0.mutex);
18895    mallocWithAlarm(n, &p);
18896    sqlite3_mutex_leave(mem0.mutex);
18897  }else{
18898    p = sqlite3GlobalConfig.m.xMalloc(n);
18899  }
18900  assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
18901  return p;
18902}
18903
18904/*
18905** This version of the memory allocation is for use by the application.
18906** First make sure the memory subsystem is initialized, then do the
18907** allocation.
18908*/
18909SQLITE_API void *sqlite3_malloc(int n){
18910#ifndef SQLITE_OMIT_AUTOINIT
18911  if( sqlite3_initialize() ) return 0;
18912#endif
18913  return sqlite3Malloc(n);
18914}
18915
18916/*
18917** Each thread may only have a single outstanding allocation from
18918** xScratchMalloc().  We verify this constraint in the single-threaded
18919** case by setting scratchAllocOut to 1 when an allocation
18920** is outstanding clearing it when the allocation is freed.
18921*/
18922#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18923static int scratchAllocOut = 0;
18924#endif
18925
18926
18927/*
18928** Allocate memory that is to be used and released right away.
18929** This routine is similar to alloca() in that it is not intended
18930** for situations where the memory might be held long-term.  This
18931** routine is intended to get memory to old large transient data
18932** structures that would not normally fit on the stack of an
18933** embedded processor.
18934*/
18935SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
18936  void *p;
18937  assert( n>0 );
18938
18939  sqlite3_mutex_enter(mem0.mutex);
18940  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
18941    p = mem0.pScratchFree;
18942    mem0.pScratchFree = mem0.pScratchFree->pNext;
18943    mem0.nScratchFree--;
18944    sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
18945    sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18946    sqlite3_mutex_leave(mem0.mutex);
18947  }else{
18948    if( sqlite3GlobalConfig.bMemstat ){
18949      sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
18950      n = mallocWithAlarm(n, &p);
18951      if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
18952      sqlite3_mutex_leave(mem0.mutex);
18953    }else{
18954      sqlite3_mutex_leave(mem0.mutex);
18955      p = sqlite3GlobalConfig.m.xMalloc(n);
18956    }
18957    sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
18958  }
18959  assert( sqlite3_mutex_notheld(mem0.mutex) );
18960
18961
18962#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18963  /* Verify that no more than two scratch allocations per thread
18964  ** are outstanding at one time.  (This is only checked in the
18965  ** single-threaded case since checking in the multi-threaded case
18966  ** would be much more complicated.) */
18967  assert( scratchAllocOut<=1 );
18968  if( p ) scratchAllocOut++;
18969#endif
18970
18971  return p;
18972}
18973SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
18974  if( p ){
18975
18976#if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
18977    /* Verify that no more than two scratch allocation per thread
18978    ** is outstanding at one time.  (This is only checked in the
18979    ** single-threaded case since checking in the multi-threaded case
18980    ** would be much more complicated.) */
18981    assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
18982    scratchAllocOut--;
18983#endif
18984
18985    if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
18986      /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
18987      ScratchFreeslot *pSlot;
18988      pSlot = (ScratchFreeslot*)p;
18989      sqlite3_mutex_enter(mem0.mutex);
18990      pSlot->pNext = mem0.pScratchFree;
18991      mem0.pScratchFree = pSlot;
18992      mem0.nScratchFree++;
18993      assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
18994      sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
18995      sqlite3_mutex_leave(mem0.mutex);
18996    }else{
18997      /* Release memory back to the heap */
18998      assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
18999      assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19000      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19001      if( sqlite3GlobalConfig.bMemstat ){
19002        int iSize = sqlite3MallocSize(p);
19003        sqlite3_mutex_enter(mem0.mutex);
19004        sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19005        sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19006        sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19007        sqlite3GlobalConfig.m.xFree(p);
19008        sqlite3_mutex_leave(mem0.mutex);
19009      }else{
19010        sqlite3GlobalConfig.m.xFree(p);
19011      }
19012    }
19013  }
19014}
19015
19016/*
19017** TRUE if p is a lookaside memory allocation from db
19018*/
19019#ifndef SQLITE_OMIT_LOOKASIDE
19020static int isLookaside(sqlite3 *db, void *p){
19021  return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19022}
19023#else
19024#define isLookaside(A,B) 0
19025#endif
19026
19027/*
19028** Return the size of a memory allocation previously obtained from
19029** sqlite3Malloc() or sqlite3_malloc().
19030*/
19031SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19032  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19033  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19034  return sqlite3GlobalConfig.m.xSize(p);
19035}
19036SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19037  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19038  if( db && isLookaside(db, p) ){
19039    return db->lookaside.sz;
19040  }else{
19041    assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19042    assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19043    assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19044    return sqlite3GlobalConfig.m.xSize(p);
19045  }
19046}
19047
19048/*
19049** Free memory previously obtained from sqlite3Malloc().
19050*/
19051SQLITE_API void sqlite3_free(void *p){
19052  if( p==0 ) return;  /* IMP: R-49053-54554 */
19053  assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19054  assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19055  if( sqlite3GlobalConfig.bMemstat ){
19056    sqlite3_mutex_enter(mem0.mutex);
19057    sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19058    sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19059    sqlite3GlobalConfig.m.xFree(p);
19060    sqlite3_mutex_leave(mem0.mutex);
19061  }else{
19062    sqlite3GlobalConfig.m.xFree(p);
19063  }
19064}
19065
19066/*
19067** Free memory that might be associated with a particular database
19068** connection.
19069*/
19070SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19071  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19072  if( db ){
19073    if( db->pnBytesFreed ){
19074      *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19075      return;
19076    }
19077    if( isLookaside(db, p) ){
19078      LookasideSlot *pBuf = (LookasideSlot*)p;
19079      pBuf->pNext = db->lookaside.pFree;
19080      db->lookaside.pFree = pBuf;
19081      db->lookaside.nOut--;
19082      return;
19083    }
19084  }
19085  assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19086  assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19087  assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19088  sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19089  sqlite3_free(p);
19090}
19091
19092/*
19093** Change the size of an existing memory allocation
19094*/
19095SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19096  int nOld, nNew, nDiff;
19097  void *pNew;
19098  if( pOld==0 ){
19099    return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19100  }
19101  if( nBytes<=0 ){
19102    sqlite3_free(pOld); /* IMP: R-31593-10574 */
19103    return 0;
19104  }
19105  if( nBytes>=0x7fffff00 ){
19106    /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19107    return 0;
19108  }
19109  nOld = sqlite3MallocSize(pOld);
19110  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19111  ** argument to xRealloc is always a value returned by a prior call to
19112  ** xRoundup. */
19113  nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19114  if( nOld==nNew ){
19115    pNew = pOld;
19116  }else if( sqlite3GlobalConfig.bMemstat ){
19117    sqlite3_mutex_enter(mem0.mutex);
19118    sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19119    nDiff = nNew - nOld;
19120    if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
19121          mem0.alarmThreshold-nDiff ){
19122      sqlite3MallocAlarm(nDiff);
19123    }
19124    assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19125    assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19126    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19127    if( pNew==0 && mem0.alarmCallback ){
19128      sqlite3MallocAlarm(nBytes);
19129      pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19130    }
19131    if( pNew ){
19132      nNew = sqlite3MallocSize(pNew);
19133      sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19134    }
19135    sqlite3_mutex_leave(mem0.mutex);
19136  }else{
19137    pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19138  }
19139  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19140  return pNew;
19141}
19142
19143/*
19144** The public interface to sqlite3Realloc.  Make sure that the memory
19145** subsystem is initialized prior to invoking sqliteRealloc.
19146*/
19147SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19148#ifndef SQLITE_OMIT_AUTOINIT
19149  if( sqlite3_initialize() ) return 0;
19150#endif
19151  return sqlite3Realloc(pOld, n);
19152}
19153
19154
19155/*
19156** Allocate and zero memory.
19157*/
19158SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19159  void *p = sqlite3Malloc(n);
19160  if( p ){
19161    memset(p, 0, n);
19162  }
19163  return p;
19164}
19165
19166/*
19167** Allocate and zero memory.  If the allocation fails, make
19168** the mallocFailed flag in the connection pointer.
19169*/
19170SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19171  void *p = sqlite3DbMallocRaw(db, n);
19172  if( p ){
19173    memset(p, 0, n);
19174  }
19175  return p;
19176}
19177
19178/*
19179** Allocate and zero memory.  If the allocation fails, make
19180** the mallocFailed flag in the connection pointer.
19181**
19182** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19183** failure on the same database connection) then always return 0.
19184** Hence for a particular database connection, once malloc starts
19185** failing, it fails consistently until mallocFailed is reset.
19186** This is an important assumption.  There are many places in the
19187** code that do things like this:
19188**
19189**         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19190**         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19191**         if( b ) a[10] = 9;
19192**
19193** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19194** that all prior mallocs (ex: "a") worked too.
19195*/
19196SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19197  void *p;
19198  assert( db==0 || sqlite3_mutex_held(db->mutex) );
19199  assert( db==0 || db->pnBytesFreed==0 );
19200#ifndef SQLITE_OMIT_LOOKASIDE
19201  if( db ){
19202    LookasideSlot *pBuf;
19203    if( db->mallocFailed ){
19204      return 0;
19205    }
19206    if( db->lookaside.bEnabled ){
19207      if( n>db->lookaside.sz ){
19208        db->lookaside.anStat[1]++;
19209      }else if( (pBuf = db->lookaside.pFree)==0 ){
19210        db->lookaside.anStat[2]++;
19211      }else{
19212        db->lookaside.pFree = pBuf->pNext;
19213        db->lookaside.nOut++;
19214        db->lookaside.anStat[0]++;
19215        if( db->lookaside.nOut>db->lookaside.mxOut ){
19216          db->lookaside.mxOut = db->lookaside.nOut;
19217        }
19218        return (void*)pBuf;
19219      }
19220    }
19221  }
19222#else
19223  if( db && db->mallocFailed ){
19224    return 0;
19225  }
19226#endif
19227  p = sqlite3Malloc(n);
19228  if( !p && db ){
19229    db->mallocFailed = 1;
19230  }
19231  sqlite3MemdebugSetType(p, MEMTYPE_DB |
19232         ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19233  return p;
19234}
19235
19236/*
19237** Resize the block of memory pointed to by p to n bytes. If the
19238** resize fails, set the mallocFailed flag in the connection object.
19239*/
19240SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19241  void *pNew = 0;
19242  assert( db!=0 );
19243  assert( sqlite3_mutex_held(db->mutex) );
19244  if( db->mallocFailed==0 ){
19245    if( p==0 ){
19246      return sqlite3DbMallocRaw(db, n);
19247    }
19248    if( isLookaside(db, p) ){
19249      if( n<=db->lookaside.sz ){
19250        return p;
19251      }
19252      pNew = sqlite3DbMallocRaw(db, n);
19253      if( pNew ){
19254        memcpy(pNew, p, db->lookaside.sz);
19255        sqlite3DbFree(db, p);
19256      }
19257    }else{
19258      assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19259      assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19260      sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19261      pNew = sqlite3_realloc(p, n);
19262      if( !pNew ){
19263        sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19264        db->mallocFailed = 1;
19265      }
19266      sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
19267            (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19268    }
19269  }
19270  return pNew;
19271}
19272
19273/*
19274** Attempt to reallocate p.  If the reallocation fails, then free p
19275** and set the mallocFailed flag in the database connection.
19276*/
19277SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19278  void *pNew;
19279  pNew = sqlite3DbRealloc(db, p, n);
19280  if( !pNew ){
19281    sqlite3DbFree(db, p);
19282  }
19283  return pNew;
19284}
19285
19286/*
19287** Make a copy of a string in memory obtained from sqliteMalloc(). These
19288** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19289** is because when memory debugging is turned on, these two functions are
19290** called via macros that record the current file and line number in the
19291** ThreadData structure.
19292*/
19293SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19294  char *zNew;
19295  size_t n;
19296  if( z==0 ){
19297    return 0;
19298  }
19299  n = sqlite3Strlen30(z) + 1;
19300  assert( (n&0x7fffffff)==n );
19301  zNew = sqlite3DbMallocRaw(db, (int)n);
19302  if( zNew ){
19303    memcpy(zNew, z, n);
19304  }
19305  return zNew;
19306}
19307SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19308  char *zNew;
19309  if( z==0 ){
19310    return 0;
19311  }
19312  assert( (n&0x7fffffff)==n );
19313  zNew = sqlite3DbMallocRaw(db, n+1);
19314  if( zNew ){
19315    memcpy(zNew, z, n);
19316    zNew[n] = 0;
19317  }
19318  return zNew;
19319}
19320
19321/*
19322** Create a string from the zFromat argument and the va_list that follows.
19323** Store the string in memory obtained from sqliteMalloc() and make *pz
19324** point to that string.
19325*/
19326SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19327  va_list ap;
19328  char *z;
19329
19330  va_start(ap, zFormat);
19331  z = sqlite3VMPrintf(db, zFormat, ap);
19332  va_end(ap);
19333  sqlite3DbFree(db, *pz);
19334  *pz = z;
19335}
19336
19337
19338/*
19339** This function must be called before exiting any API function (i.e.
19340** returning control to the user) that has called sqlite3_malloc or
19341** sqlite3_realloc.
19342**
19343** The returned value is normally a copy of the second argument to this
19344** function. However, if a malloc() failure has occurred since the previous
19345** invocation SQLITE_NOMEM is returned instead.
19346**
19347** If the first argument, db, is not NULL and a malloc() error has occurred,
19348** then the connection error-code (the value returned by sqlite3_errcode())
19349** is set to SQLITE_NOMEM.
19350*/
19351SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19352  /* If the db handle is not NULL, then we must hold the connection handle
19353  ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
19354  ** is unsafe, as is the call to sqlite3Error().
19355  */
19356  assert( !db || sqlite3_mutex_held(db->mutex) );
19357  if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19358    sqlite3Error(db, SQLITE_NOMEM, 0);
19359    db->mallocFailed = 0;
19360    rc = SQLITE_NOMEM;
19361  }
19362  return rc & (db ? db->errMask : 0xff);
19363}
19364
19365/************** End of malloc.c **********************************************/
19366/************** Begin file printf.c ******************************************/
19367/*
19368** The "printf" code that follows dates from the 1980's.  It is in
19369** the public domain.  The original comments are included here for
19370** completeness.  They are very out-of-date but might be useful as
19371** an historical reference.  Most of the "enhancements" have been backed
19372** out so that the functionality is now the same as standard printf().
19373**
19374**************************************************************************
19375**
19376** This file contains code for a set of "printf"-like routines.  These
19377** routines format strings much like the printf() from the standard C
19378** library, though the implementation here has enhancements to support
19379** SQLlite.
19380*/
19381
19382/*
19383** Conversion types fall into various categories as defined by the
19384** following enumeration.
19385*/
19386#define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19387#define etFLOAT       2 /* Floating point.  %f */
19388#define etEXP         3 /* Exponentional notation. %e and %E */
19389#define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19390#define etSIZE        5 /* Return number of characters processed so far. %n */
19391#define etSTRING      6 /* Strings. %s */
19392#define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19393#define etPERCENT     8 /* Percent symbol. %% */
19394#define etCHARX       9 /* Characters. %c */
19395/* The rest are extensions, not normally found in printf() */
19396#define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19397#define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19398                          NULL pointers replaced by SQL NULL.  %Q */
19399#define etTOKEN      12 /* a pointer to a Token structure */
19400#define etSRCLIST    13 /* a pointer to a SrcList */
19401#define etPOINTER    14 /* The %p conversion */
19402#define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19403#define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19404
19405#define etINVALID     0 /* Any unrecognized conversion type */
19406
19407
19408/*
19409** An "etByte" is an 8-bit unsigned value.
19410*/
19411typedef unsigned char etByte;
19412
19413/*
19414** Each builtin conversion character (ex: the 'd' in "%d") is described
19415** by an instance of the following structure
19416*/
19417typedef struct et_info {   /* Information about each format field */
19418  char fmttype;            /* The format field code letter */
19419  etByte base;             /* The base for radix conversion */
19420  etByte flags;            /* One or more of FLAG_ constants below */
19421  etByte type;             /* Conversion paradigm */
19422  etByte charset;          /* Offset into aDigits[] of the digits string */
19423  etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19424} et_info;
19425
19426/*
19427** Allowed values for et_info.flags
19428*/
19429#define FLAG_SIGNED  1     /* True if the value to convert is signed */
19430#define FLAG_INTERN  2     /* True if for internal use only */
19431#define FLAG_STRING  4     /* Allow infinity precision */
19432
19433
19434/*
19435** The following table is searched linearly, so it is good to put the
19436** most frequently used conversion types first.
19437*/
19438static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19439static const char aPrefix[] = "-x0\000X0";
19440static const et_info fmtinfo[] = {
19441  {  'd', 10, 1, etRADIX,      0,  0 },
19442  {  's',  0, 4, etSTRING,     0,  0 },
19443  {  'g',  0, 1, etGENERIC,    30, 0 },
19444  {  'z',  0, 4, etDYNSTRING,  0,  0 },
19445  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19446  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19447  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19448  {  'c',  0, 0, etCHARX,      0,  0 },
19449  {  'o',  8, 0, etRADIX,      0,  2 },
19450  {  'u', 10, 0, etRADIX,      0,  0 },
19451  {  'x', 16, 0, etRADIX,      16, 1 },
19452  {  'X', 16, 0, etRADIX,      0,  4 },
19453#ifndef SQLITE_OMIT_FLOATING_POINT
19454  {  'f',  0, 1, etFLOAT,      0,  0 },
19455  {  'e',  0, 1, etEXP,        30, 0 },
19456  {  'E',  0, 1, etEXP,        14, 0 },
19457  {  'G',  0, 1, etGENERIC,    14, 0 },
19458#endif
19459  {  'i', 10, 1, etRADIX,      0,  0 },
19460  {  'n',  0, 0, etSIZE,       0,  0 },
19461  {  '%',  0, 0, etPERCENT,    0,  0 },
19462  {  'p', 16, 0, etPOINTER,    0,  1 },
19463
19464/* All the rest have the FLAG_INTERN bit set and are thus for internal
19465** use only */
19466  {  'T',  0, 2, etTOKEN,      0,  0 },
19467  {  'S',  0, 2, etSRCLIST,    0,  0 },
19468  {  'r', 10, 3, etORDINAL,    0,  0 },
19469};
19470
19471/*
19472** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19473** conversions will work.
19474*/
19475#ifndef SQLITE_OMIT_FLOATING_POINT
19476/*
19477** "*val" is a double such that 0.1 <= *val < 10.0
19478** Return the ascii code for the leading digit of *val, then
19479** multiply "*val" by 10.0 to renormalize.
19480**
19481** Example:
19482**     input:     *val = 3.14159
19483**     output:    *val = 1.4159    function return = '3'
19484**
19485** The counter *cnt is incremented each time.  After counter exceeds
19486** 16 (the number of significant digits in a 64-bit float) '0' is
19487** always returned.
19488*/
19489static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19490  int digit;
19491  LONGDOUBLE_TYPE d;
19492  if( (*cnt)++ >= 16 ) return '0';
19493  digit = (int)*val;
19494  d = digit;
19495  digit += '0';
19496  *val = (*val - d)*10.0;
19497  return (char)digit;
19498}
19499#endif /* SQLITE_OMIT_FLOATING_POINT */
19500
19501/*
19502** Append N space characters to the given string buffer.
19503*/
19504SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19505  static const char zSpaces[] = "                             ";
19506  while( N>=(int)sizeof(zSpaces)-1 ){
19507    sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19508    N -= sizeof(zSpaces)-1;
19509  }
19510  if( N>0 ){
19511    sqlite3StrAccumAppend(pAccum, zSpaces, N);
19512  }
19513}
19514
19515/*
19516** On machines with a small stack size, you can redefine the
19517** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19518*/
19519#ifndef SQLITE_PRINT_BUF_SIZE
19520# define SQLITE_PRINT_BUF_SIZE 70
19521#endif
19522#define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19523
19524/*
19525** Render a string given by "fmt" into the StrAccum object.
19526*/
19527SQLITE_PRIVATE void sqlite3VXPrintf(
19528  StrAccum *pAccum,                  /* Accumulate results here */
19529  int useExtended,                   /* Allow extended %-conversions */
19530  const char *fmt,                   /* Format string */
19531  va_list ap                         /* arguments */
19532){
19533  int c;                     /* Next character in the format string */
19534  char *bufpt;               /* Pointer to the conversion buffer */
19535  int precision;             /* Precision of the current field */
19536  int length;                /* Length of the field */
19537  int idx;                   /* A general purpose loop counter */
19538  int width;                 /* Width of the current field */
19539  etByte flag_leftjustify;   /* True if "-" flag is present */
19540  etByte flag_plussign;      /* True if "+" flag is present */
19541  etByte flag_blanksign;     /* True if " " flag is present */
19542  etByte flag_alternateform; /* True if "#" flag is present */
19543  etByte flag_altform2;      /* True if "!" flag is present */
19544  etByte flag_zeropad;       /* True if field width constant starts with zero */
19545  etByte flag_long;          /* True if "l" flag is present */
19546  etByte flag_longlong;      /* True if the "ll" flag is present */
19547  etByte done;               /* Loop termination flag */
19548  etByte xtype = 0;          /* Conversion paradigm */
19549  char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19550  sqlite_uint64 longvalue;   /* Value for integer types */
19551  LONGDOUBLE_TYPE realvalue; /* Value for real types */
19552  const et_info *infop;      /* Pointer to the appropriate info structure */
19553  char *zOut;                /* Rendering buffer */
19554  int nOut;                  /* Size of the rendering buffer */
19555  char *zExtra;              /* Malloced memory used by some conversion */
19556#ifndef SQLITE_OMIT_FLOATING_POINT
19557  int  exp, e2;              /* exponent of real numbers */
19558  int nsd;                   /* Number of significant digits returned */
19559  double rounder;            /* Used for rounding floating point values */
19560  etByte flag_dp;            /* True if decimal point should be shown */
19561  etByte flag_rtz;           /* True if trailing zeros should be removed */
19562#endif
19563  char buf[etBUFSIZE];       /* Conversion buffer */
19564
19565  bufpt = 0;
19566  for(; (c=(*fmt))!=0; ++fmt){
19567    if( c!='%' ){
19568      int amt;
19569      bufpt = (char *)fmt;
19570      amt = 1;
19571      while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19572      sqlite3StrAccumAppend(pAccum, bufpt, amt);
19573      if( c==0 ) break;
19574    }
19575    if( (c=(*++fmt))==0 ){
19576      sqlite3StrAccumAppend(pAccum, "%", 1);
19577      break;
19578    }
19579    /* Find out what flags are present */
19580    flag_leftjustify = flag_plussign = flag_blanksign =
19581     flag_alternateform = flag_altform2 = flag_zeropad = 0;
19582    done = 0;
19583    do{
19584      switch( c ){
19585        case '-':   flag_leftjustify = 1;     break;
19586        case '+':   flag_plussign = 1;        break;
19587        case ' ':   flag_blanksign = 1;       break;
19588        case '#':   flag_alternateform = 1;   break;
19589        case '!':   flag_altform2 = 1;        break;
19590        case '0':   flag_zeropad = 1;         break;
19591        default:    done = 1;                 break;
19592      }
19593    }while( !done && (c=(*++fmt))!=0 );
19594    /* Get the field width */
19595    width = 0;
19596    if( c=='*' ){
19597      width = va_arg(ap,int);
19598      if( width<0 ){
19599        flag_leftjustify = 1;
19600        width = -width;
19601      }
19602      c = *++fmt;
19603    }else{
19604      while( c>='0' && c<='9' ){
19605        width = width*10 + c - '0';
19606        c = *++fmt;
19607      }
19608    }
19609    /* Get the precision */
19610    if( c=='.' ){
19611      precision = 0;
19612      c = *++fmt;
19613      if( c=='*' ){
19614        precision = va_arg(ap,int);
19615        if( precision<0 ) precision = -precision;
19616        c = *++fmt;
19617      }else{
19618        while( c>='0' && c<='9' ){
19619          precision = precision*10 + c - '0';
19620          c = *++fmt;
19621        }
19622      }
19623    }else{
19624      precision = -1;
19625    }
19626    /* Get the conversion type modifier */
19627    if( c=='l' ){
19628      flag_long = 1;
19629      c = *++fmt;
19630      if( c=='l' ){
19631        flag_longlong = 1;
19632        c = *++fmt;
19633      }else{
19634        flag_longlong = 0;
19635      }
19636    }else{
19637      flag_long = flag_longlong = 0;
19638    }
19639    /* Fetch the info entry for the field */
19640    infop = &fmtinfo[0];
19641    xtype = etINVALID;
19642    for(idx=0; idx<ArraySize(fmtinfo); idx++){
19643      if( c==fmtinfo[idx].fmttype ){
19644        infop = &fmtinfo[idx];
19645        if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19646          xtype = infop->type;
19647        }else{
19648          return;
19649        }
19650        break;
19651      }
19652    }
19653    zExtra = 0;
19654
19655    /*
19656    ** At this point, variables are initialized as follows:
19657    **
19658    **   flag_alternateform          TRUE if a '#' is present.
19659    **   flag_altform2               TRUE if a '!' is present.
19660    **   flag_plussign               TRUE if a '+' is present.
19661    **   flag_leftjustify            TRUE if a '-' is present or if the
19662    **                               field width was negative.
19663    **   flag_zeropad                TRUE if the width began with 0.
19664    **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19665    **                               the conversion character.
19666    **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19667    **                               the conversion character.
19668    **   flag_blanksign              TRUE if a ' ' is present.
19669    **   width                       The specified field width.  This is
19670    **                               always non-negative.  Zero is the default.
19671    **   precision                   The specified precision.  The default
19672    **                               is -1.
19673    **   xtype                       The class of the conversion.
19674    **   infop                       Pointer to the appropriate info struct.
19675    */
19676    switch( xtype ){
19677      case etPOINTER:
19678        flag_longlong = sizeof(char*)==sizeof(i64);
19679        flag_long = sizeof(char*)==sizeof(long int);
19680        /* Fall through into the next case */
19681      case etORDINAL:
19682      case etRADIX:
19683        if( infop->flags & FLAG_SIGNED ){
19684          i64 v;
19685          if( flag_longlong ){
19686            v = va_arg(ap,i64);
19687          }else if( flag_long ){
19688            v = va_arg(ap,long int);
19689          }else{
19690            v = va_arg(ap,int);
19691          }
19692          if( v<0 ){
19693            if( v==SMALLEST_INT64 ){
19694              longvalue = ((u64)1)<<63;
19695            }else{
19696              longvalue = -v;
19697            }
19698            prefix = '-';
19699          }else{
19700            longvalue = v;
19701            if( flag_plussign )        prefix = '+';
19702            else if( flag_blanksign )  prefix = ' ';
19703            else                       prefix = 0;
19704          }
19705        }else{
19706          if( flag_longlong ){
19707            longvalue = va_arg(ap,u64);
19708          }else if( flag_long ){
19709            longvalue = va_arg(ap,unsigned long int);
19710          }else{
19711            longvalue = va_arg(ap,unsigned int);
19712          }
19713          prefix = 0;
19714        }
19715        if( longvalue==0 ) flag_alternateform = 0;
19716        if( flag_zeropad && precision<width-(prefix!=0) ){
19717          precision = width-(prefix!=0);
19718        }
19719        if( precision<etBUFSIZE-10 ){
19720          nOut = etBUFSIZE;
19721          zOut = buf;
19722        }else{
19723          nOut = precision + 10;
19724          zOut = zExtra = sqlite3Malloc( nOut );
19725          if( zOut==0 ){
19726            pAccum->mallocFailed = 1;
19727            return;
19728          }
19729        }
19730        bufpt = &zOut[nOut-1];
19731        if( xtype==etORDINAL ){
19732          static const char zOrd[] = "thstndrd";
19733          int x = (int)(longvalue % 10);
19734          if( x>=4 || (longvalue/10)%10==1 ){
19735            x = 0;
19736          }
19737          *(--bufpt) = zOrd[x*2+1];
19738          *(--bufpt) = zOrd[x*2];
19739        }
19740        {
19741          register const char *cset;      /* Use registers for speed */
19742          register int base;
19743          cset = &aDigits[infop->charset];
19744          base = infop->base;
19745          do{                                           /* Convert to ascii */
19746            *(--bufpt) = cset[longvalue%base];
19747            longvalue = longvalue/base;
19748          }while( longvalue>0 );
19749        }
19750        length = (int)(&zOut[nOut-1]-bufpt);
19751        for(idx=precision-length; idx>0; idx--){
19752          *(--bufpt) = '0';                             /* Zero pad */
19753        }
19754        if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19755        if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19756          const char *pre;
19757          char x;
19758          pre = &aPrefix[infop->prefix];
19759          for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19760        }
19761        length = (int)(&zOut[nOut-1]-bufpt);
19762        break;
19763      case etFLOAT:
19764      case etEXP:
19765      case etGENERIC:
19766        realvalue = va_arg(ap,double);
19767#ifdef SQLITE_OMIT_FLOATING_POINT
19768        length = 0;
19769#else
19770        if( precision<0 ) precision = 6;         /* Set default precision */
19771        if( realvalue<0.0 ){
19772          realvalue = -realvalue;
19773          prefix = '-';
19774        }else{
19775          if( flag_plussign )          prefix = '+';
19776          else if( flag_blanksign )    prefix = ' ';
19777          else                         prefix = 0;
19778        }
19779        if( xtype==etGENERIC && precision>0 ) precision--;
19780#if 0
19781        /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19782        for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19783#else
19784        /* It makes more sense to use 0.5 */
19785        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19786#endif
19787        if( xtype==etFLOAT ) realvalue += rounder;
19788        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19789        exp = 0;
19790        if( sqlite3IsNaN((double)realvalue) ){
19791          bufpt = "NaN";
19792          length = 3;
19793          break;
19794        }
19795        if( realvalue>0.0 ){
19796          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
19797          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
19798          while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
19799          while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19800          while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19801          if( exp>350 ){
19802            if( prefix=='-' ){
19803              bufpt = "-Inf";
19804            }else if( prefix=='+' ){
19805              bufpt = "+Inf";
19806            }else{
19807              bufpt = "Inf";
19808            }
19809            length = sqlite3Strlen30(bufpt);
19810            break;
19811          }
19812        }
19813        bufpt = buf;
19814        /*
19815        ** If the field type is etGENERIC, then convert to either etEXP
19816        ** or etFLOAT, as appropriate.
19817        */
19818        if( xtype!=etFLOAT ){
19819          realvalue += rounder;
19820          if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
19821        }
19822        if( xtype==etGENERIC ){
19823          flag_rtz = !flag_alternateform;
19824          if( exp<-4 || exp>precision ){
19825            xtype = etEXP;
19826          }else{
19827            precision = precision - exp;
19828            xtype = etFLOAT;
19829          }
19830        }else{
19831          flag_rtz = 0;
19832        }
19833        if( xtype==etEXP ){
19834          e2 = 0;
19835        }else{
19836          e2 = exp;
19837        }
19838        if( e2+precision+width > etBUFSIZE - 15 ){
19839          bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
19840          if( bufpt==0 ){
19841            pAccum->mallocFailed = 1;
19842            return;
19843          }
19844        }
19845        zOut = bufpt;
19846        nsd = 0;
19847        flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
19848        /* The sign in front of the number */
19849        if( prefix ){
19850          *(bufpt++) = prefix;
19851        }
19852        /* Digits prior to the decimal point */
19853        if( e2<0 ){
19854          *(bufpt++) = '0';
19855        }else{
19856          for(; e2>=0; e2--){
19857            *(bufpt++) = et_getdigit(&realvalue,&nsd);
19858          }
19859        }
19860        /* The decimal point */
19861        if( flag_dp ){
19862          *(bufpt++) = '.';
19863        }
19864        /* "0" digits after the decimal point but before the first
19865        ** significant digit of the number */
19866        for(e2++; e2<0; precision--, e2++){
19867          assert( precision>0 );
19868          *(bufpt++) = '0';
19869        }
19870        /* Significant digits after the decimal point */
19871        while( (precision--)>0 ){
19872          *(bufpt++) = et_getdigit(&realvalue,&nsd);
19873        }
19874        /* Remove trailing zeros and the "." if no digits follow the "." */
19875        if( flag_rtz && flag_dp ){
19876          while( bufpt[-1]=='0' ) *(--bufpt) = 0;
19877          assert( bufpt>zOut );
19878          if( bufpt[-1]=='.' ){
19879            if( flag_altform2 ){
19880              *(bufpt++) = '0';
19881            }else{
19882              *(--bufpt) = 0;
19883            }
19884          }
19885        }
19886        /* Add the "eNNN" suffix */
19887        if( xtype==etEXP ){
19888          *(bufpt++) = aDigits[infop->charset];
19889          if( exp<0 ){
19890            *(bufpt++) = '-'; exp = -exp;
19891          }else{
19892            *(bufpt++) = '+';
19893          }
19894          if( exp>=100 ){
19895            *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
19896            exp %= 100;
19897          }
19898          *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
19899          *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
19900        }
19901        *bufpt = 0;
19902
19903        /* The converted number is in buf[] and zero terminated. Output it.
19904        ** Note that the number is in the usual order, not reversed as with
19905        ** integer conversions. */
19906        length = (int)(bufpt-zOut);
19907        bufpt = zOut;
19908
19909        /* Special case:  Add leading zeros if the flag_zeropad flag is
19910        ** set and we are not left justified */
19911        if( flag_zeropad && !flag_leftjustify && length < width){
19912          int i;
19913          int nPad = width - length;
19914          for(i=width; i>=nPad; i--){
19915            bufpt[i] = bufpt[i-nPad];
19916          }
19917          i = prefix!=0;
19918          while( nPad-- ) bufpt[i++] = '0';
19919          length = width;
19920        }
19921#endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
19922        break;
19923      case etSIZE:
19924        *(va_arg(ap,int*)) = pAccum->nChar;
19925        length = width = 0;
19926        break;
19927      case etPERCENT:
19928        buf[0] = '%';
19929        bufpt = buf;
19930        length = 1;
19931        break;
19932      case etCHARX:
19933        c = va_arg(ap,int);
19934        buf[0] = (char)c;
19935        if( precision>=0 ){
19936          for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
19937          length = precision;
19938        }else{
19939          length =1;
19940        }
19941        bufpt = buf;
19942        break;
19943      case etSTRING:
19944      case etDYNSTRING:
19945        bufpt = va_arg(ap,char*);
19946        if( bufpt==0 ){
19947          bufpt = "";
19948        }else if( xtype==etDYNSTRING ){
19949          zExtra = bufpt;
19950        }
19951        if( precision>=0 ){
19952          for(length=0; length<precision && bufpt[length]; length++){}
19953        }else{
19954          length = sqlite3Strlen30(bufpt);
19955        }
19956        break;
19957      case etSQLESCAPE:
19958      case etSQLESCAPE2:
19959      case etSQLESCAPE3: {
19960        int i, j, k, n, isnull;
19961        int needQuote;
19962        char ch;
19963        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
19964        char *escarg = va_arg(ap,char*);
19965        isnull = escarg==0;
19966        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
19967        k = precision;
19968        for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
19969          if( ch==q )  n++;
19970        }
19971        needQuote = !isnull && xtype==etSQLESCAPE2;
19972        n += i + 1 + needQuote*2;
19973        if( n>etBUFSIZE ){
19974          bufpt = zExtra = sqlite3Malloc( n );
19975          if( bufpt==0 ){
19976            pAccum->mallocFailed = 1;
19977            return;
19978          }
19979        }else{
19980          bufpt = buf;
19981        }
19982        j = 0;
19983        if( needQuote ) bufpt[j++] = q;
19984        k = i;
19985        for(i=0; i<k; i++){
19986          bufpt[j++] = ch = escarg[i];
19987          if( ch==q ) bufpt[j++] = ch;
19988        }
19989        if( needQuote ) bufpt[j++] = q;
19990        bufpt[j] = 0;
19991        length = j;
19992        /* The precision in %q and %Q means how many input characters to
19993        ** consume, not the length of the output...
19994        ** if( precision>=0 && precision<length ) length = precision; */
19995        break;
19996      }
19997      case etTOKEN: {
19998        Token *pToken = va_arg(ap, Token*);
19999        if( pToken ){
20000          sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20001        }
20002        length = width = 0;
20003        break;
20004      }
20005      case etSRCLIST: {
20006        SrcList *pSrc = va_arg(ap, SrcList*);
20007        int k = va_arg(ap, int);
20008        struct SrcList_item *pItem = &pSrc->a[k];
20009        assert( k>=0 && k<pSrc->nSrc );
20010        if( pItem->zDatabase ){
20011          sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20012          sqlite3StrAccumAppend(pAccum, ".", 1);
20013        }
20014        sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20015        length = width = 0;
20016        break;
20017      }
20018      default: {
20019        assert( xtype==etINVALID );
20020        return;
20021      }
20022    }/* End switch over the format type */
20023    /*
20024    ** The text of the conversion is pointed to by "bufpt" and is
20025    ** "length" characters long.  The field width is "width".  Do
20026    ** the output.
20027    */
20028    if( !flag_leftjustify ){
20029      register int nspace;
20030      nspace = width-length;
20031      if( nspace>0 ){
20032        sqlite3AppendSpace(pAccum, nspace);
20033      }
20034    }
20035    if( length>0 ){
20036      sqlite3StrAccumAppend(pAccum, bufpt, length);
20037    }
20038    if( flag_leftjustify ){
20039      register int nspace;
20040      nspace = width-length;
20041      if( nspace>0 ){
20042        sqlite3AppendSpace(pAccum, nspace);
20043      }
20044    }
20045    sqlite3_free(zExtra);
20046  }/* End for loop over the format string */
20047} /* End of function */
20048
20049/*
20050** Append N bytes of text from z to the StrAccum object.
20051*/
20052SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20053  assert( z!=0 || N==0 );
20054  if( p->tooBig | p->mallocFailed ){
20055    testcase(p->tooBig);
20056    testcase(p->mallocFailed);
20057    return;
20058  }
20059  assert( p->zText!=0 || p->nChar==0 );
20060  if( N<0 ){
20061    N = sqlite3Strlen30(z);
20062  }
20063  if( N==0 || NEVER(z==0) ){
20064    return;
20065  }
20066  if( p->nChar+N >= p->nAlloc ){
20067    char *zNew;
20068    if( !p->useMalloc ){
20069      p->tooBig = 1;
20070      N = p->nAlloc - p->nChar - 1;
20071      if( N<=0 ){
20072        return;
20073      }
20074    }else{
20075      char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20076      i64 szNew = p->nChar;
20077      szNew += N + 1;
20078      if( szNew > p->mxAlloc ){
20079        sqlite3StrAccumReset(p);
20080        p->tooBig = 1;
20081        return;
20082      }else{
20083        p->nAlloc = (int)szNew;
20084      }
20085      if( p->useMalloc==1 ){
20086        zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20087      }else{
20088        zNew = sqlite3_realloc(zOld, p->nAlloc);
20089      }
20090      if( zNew ){
20091        if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20092        p->zText = zNew;
20093      }else{
20094        p->mallocFailed = 1;
20095        sqlite3StrAccumReset(p);
20096        return;
20097      }
20098    }
20099  }
20100  assert( p->zText );
20101  memcpy(&p->zText[p->nChar], z, N);
20102  p->nChar += N;
20103}
20104
20105/*
20106** Finish off a string by making sure it is zero-terminated.
20107** Return a pointer to the resulting string.  Return a NULL
20108** pointer if any kind of error was encountered.
20109*/
20110SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20111  if( p->zText ){
20112    p->zText[p->nChar] = 0;
20113    if( p->useMalloc && p->zText==p->zBase ){
20114      if( p->useMalloc==1 ){
20115        p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20116      }else{
20117        p->zText = sqlite3_malloc(p->nChar+1);
20118      }
20119      if( p->zText ){
20120        memcpy(p->zText, p->zBase, p->nChar+1);
20121      }else{
20122        p->mallocFailed = 1;
20123      }
20124    }
20125  }
20126  return p->zText;
20127}
20128
20129/*
20130** Reset an StrAccum string.  Reclaim all malloced memory.
20131*/
20132SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20133  if( p->zText!=p->zBase ){
20134    if( p->useMalloc==1 ){
20135      sqlite3DbFree(p->db, p->zText);
20136    }else{
20137      sqlite3_free(p->zText);
20138    }
20139  }
20140  p->zText = 0;
20141}
20142
20143/*
20144** Initialize a string accumulator
20145*/
20146SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20147  p->zText = p->zBase = zBase;
20148  p->db = 0;
20149  p->nChar = 0;
20150  p->nAlloc = n;
20151  p->mxAlloc = mx;
20152  p->useMalloc = 1;
20153  p->tooBig = 0;
20154  p->mallocFailed = 0;
20155}
20156
20157/*
20158** Print into memory obtained from sqliteMalloc().  Use the internal
20159** %-conversion extensions.
20160*/
20161SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20162  char *z;
20163  char zBase[SQLITE_PRINT_BUF_SIZE];
20164  StrAccum acc;
20165  assert( db!=0 );
20166  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20167                      db->aLimit[SQLITE_LIMIT_LENGTH]);
20168  acc.db = db;
20169  sqlite3VXPrintf(&acc, 1, zFormat, ap);
20170  z = sqlite3StrAccumFinish(&acc);
20171  if( acc.mallocFailed ){
20172    db->mallocFailed = 1;
20173  }
20174  return z;
20175}
20176
20177/*
20178** Print into memory obtained from sqliteMalloc().  Use the internal
20179** %-conversion extensions.
20180*/
20181SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20182  va_list ap;
20183  char *z;
20184  va_start(ap, zFormat);
20185  z = sqlite3VMPrintf(db, zFormat, ap);
20186  va_end(ap);
20187  return z;
20188}
20189
20190/*
20191** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20192** the string and before returnning.  This routine is intended to be used
20193** to modify an existing string.  For example:
20194**
20195**       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20196**
20197*/
20198SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20199  va_list ap;
20200  char *z;
20201  va_start(ap, zFormat);
20202  z = sqlite3VMPrintf(db, zFormat, ap);
20203  va_end(ap);
20204  sqlite3DbFree(db, zStr);
20205  return z;
20206}
20207
20208/*
20209** Print into memory obtained from sqlite3_malloc().  Omit the internal
20210** %-conversion extensions.
20211*/
20212SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20213  char *z;
20214  char zBase[SQLITE_PRINT_BUF_SIZE];
20215  StrAccum acc;
20216#ifndef SQLITE_OMIT_AUTOINIT
20217  if( sqlite3_initialize() ) return 0;
20218#endif
20219  sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20220  acc.useMalloc = 2;
20221  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20222  z = sqlite3StrAccumFinish(&acc);
20223  return z;
20224}
20225
20226/*
20227** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20228** %-conversion extensions.
20229*/
20230SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20231  va_list ap;
20232  char *z;
20233#ifndef SQLITE_OMIT_AUTOINIT
20234  if( sqlite3_initialize() ) return 0;
20235#endif
20236  va_start(ap, zFormat);
20237  z = sqlite3_vmprintf(zFormat, ap);
20238  va_end(ap);
20239  return z;
20240}
20241
20242/*
20243** sqlite3_snprintf() works like snprintf() except that it ignores the
20244** current locale settings.  This is important for SQLite because we
20245** are not able to use a "," as the decimal point in place of "." as
20246** specified by some locales.
20247**
20248** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20249** from the snprintf() standard.  Unfortunately, it is too late to change
20250** this without breaking compatibility, so we just have to live with the
20251** mistake.
20252**
20253** sqlite3_vsnprintf() is the varargs version.
20254*/
20255SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20256  StrAccum acc;
20257  if( n<=0 ) return zBuf;
20258  sqlite3StrAccumInit(&acc, zBuf, n, 0);
20259  acc.useMalloc = 0;
20260  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20261  return sqlite3StrAccumFinish(&acc);
20262}
20263SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20264  char *z;
20265  va_list ap;
20266  va_start(ap,zFormat);
20267  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20268  va_end(ap);
20269  return z;
20270}
20271
20272/*
20273** This is the routine that actually formats the sqlite3_log() message.
20274** We house it in a separate routine from sqlite3_log() to avoid using
20275** stack space on small-stack systems when logging is disabled.
20276**
20277** sqlite3_log() must render into a static buffer.  It cannot dynamically
20278** allocate memory because it might be called while the memory allocator
20279** mutex is held.
20280*/
20281static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20282  StrAccum acc;                          /* String accumulator */
20283  char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20284
20285  sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20286  acc.useMalloc = 0;
20287  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20288  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20289                           sqlite3StrAccumFinish(&acc));
20290}
20291
20292/*
20293** Format and write a message to the log if logging is enabled.
20294*/
20295SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20296  va_list ap;                             /* Vararg list */
20297  if( sqlite3GlobalConfig.xLog ){
20298    va_start(ap, zFormat);
20299    renderLogMsg(iErrCode, zFormat, ap);
20300    va_end(ap);
20301  }
20302}
20303
20304#if defined(SQLITE_DEBUG)
20305/*
20306** A version of printf() that understands %lld.  Used for debugging.
20307** The printf() built into some versions of windows does not understand %lld
20308** and segfaults if you give it a long long int.
20309*/
20310SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20311  va_list ap;
20312  StrAccum acc;
20313  char zBuf[500];
20314  sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20315  acc.useMalloc = 0;
20316  va_start(ap,zFormat);
20317  sqlite3VXPrintf(&acc, 0, zFormat, ap);
20318  va_end(ap);
20319  sqlite3StrAccumFinish(&acc);
20320  fprintf(stdout,"%s", zBuf);
20321  fflush(stdout);
20322}
20323#endif
20324
20325#ifndef SQLITE_OMIT_TRACE
20326/*
20327** variable-argument wrapper around sqlite3VXPrintf().
20328*/
20329SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20330  va_list ap;
20331  va_start(ap,zFormat);
20332  sqlite3VXPrintf(p, 1, zFormat, ap);
20333  va_end(ap);
20334}
20335#endif
20336
20337/************** End of printf.c **********************************************/
20338/************** Begin file random.c ******************************************/
20339/*
20340** 2001 September 15
20341**
20342** The author disclaims copyright to this source code.  In place of
20343** a legal notice, here is a blessing:
20344**
20345**    May you do good and not evil.
20346**    May you find forgiveness for yourself and forgive others.
20347**    May you share freely, never taking more than you give.
20348**
20349*************************************************************************
20350** This file contains code to implement a pseudo-random number
20351** generator (PRNG) for SQLite.
20352**
20353** Random numbers are used by some of the database backends in order
20354** to generate random integer keys for tables or random filenames.
20355*/
20356
20357
20358/* All threads share a single random number generator.
20359** This structure is the current state of the generator.
20360*/
20361static SQLITE_WSD struct sqlite3PrngType {
20362  unsigned char isInit;          /* True if initialized */
20363  unsigned char i, j;            /* State variables */
20364  unsigned char s[256];          /* State variables */
20365} sqlite3Prng;
20366
20367/*
20368** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
20369** must be held while executing this routine.
20370**
20371** Why not just use a library random generator like lrand48() for this?
20372** Because the OP_NewRowid opcode in the VDBE depends on having a very
20373** good source of random numbers.  The lrand48() library function may
20374** well be good enough.  But maybe not.  Or maybe lrand48() has some
20375** subtle problems on some systems that could cause problems.  It is hard
20376** to know.  To minimize the risk of problems due to bad lrand48()
20377** implementations, SQLite uses this random number generator based
20378** on RC4, which we know works very well.
20379**
20380** (Later):  Actually, OP_NewRowid does not depend on a good source of
20381** randomness any more.  But we will leave this code in all the same.
20382*/
20383static u8 randomByte(void){
20384  unsigned char t;
20385
20386
20387  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20388  ** state vector.  If writable static data is unsupported on the target,
20389  ** we have to locate the state vector at run-time.  In the more common
20390  ** case where writable static data is supported, wsdPrng can refer directly
20391  ** to the "sqlite3Prng" state vector declared above.
20392  */
20393#ifdef SQLITE_OMIT_WSD
20394  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20395# define wsdPrng p[0]
20396#else
20397# define wsdPrng sqlite3Prng
20398#endif
20399
20400
20401  /* Initialize the state of the random number generator once,
20402  ** the first time this routine is called.  The seed value does
20403  ** not need to contain a lot of randomness since we are not
20404  ** trying to do secure encryption or anything like that...
20405  **
20406  ** Nothing in this file or anywhere else in SQLite does any kind of
20407  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20408  ** number generator) not as an encryption device.
20409  */
20410  if( !wsdPrng.isInit ){
20411    int i;
20412    char k[256];
20413    wsdPrng.j = 0;
20414    wsdPrng.i = 0;
20415    sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20416    for(i=0; i<256; i++){
20417      wsdPrng.s[i] = (u8)i;
20418    }
20419    for(i=0; i<256; i++){
20420      wsdPrng.j += wsdPrng.s[i] + k[i];
20421      t = wsdPrng.s[wsdPrng.j];
20422      wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20423      wsdPrng.s[i] = t;
20424    }
20425    wsdPrng.isInit = 1;
20426  }
20427
20428  /* Generate and return single random byte
20429  */
20430  wsdPrng.i++;
20431  t = wsdPrng.s[wsdPrng.i];
20432  wsdPrng.j += t;
20433  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20434  wsdPrng.s[wsdPrng.j] = t;
20435  t += wsdPrng.s[wsdPrng.i];
20436  return wsdPrng.s[t];
20437}
20438
20439/*
20440** Return N random bytes.
20441*/
20442SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20443  unsigned char *zBuf = pBuf;
20444#if SQLITE_THREADSAFE
20445  sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20446#endif
20447  sqlite3_mutex_enter(mutex);
20448  while( N-- ){
20449    *(zBuf++) = randomByte();
20450  }
20451  sqlite3_mutex_leave(mutex);
20452}
20453
20454#ifndef SQLITE_OMIT_BUILTIN_TEST
20455/*
20456** For testing purposes, we sometimes want to preserve the state of
20457** PRNG and restore the PRNG to its saved state at a later time, or
20458** to reset the PRNG to its initial state.  These routines accomplish
20459** those tasks.
20460**
20461** The sqlite3_test_control() interface calls these routines to
20462** control the PRNG.
20463*/
20464static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20465SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20466  memcpy(
20467    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20468    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20469    sizeof(sqlite3Prng)
20470  );
20471}
20472SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20473  memcpy(
20474    &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20475    &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20476    sizeof(sqlite3Prng)
20477  );
20478}
20479SQLITE_PRIVATE void sqlite3PrngResetState(void){
20480  GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20481}
20482#endif /* SQLITE_OMIT_BUILTIN_TEST */
20483
20484/************** End of random.c **********************************************/
20485/************** Begin file utf.c *********************************************/
20486/*
20487** 2004 April 13
20488**
20489** The author disclaims copyright to this source code.  In place of
20490** a legal notice, here is a blessing:
20491**
20492**    May you do good and not evil.
20493**    May you find forgiveness for yourself and forgive others.
20494**    May you share freely, never taking more than you give.
20495**
20496*************************************************************************
20497** This file contains routines used to translate between UTF-8,
20498** UTF-16, UTF-16BE, and UTF-16LE.
20499**
20500** Notes on UTF-8:
20501**
20502**   Byte-0    Byte-1    Byte-2    Byte-3    Value
20503**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20504**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20505**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20506**  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20507**
20508**
20509** Notes on UTF-16:  (with wwww+1==uuuuu)
20510**
20511**      Word-0               Word-1          Value
20512**  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20513**  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20514**
20515**
20516** BOM or Byte Order Mark:
20517**     0xff 0xfe   little-endian utf-16 follows
20518**     0xfe 0xff   big-endian utf-16 follows
20519**
20520*/
20521/* #include <assert.h> */
20522
20523#ifndef SQLITE_AMALGAMATION
20524/*
20525** The following constant value is used by the SQLITE_BIGENDIAN and
20526** SQLITE_LITTLEENDIAN macros.
20527*/
20528SQLITE_PRIVATE const int sqlite3one = 1;
20529#endif /* SQLITE_AMALGAMATION */
20530
20531/*
20532** This lookup table is used to help decode the first byte of
20533** a multi-byte UTF8 character.
20534*/
20535static const unsigned char sqlite3Utf8Trans1[] = {
20536  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20537  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20538  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20539  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20540  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20541  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20542  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20543  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20544};
20545
20546
20547#define WRITE_UTF8(zOut, c) {                          \
20548  if( c<0x00080 ){                                     \
20549    *zOut++ = (u8)(c&0xFF);                            \
20550  }                                                    \
20551  else if( c<0x00800 ){                                \
20552    *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20553    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20554  }                                                    \
20555  else if( c<0x10000 ){                                \
20556    *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20557    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20558    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20559  }else{                                               \
20560    *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20561    *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20562    *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20563    *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20564  }                                                    \
20565}
20566
20567#define WRITE_UTF16LE(zOut, c) {                                    \
20568  if( c<=0xFFFF ){                                                  \
20569    *zOut++ = (u8)(c&0x00FF);                                       \
20570    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20571  }else{                                                            \
20572    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20573    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20574    *zOut++ = (u8)(c&0x00FF);                                       \
20575    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20576  }                                                                 \
20577}
20578
20579#define WRITE_UTF16BE(zOut, c) {                                    \
20580  if( c<=0xFFFF ){                                                  \
20581    *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20582    *zOut++ = (u8)(c&0x00FF);                                       \
20583  }else{                                                            \
20584    *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20585    *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20586    *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20587    *zOut++ = (u8)(c&0x00FF);                                       \
20588  }                                                                 \
20589}
20590
20591#define READ_UTF16LE(zIn, TERM, c){                                   \
20592  c = (*zIn++);                                                       \
20593  c += ((*zIn++)<<8);                                                 \
20594  if( c>=0xD800 && c<0xE000 && TERM ){                                \
20595    int c2 = (*zIn++);                                                \
20596    c2 += ((*zIn++)<<8);                                              \
20597    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20598  }                                                                   \
20599}
20600
20601#define READ_UTF16BE(zIn, TERM, c){                                   \
20602  c = ((*zIn++)<<8);                                                  \
20603  c += (*zIn++);                                                      \
20604  if( c>=0xD800 && c<0xE000 && TERM ){                                \
20605    int c2 = ((*zIn++)<<8);                                           \
20606    c2 += (*zIn++);                                                   \
20607    c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20608  }                                                                   \
20609}
20610
20611/*
20612** Translate a single UTF-8 character.  Return the unicode value.
20613**
20614** During translation, assume that the byte that zTerm points
20615** is a 0x00.
20616**
20617** Write a pointer to the next unread byte back into *pzNext.
20618**
20619** Notes On Invalid UTF-8:
20620**
20621**  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20622**     be encoded as a multi-byte character.  Any multi-byte character that
20623**     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20624**
20625**  *  This routine never allows a UTF16 surrogate value to be encoded.
20626**     If a multi-byte character attempts to encode a value between
20627**     0xd800 and 0xe000 then it is rendered as 0xfffd.
20628**
20629**  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20630**     byte of a character are interpreted as single-byte characters
20631**     and rendered as themselves even though they are technically
20632**     invalid characters.
20633**
20634**  *  This routine accepts an infinite number of different UTF8 encodings
20635**     for unicode values 0x80 and greater.  It do not change over-length
20636**     encodings to 0xfffd as some systems recommend.
20637*/
20638#define READ_UTF8(zIn, zTerm, c)                           \
20639  c = *(zIn++);                                            \
20640  if( c>=0xc0 ){                                           \
20641    c = sqlite3Utf8Trans1[c-0xc0];                         \
20642    while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20643      c = (c<<6) + (0x3f & *(zIn++));                      \
20644    }                                                      \
20645    if( c<0x80                                             \
20646        || (c&0xFFFFF800)==0xD800                          \
20647        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20648  }
20649SQLITE_PRIVATE u32 sqlite3Utf8Read(
20650  const unsigned char *zIn,       /* First byte of UTF-8 character */
20651  const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
20652){
20653  unsigned int c;
20654
20655  /* Same as READ_UTF8() above but without the zTerm parameter.
20656  ** For this routine, we assume the UTF8 string is always zero-terminated.
20657  */
20658  c = *(zIn++);
20659  if( c>=0xc0 ){
20660    c = sqlite3Utf8Trans1[c-0xc0];
20661    while( (*zIn & 0xc0)==0x80 ){
20662      c = (c<<6) + (0x3f & *(zIn++));
20663    }
20664    if( c<0x80
20665        || (c&0xFFFFF800)==0xD800
20666        || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20667  }
20668  *pzNext = zIn;
20669  return c;
20670}
20671
20672
20673
20674
20675/*
20676** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20677** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20678*/
20679/* #define TRANSLATE_TRACE 1 */
20680
20681#ifndef SQLITE_OMIT_UTF16
20682/*
20683** This routine transforms the internal text encoding used by pMem to
20684** desiredEnc. It is an error if the string is already of the desired
20685** encoding, or if *pMem does not contain a string value.
20686*/
20687SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20688  int len;                    /* Maximum length of output string in bytes */
20689  unsigned char *zOut;                  /* Output buffer */
20690  unsigned char *zIn;                   /* Input iterator */
20691  unsigned char *zTerm;                 /* End of input */
20692  unsigned char *z;                     /* Output iterator */
20693  unsigned int c;
20694
20695  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20696  assert( pMem->flags&MEM_Str );
20697  assert( pMem->enc!=desiredEnc );
20698  assert( pMem->enc!=0 );
20699  assert( pMem->n>=0 );
20700
20701#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20702  {
20703    char zBuf[100];
20704    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20705    fprintf(stderr, "INPUT:  %s\n", zBuf);
20706  }
20707#endif
20708
20709  /* If the translation is between UTF-16 little and big endian, then
20710  ** all that is required is to swap the byte order. This case is handled
20711  ** differently from the others.
20712  */
20713  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20714    u8 temp;
20715    int rc;
20716    rc = sqlite3VdbeMemMakeWriteable(pMem);
20717    if( rc!=SQLITE_OK ){
20718      assert( rc==SQLITE_NOMEM );
20719      return SQLITE_NOMEM;
20720    }
20721    zIn = (u8*)pMem->z;
20722    zTerm = &zIn[pMem->n&~1];
20723    while( zIn<zTerm ){
20724      temp = *zIn;
20725      *zIn = *(zIn+1);
20726      zIn++;
20727      *zIn++ = temp;
20728    }
20729    pMem->enc = desiredEnc;
20730    goto translate_out;
20731  }
20732
20733  /* Set len to the maximum number of bytes required in the output buffer. */
20734  if( desiredEnc==SQLITE_UTF8 ){
20735    /* When converting from UTF-16, the maximum growth results from
20736    ** translating a 2-byte character to a 4-byte UTF-8 character.
20737    ** A single byte is required for the output string
20738    ** nul-terminator.
20739    */
20740    pMem->n &= ~1;
20741    len = pMem->n * 2 + 1;
20742  }else{
20743    /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20744    ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20745    ** character. Two bytes are required in the output buffer for the
20746    ** nul-terminator.
20747    */
20748    len = pMem->n * 2 + 2;
20749  }
20750
20751  /* Set zIn to point at the start of the input buffer and zTerm to point 1
20752  ** byte past the end.
20753  **
20754  ** Variable zOut is set to point at the output buffer, space obtained
20755  ** from sqlite3_malloc().
20756  */
20757  zIn = (u8*)pMem->z;
20758  zTerm = &zIn[pMem->n];
20759  zOut = sqlite3DbMallocRaw(pMem->db, len);
20760  if( !zOut ){
20761    return SQLITE_NOMEM;
20762  }
20763  z = zOut;
20764
20765  if( pMem->enc==SQLITE_UTF8 ){
20766    if( desiredEnc==SQLITE_UTF16LE ){
20767      /* UTF-8 -> UTF-16 Little-endian */
20768      while( zIn<zTerm ){
20769        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20770        READ_UTF8(zIn, zTerm, c);
20771        WRITE_UTF16LE(z, c);
20772      }
20773    }else{
20774      assert( desiredEnc==SQLITE_UTF16BE );
20775      /* UTF-8 -> UTF-16 Big-endian */
20776      while( zIn<zTerm ){
20777        /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
20778        READ_UTF8(zIn, zTerm, c);
20779        WRITE_UTF16BE(z, c);
20780      }
20781    }
20782    pMem->n = (int)(z - zOut);
20783    *z++ = 0;
20784  }else{
20785    assert( desiredEnc==SQLITE_UTF8 );
20786    if( pMem->enc==SQLITE_UTF16LE ){
20787      /* UTF-16 Little-endian -> UTF-8 */
20788      while( zIn<zTerm ){
20789        READ_UTF16LE(zIn, zIn<zTerm, c);
20790        WRITE_UTF8(z, c);
20791      }
20792    }else{
20793      /* UTF-16 Big-endian -> UTF-8 */
20794      while( zIn<zTerm ){
20795        READ_UTF16BE(zIn, zIn<zTerm, c);
20796        WRITE_UTF8(z, c);
20797      }
20798    }
20799    pMem->n = (int)(z - zOut);
20800  }
20801  *z = 0;
20802  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20803
20804  sqlite3VdbeMemRelease(pMem);
20805  pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20806  pMem->enc = desiredEnc;
20807  pMem->flags |= (MEM_Term|MEM_Dyn);
20808  pMem->z = (char*)zOut;
20809  pMem->zMalloc = pMem->z;
20810
20811translate_out:
20812#if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20813  {
20814    char zBuf[100];
20815    sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20816    fprintf(stderr, "OUTPUT: %s\n", zBuf);
20817  }
20818#endif
20819  return SQLITE_OK;
20820}
20821
20822/*
20823** This routine checks for a byte-order mark at the beginning of the
20824** UTF-16 string stored in *pMem. If one is present, it is removed and
20825** the encoding of the Mem adjusted. This routine does not do any
20826** byte-swapping, it just sets Mem.enc appropriately.
20827**
20828** The allocation (static, dynamic etc.) and encoding of the Mem may be
20829** changed by this function.
20830*/
20831SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
20832  int rc = SQLITE_OK;
20833  u8 bom = 0;
20834
20835  assert( pMem->n>=0 );
20836  if( pMem->n>1 ){
20837    u8 b1 = *(u8 *)pMem->z;
20838    u8 b2 = *(((u8 *)pMem->z) + 1);
20839    if( b1==0xFE && b2==0xFF ){
20840      bom = SQLITE_UTF16BE;
20841    }
20842    if( b1==0xFF && b2==0xFE ){
20843      bom = SQLITE_UTF16LE;
20844    }
20845  }
20846
20847  if( bom ){
20848    rc = sqlite3VdbeMemMakeWriteable(pMem);
20849    if( rc==SQLITE_OK ){
20850      pMem->n -= 2;
20851      memmove(pMem->z, &pMem->z[2], pMem->n);
20852      pMem->z[pMem->n] = '\0';
20853      pMem->z[pMem->n+1] = '\0';
20854      pMem->flags |= MEM_Term;
20855      pMem->enc = bom;
20856    }
20857  }
20858  return rc;
20859}
20860#endif /* SQLITE_OMIT_UTF16 */
20861
20862/*
20863** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
20864** return the number of unicode characters in pZ up to (but not including)
20865** the first 0x00 byte. If nByte is not less than zero, return the
20866** number of unicode characters in the first nByte of pZ (or up to
20867** the first 0x00, whichever comes first).
20868*/
20869SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
20870  int r = 0;
20871  const u8 *z = (const u8*)zIn;
20872  const u8 *zTerm;
20873  if( nByte>=0 ){
20874    zTerm = &z[nByte];
20875  }else{
20876    zTerm = (const u8*)(-1);
20877  }
20878  assert( z<=zTerm );
20879  while( *z!=0 && z<zTerm ){
20880    SQLITE_SKIP_UTF8(z);
20881    r++;
20882  }
20883  return r;
20884}
20885
20886/* This test function is not currently used by the automated test-suite.
20887** Hence it is only available in debug builds.
20888*/
20889#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
20890/*
20891** Translate UTF-8 to UTF-8.
20892**
20893** This has the effect of making sure that the string is well-formed
20894** UTF-8.  Miscoded characters are removed.
20895**
20896** The translation is done in-place and aborted if the output
20897** overruns the input.
20898*/
20899SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
20900  unsigned char *zOut = zIn;
20901  unsigned char *zStart = zIn;
20902  u32 c;
20903
20904  while( zIn[0] && zOut<=zIn ){
20905    c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
20906    if( c!=0xfffd ){
20907      WRITE_UTF8(zOut, c);
20908    }
20909  }
20910  *zOut = 0;
20911  return (int)(zOut - zStart);
20912}
20913#endif
20914
20915#ifndef SQLITE_OMIT_UTF16
20916/*
20917** Convert a UTF-16 string in the native encoding into a UTF-8 string.
20918** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
20919** be freed by the calling function.
20920**
20921** NULL is returned if there is an allocation error.
20922*/
20923SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
20924  Mem m;
20925  memset(&m, 0, sizeof(m));
20926  m.db = db;
20927  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
20928  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
20929  if( db->mallocFailed ){
20930    sqlite3VdbeMemRelease(&m);
20931    m.z = 0;
20932  }
20933  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
20934  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
20935  assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
20936  assert( m.z || db->mallocFailed );
20937  return m.z;
20938}
20939
20940/*
20941** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
20942** enc. A pointer to the new string is returned, and the value of *pnOut
20943** is set to the length of the returned string in bytes. The call should
20944** arrange to call sqlite3DbFree() on the returned pointer when it is
20945** no longer required.
20946**
20947** If a malloc failure occurs, NULL is returned and the db.mallocFailed
20948** flag set.
20949*/
20950#ifdef SQLITE_ENABLE_STAT3
20951SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
20952  Mem m;
20953  memset(&m, 0, sizeof(m));
20954  m.db = db;
20955  sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
20956  if( sqlite3VdbeMemTranslate(&m, enc) ){
20957    assert( db->mallocFailed );
20958    return 0;
20959  }
20960  assert( m.z==m.zMalloc );
20961  *pnOut = m.n;
20962  return m.z;
20963}
20964#endif
20965
20966/*
20967** zIn is a UTF-16 encoded unicode string at least nChar characters long.
20968** Return the number of bytes in the first nChar unicode characters
20969** in pZ.  nChar must be non-negative.
20970*/
20971SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
20972  int c;
20973  unsigned char const *z = zIn;
20974  int n = 0;
20975
20976  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
20977    while( n<nChar ){
20978      READ_UTF16BE(z, 1, c);
20979      n++;
20980    }
20981  }else{
20982    while( n<nChar ){
20983      READ_UTF16LE(z, 1, c);
20984      n++;
20985    }
20986  }
20987  return (int)(z-(unsigned char const *)zIn);
20988}
20989
20990#if defined(SQLITE_TEST)
20991/*
20992** This routine is called from the TCL test function "translate_selftest".
20993** It checks that the primitives for serializing and deserializing
20994** characters in each encoding are inverses of each other.
20995*/
20996SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
20997  unsigned int i, t;
20998  unsigned char zBuf[20];
20999  unsigned char *z;
21000  int n;
21001  unsigned int c;
21002
21003  for(i=0; i<0x00110000; i++){
21004    z = zBuf;
21005    WRITE_UTF8(z, i);
21006    n = (int)(z-zBuf);
21007    assert( n>0 && n<=4 );
21008    z[0] = 0;
21009    z = zBuf;
21010    c = sqlite3Utf8Read(z, (const u8**)&z);
21011    t = i;
21012    if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21013    if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21014    assert( c==t );
21015    assert( (z-zBuf)==n );
21016  }
21017  for(i=0; i<0x00110000; i++){
21018    if( i>=0xD800 && i<0xE000 ) continue;
21019    z = zBuf;
21020    WRITE_UTF16LE(z, i);
21021    n = (int)(z-zBuf);
21022    assert( n>0 && n<=4 );
21023    z[0] = 0;
21024    z = zBuf;
21025    READ_UTF16LE(z, 1, c);
21026    assert( c==i );
21027    assert( (z-zBuf)==n );
21028  }
21029  for(i=0; i<0x00110000; i++){
21030    if( i>=0xD800 && i<0xE000 ) continue;
21031    z = zBuf;
21032    WRITE_UTF16BE(z, i);
21033    n = (int)(z-zBuf);
21034    assert( n>0 && n<=4 );
21035    z[0] = 0;
21036    z = zBuf;
21037    READ_UTF16BE(z, 1, c);
21038    assert( c==i );
21039    assert( (z-zBuf)==n );
21040  }
21041}
21042#endif /* SQLITE_TEST */
21043#endif /* SQLITE_OMIT_UTF16 */
21044
21045/************** End of utf.c *************************************************/
21046/************** Begin file util.c ********************************************/
21047/*
21048** 2001 September 15
21049**
21050** The author disclaims copyright to this source code.  In place of
21051** a legal notice, here is a blessing:
21052**
21053**    May you do good and not evil.
21054**    May you find forgiveness for yourself and forgive others.
21055**    May you share freely, never taking more than you give.
21056**
21057*************************************************************************
21058** Utility functions used throughout sqlite.
21059**
21060** This file contains functions for allocating memory, comparing
21061** strings, and stuff like that.
21062**
21063*/
21064/* #include <stdarg.h> */
21065#ifdef SQLITE_HAVE_ISNAN
21066# include <math.h>
21067#endif
21068
21069/*
21070** Routine needed to support the testcase() macro.
21071*/
21072#ifdef SQLITE_COVERAGE_TEST
21073SQLITE_PRIVATE void sqlite3Coverage(int x){
21074  static unsigned dummy = 0;
21075  dummy += (unsigned)x;
21076}
21077#endif
21078
21079#ifndef SQLITE_OMIT_FLOATING_POINT
21080/*
21081** Return true if the floating point value is Not a Number (NaN).
21082**
21083** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21084** Otherwise, we have our own implementation that works on most systems.
21085*/
21086SQLITE_PRIVATE int sqlite3IsNaN(double x){
21087  int rc;   /* The value return */
21088#if !defined(SQLITE_HAVE_ISNAN)
21089  /*
21090  ** Systems that support the isnan() library function should probably
21091  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
21092  ** found that many systems do not have a working isnan() function so
21093  ** this implementation is provided as an alternative.
21094  **
21095  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21096  ** On the other hand, the use of -ffast-math comes with the following
21097  ** warning:
21098  **
21099  **      This option [-ffast-math] should never be turned on by any
21100  **      -O option since it can result in incorrect output for programs
21101  **      which depend on an exact implementation of IEEE or ISO
21102  **      rules/specifications for math functions.
21103  **
21104  ** Under MSVC, this NaN test may fail if compiled with a floating-
21105  ** point precision mode other than /fp:precise.  From the MSDN
21106  ** documentation:
21107  **
21108  **      The compiler [with /fp:precise] will properly handle comparisons
21109  **      involving NaN. For example, x != x evaluates to true if x is NaN
21110  **      ...
21111  */
21112#ifdef __FAST_MATH__
21113# error SQLite will not work correctly with the -ffast-math option of GCC.
21114#endif
21115  volatile double y = x;
21116  volatile double z = y;
21117  rc = (y!=z);
21118#else  /* if defined(SQLITE_HAVE_ISNAN) */
21119  rc = isnan(x);
21120#endif /* SQLITE_HAVE_ISNAN */
21121  testcase( rc );
21122  return rc;
21123}
21124#endif /* SQLITE_OMIT_FLOATING_POINT */
21125
21126/*
21127** Compute a string length that is limited to what can be stored in
21128** lower 30 bits of a 32-bit signed integer.
21129**
21130** The value returned will never be negative.  Nor will it ever be greater
21131** than the actual length of the string.  For very long strings (greater
21132** than 1GiB) the value returned might be less than the true string length.
21133*/
21134SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21135  const char *z2 = z;
21136  if( z==0 ) return 0;
21137  while( *z2 ){ z2++; }
21138  return 0x3fffffff & (int)(z2 - z);
21139}
21140
21141/*
21142** Set the most recent error code and error string for the sqlite
21143** handle "db". The error code is set to "err_code".
21144**
21145** If it is not NULL, string zFormat specifies the format of the
21146** error string in the style of the printf functions: The following
21147** format characters are allowed:
21148**
21149**      %s      Insert a string
21150**      %z      A string that should be freed after use
21151**      %d      Insert an integer
21152**      %T      Insert a token
21153**      %S      Insert the first element of a SrcList
21154**
21155** zFormat and any string tokens that follow it are assumed to be
21156** encoded in UTF-8.
21157**
21158** To clear the most recent error for sqlite handle "db", sqlite3Error
21159** should be called with err_code set to SQLITE_OK and zFormat set
21160** to NULL.
21161*/
21162SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21163  if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21164    db->errCode = err_code;
21165    if( zFormat ){
21166      char *z;
21167      va_list ap;
21168      va_start(ap, zFormat);
21169      z = sqlite3VMPrintf(db, zFormat, ap);
21170      va_end(ap);
21171      sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21172    }else{
21173      sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21174    }
21175  }
21176}
21177
21178/*
21179** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21180** The following formatting characters are allowed:
21181**
21182**      %s      Insert a string
21183**      %z      A string that should be freed after use
21184**      %d      Insert an integer
21185**      %T      Insert a token
21186**      %S      Insert the first element of a SrcList
21187**
21188** This function should be used to report any error that occurs whilst
21189** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21190** last thing the sqlite3_prepare() function does is copy the error
21191** stored by this function into the database handle using sqlite3Error().
21192** Function sqlite3Error() should be used during statement execution
21193** (sqlite3_step() etc.).
21194*/
21195SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21196  char *zMsg;
21197  va_list ap;
21198  sqlite3 *db = pParse->db;
21199  va_start(ap, zFormat);
21200  zMsg = sqlite3VMPrintf(db, zFormat, ap);
21201  va_end(ap);
21202  if( db->suppressErr ){
21203    sqlite3DbFree(db, zMsg);
21204  }else{
21205    pParse->nErr++;
21206    sqlite3DbFree(db, pParse->zErrMsg);
21207    pParse->zErrMsg = zMsg;
21208    pParse->rc = SQLITE_ERROR;
21209  }
21210}
21211
21212/*
21213** Convert an SQL-style quoted string into a normal string by removing
21214** the quote characters.  The conversion is done in-place.  If the
21215** input does not begin with a quote character, then this routine
21216** is a no-op.
21217**
21218** The input string must be zero-terminated.  A new zero-terminator
21219** is added to the dequoted string.
21220**
21221** The return value is -1 if no dequoting occurs or the length of the
21222** dequoted string, exclusive of the zero terminator, if dequoting does
21223** occur.
21224**
21225** 2002-Feb-14: This routine is extended to remove MS-Access style
21226** brackets from around identifers.  For example:  "[a-b-c]" becomes
21227** "a-b-c".
21228*/
21229SQLITE_PRIVATE int sqlite3Dequote(char *z){
21230  char quote;
21231  int i, j;
21232  if( z==0 ) return -1;
21233  quote = z[0];
21234  switch( quote ){
21235    case '\'':  break;
21236    case '"':   break;
21237    case '`':   break;                /* For MySQL compatibility */
21238    case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21239    default:    return -1;
21240  }
21241  for(i=1, j=0; ALWAYS(z[i]); i++){
21242    if( z[i]==quote ){
21243      if( z[i+1]==quote ){
21244        z[j++] = quote;
21245        i++;
21246      }else{
21247        break;
21248      }
21249    }else{
21250      z[j++] = z[i];
21251    }
21252  }
21253  z[j] = 0;
21254  return j;
21255}
21256
21257/* Convenient short-hand */
21258#define UpperToLower sqlite3UpperToLower
21259
21260/*
21261** Some systems have stricmp().  Others have strcasecmp().  Because
21262** there is no consistency, we will define our own.
21263**
21264** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21265** sqlite3_strnicmp() APIs allow applications and extensions to compare
21266** the contents of two buffers containing UTF-8 strings in a
21267** case-independent fashion, using the same definition of "case
21268** independence" that SQLite uses internally when comparing identifiers.
21269*/
21270SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21271  register unsigned char *a, *b;
21272  a = (unsigned char *)zLeft;
21273  b = (unsigned char *)zRight;
21274  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21275  return UpperToLower[*a] - UpperToLower[*b];
21276}
21277SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21278  register unsigned char *a, *b;
21279  a = (unsigned char *)zLeft;
21280  b = (unsigned char *)zRight;
21281  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21282  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21283}
21284
21285/*
21286** The string z[] is an text representation of a real number.
21287** Convert this string to a double and write it into *pResult.
21288**
21289** The string z[] is length bytes in length (bytes, not characters) and
21290** uses the encoding enc.  The string is not necessarily zero-terminated.
21291**
21292** Return TRUE if the result is a valid real number (or integer) and FALSE
21293** if the string is empty or contains extraneous text.  Valid numbers
21294** are in one of these formats:
21295**
21296**    [+-]digits[E[+-]digits]
21297**    [+-]digits.[digits][E[+-]digits]
21298**    [+-].digits[E[+-]digits]
21299**
21300** Leading and trailing whitespace is ignored for the purpose of determining
21301** validity.
21302**
21303** If some prefix of the input string is a valid number, this routine
21304** returns FALSE but it still converts the prefix and writes the result
21305** into *pResult.
21306*/
21307SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21308#ifndef SQLITE_OMIT_FLOATING_POINT
21309  int incr = (enc==SQLITE_UTF8?1:2);
21310  const char *zEnd = z + length;
21311  /* sign * significand * (10 ^ (esign * exponent)) */
21312  int sign = 1;    /* sign of significand */
21313  i64 s = 0;       /* significand */
21314  int d = 0;       /* adjust exponent for shifting decimal point */
21315  int esign = 1;   /* sign of exponent */
21316  int e = 0;       /* exponent */
21317  int eValid = 1;  /* True exponent is either not used or is well-formed */
21318  double result;
21319  int nDigits = 0;
21320
21321  *pResult = 0.0;   /* Default return value, in case of an error */
21322
21323  if( enc==SQLITE_UTF16BE ) z++;
21324
21325  /* skip leading spaces */
21326  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21327  if( z>=zEnd ) return 0;
21328
21329  /* get sign of significand */
21330  if( *z=='-' ){
21331    sign = -1;
21332    z+=incr;
21333  }else if( *z=='+' ){
21334    z+=incr;
21335  }
21336
21337  /* skip leading zeroes */
21338  while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21339
21340  /* copy max significant digits to significand */
21341  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21342    s = s*10 + (*z - '0');
21343    z+=incr, nDigits++;
21344  }
21345
21346  /* skip non-significant significand digits
21347  ** (increase exponent by d to shift decimal left) */
21348  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21349  if( z>=zEnd ) goto do_atof_calc;
21350
21351  /* if decimal point is present */
21352  if( *z=='.' ){
21353    z+=incr;
21354    /* copy digits from after decimal to significand
21355    ** (decrease exponent by d to shift decimal right) */
21356    while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21357      s = s*10 + (*z - '0');
21358      z+=incr, nDigits++, d--;
21359    }
21360    /* skip non-significant digits */
21361    while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21362  }
21363  if( z>=zEnd ) goto do_atof_calc;
21364
21365  /* if exponent is present */
21366  if( *z=='e' || *z=='E' ){
21367    z+=incr;
21368    eValid = 0;
21369    if( z>=zEnd ) goto do_atof_calc;
21370    /* get sign of exponent */
21371    if( *z=='-' ){
21372      esign = -1;
21373      z+=incr;
21374    }else if( *z=='+' ){
21375      z+=incr;
21376    }
21377    /* copy digits to exponent */
21378    while( z<zEnd && sqlite3Isdigit(*z) ){
21379      e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21380      z+=incr;
21381      eValid = 1;
21382    }
21383  }
21384
21385  /* skip trailing spaces */
21386  if( nDigits && eValid ){
21387    while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21388  }
21389
21390do_atof_calc:
21391  /* adjust exponent by d, and update sign */
21392  e = (e*esign) + d;
21393  if( e<0 ) {
21394    esign = -1;
21395    e *= -1;
21396  } else {
21397    esign = 1;
21398  }
21399
21400  /* if 0 significand */
21401  if( !s ) {
21402    /* In the IEEE 754 standard, zero is signed.
21403    ** Add the sign if we've seen at least one digit */
21404    result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21405  } else {
21406    /* attempt to reduce exponent */
21407    if( esign>0 ){
21408      while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21409    }else{
21410      while( !(s%10) && e>0 ) e--,s/=10;
21411    }
21412
21413    /* adjust the sign of significand */
21414    s = sign<0 ? -s : s;
21415
21416    /* if exponent, scale significand as appropriate
21417    ** and store in result. */
21418    if( e ){
21419      double scale = 1.0;
21420      /* attempt to handle extremely small/large numbers better */
21421      if( e>307 && e<342 ){
21422        while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21423        if( esign<0 ){
21424          result = s / scale;
21425          result /= 1.0e+308;
21426        }else{
21427          result = s * scale;
21428          result *= 1.0e+308;
21429        }
21430      }else if( e>=342 ){
21431        if( esign<0 ){
21432          result = 0.0*s;
21433        }else{
21434          result = 1e308*1e308*s;  /* Infinity */
21435        }
21436      }else{
21437        /* 1.0e+22 is the largest power of 10 than can be
21438        ** represented exactly. */
21439        while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21440        while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21441        if( esign<0 ){
21442          result = s / scale;
21443        }else{
21444          result = s * scale;
21445        }
21446      }
21447    } else {
21448      result = (double)s;
21449    }
21450  }
21451
21452  /* store the result */
21453  *pResult = result;
21454
21455  /* return true if number and no extra non-whitespace chracters after */
21456  return z>=zEnd && nDigits>0 && eValid;
21457#else
21458  return !sqlite3Atoi64(z, pResult, length, enc);
21459#endif /* SQLITE_OMIT_FLOATING_POINT */
21460}
21461
21462/*
21463** Compare the 19-character string zNum against the text representation
21464** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21465** if zNum is less than, equal to, or greater than the string.
21466** Note that zNum must contain exactly 19 characters.
21467**
21468** Unlike memcmp() this routine is guaranteed to return the difference
21469** in the values of the last digit if the only difference is in the
21470** last digit.  So, for example,
21471**
21472**      compare2pow63("9223372036854775800", 1)
21473**
21474** will return -8.
21475*/
21476static int compare2pow63(const char *zNum, int incr){
21477  int c = 0;
21478  int i;
21479                    /* 012345678901234567 */
21480  const char *pow63 = "922337203685477580";
21481  for(i=0; c==0 && i<18; i++){
21482    c = (zNum[i*incr]-pow63[i])*10;
21483  }
21484  if( c==0 ){
21485    c = zNum[18*incr] - '8';
21486    testcase( c==(-1) );
21487    testcase( c==0 );
21488    testcase( c==(+1) );
21489  }
21490  return c;
21491}
21492
21493
21494/*
21495** Convert zNum to a 64-bit signed integer.
21496**
21497** If the zNum value is representable as a 64-bit twos-complement
21498** integer, then write that value into *pNum and return 0.
21499**
21500** If zNum is exactly 9223372036854665808, return 2.  This special
21501** case is broken out because while 9223372036854665808 cannot be a
21502** signed 64-bit integer, its negative -9223372036854665808 can be.
21503**
21504** If zNum is too big for a 64-bit integer and is not
21505** 9223372036854665808 then return 1.
21506**
21507** length is the number of bytes in the string (bytes, not characters).
21508** The string is not necessarily zero-terminated.  The encoding is
21509** given by enc.
21510*/
21511SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21512  int incr = (enc==SQLITE_UTF8?1:2);
21513  u64 u = 0;
21514  int neg = 0; /* assume positive */
21515  int i;
21516  int c = 0;
21517  const char *zStart;
21518  const char *zEnd = zNum + length;
21519  if( enc==SQLITE_UTF16BE ) zNum++;
21520  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21521  if( zNum<zEnd ){
21522    if( *zNum=='-' ){
21523      neg = 1;
21524      zNum+=incr;
21525    }else if( *zNum=='+' ){
21526      zNum+=incr;
21527    }
21528  }
21529  zStart = zNum;
21530  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21531  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21532    u = u*10 + c - '0';
21533  }
21534  if( u>LARGEST_INT64 ){
21535    *pNum = SMALLEST_INT64;
21536  }else if( neg ){
21537    *pNum = -(i64)u;
21538  }else{
21539    *pNum = (i64)u;
21540  }
21541  testcase( i==18 );
21542  testcase( i==19 );
21543  testcase( i==20 );
21544  if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr ){
21545    /* zNum is empty or contains non-numeric text or is longer
21546    ** than 19 digits (thus guaranteeing that it is too large) */
21547    return 1;
21548  }else if( i<19*incr ){
21549    /* Less than 19 digits, so we know that it fits in 64 bits */
21550    assert( u<=LARGEST_INT64 );
21551    return 0;
21552  }else{
21553    /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21554    c = compare2pow63(zNum, incr);
21555    if( c<0 ){
21556      /* zNum is less than 9223372036854775808 so it fits */
21557      assert( u<=LARGEST_INT64 );
21558      return 0;
21559    }else if( c>0 ){
21560      /* zNum is greater than 9223372036854775808 so it overflows */
21561      return 1;
21562    }else{
21563      /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21564      ** special case 2 overflow if positive */
21565      assert( u-1==LARGEST_INT64 );
21566      assert( (*pNum)==SMALLEST_INT64 );
21567      return neg ? 0 : 2;
21568    }
21569  }
21570}
21571
21572/*
21573** If zNum represents an integer that will fit in 32-bits, then set
21574** *pValue to that integer and return true.  Otherwise return false.
21575**
21576** Any non-numeric characters that following zNum are ignored.
21577** This is different from sqlite3Atoi64() which requires the
21578** input number to be zero-terminated.
21579*/
21580SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21581  sqlite_int64 v = 0;
21582  int i, c;
21583  int neg = 0;
21584  if( zNum[0]=='-' ){
21585    neg = 1;
21586    zNum++;
21587  }else if( zNum[0]=='+' ){
21588    zNum++;
21589  }
21590  while( zNum[0]=='0' ) zNum++;
21591  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21592    v = v*10 + c;
21593  }
21594
21595  /* The longest decimal representation of a 32 bit integer is 10 digits:
21596  **
21597  **             1234567890
21598  **     2^31 -> 2147483648
21599  */
21600  testcase( i==10 );
21601  if( i>10 ){
21602    return 0;
21603  }
21604  testcase( v-neg==2147483647 );
21605  if( v-neg>2147483647 ){
21606    return 0;
21607  }
21608  if( neg ){
21609    v = -v;
21610  }
21611  *pValue = (int)v;
21612  return 1;
21613}
21614
21615/*
21616** Return a 32-bit integer value extracted from a string.  If the
21617** string is not an integer, just return 0.
21618*/
21619SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21620  int x = 0;
21621  if( z ) sqlite3GetInt32(z, &x);
21622  return x;
21623}
21624
21625/*
21626** The variable-length integer encoding is as follows:
21627**
21628** KEY:
21629**         A = 0xxxxxxx    7 bits of data and one flag bit
21630**         B = 1xxxxxxx    7 bits of data and one flag bit
21631**         C = xxxxxxxx    8 bits of data
21632**
21633**  7 bits - A
21634** 14 bits - BA
21635** 21 bits - BBA
21636** 28 bits - BBBA
21637** 35 bits - BBBBA
21638** 42 bits - BBBBBA
21639** 49 bits - BBBBBBA
21640** 56 bits - BBBBBBBA
21641** 64 bits - BBBBBBBBC
21642*/
21643
21644/*
21645** Write a 64-bit variable-length integer to memory starting at p[0].
21646** The length of data write will be between 1 and 9 bytes.  The number
21647** of bytes written is returned.
21648**
21649** A variable-length integer consists of the lower 7 bits of each byte
21650** for all bytes that have the 8th bit set and one byte with the 8th
21651** bit clear.  Except, if we get to the 9th byte, it stores the full
21652** 8 bits and is the last byte.
21653*/
21654SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21655  int i, j, n;
21656  u8 buf[10];
21657  if( v & (((u64)0xff000000)<<32) ){
21658    p[8] = (u8)v;
21659    v >>= 8;
21660    for(i=7; i>=0; i--){
21661      p[i] = (u8)((v & 0x7f) | 0x80);
21662      v >>= 7;
21663    }
21664    return 9;
21665  }
21666  n = 0;
21667  do{
21668    buf[n++] = (u8)((v & 0x7f) | 0x80);
21669    v >>= 7;
21670  }while( v!=0 );
21671  buf[0] &= 0x7f;
21672  assert( n<=9 );
21673  for(i=0, j=n-1; j>=0; j--, i++){
21674    p[i] = buf[j];
21675  }
21676  return n;
21677}
21678
21679/*
21680** This routine is a faster version of sqlite3PutVarint() that only
21681** works for 32-bit positive integers and which is optimized for
21682** the common case of small integers.  A MACRO version, putVarint32,
21683** is provided which inlines the single-byte case.  All code should use
21684** the MACRO version as this function assumes the single-byte case has
21685** already been handled.
21686*/
21687SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21688#ifndef putVarint32
21689  if( (v & ~0x7f)==0 ){
21690    p[0] = v;
21691    return 1;
21692  }
21693#endif
21694  if( (v & ~0x3fff)==0 ){
21695    p[0] = (u8)((v>>7) | 0x80);
21696    p[1] = (u8)(v & 0x7f);
21697    return 2;
21698  }
21699  return sqlite3PutVarint(p, v);
21700}
21701
21702/*
21703** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21704** are defined here rather than simply putting the constant expressions
21705** inline in order to work around bugs in the RVT compiler.
21706**
21707** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21708**
21709** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21710*/
21711#define SLOT_2_0     0x001fc07f
21712#define SLOT_4_2_0   0xf01fc07f
21713
21714
21715/*
21716** Read a 64-bit variable-length integer from memory starting at p[0].
21717** Return the number of bytes read.  The value is stored in *v.
21718*/
21719SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21720  u32 a,b,s;
21721
21722  a = *p;
21723  /* a: p0 (unmasked) */
21724  if (!(a&0x80))
21725  {
21726    *v = a;
21727    return 1;
21728  }
21729
21730  p++;
21731  b = *p;
21732  /* b: p1 (unmasked) */
21733  if (!(b&0x80))
21734  {
21735    a &= 0x7f;
21736    a = a<<7;
21737    a |= b;
21738    *v = a;
21739    return 2;
21740  }
21741
21742  /* Verify that constants are precomputed correctly */
21743  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21744  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21745
21746  p++;
21747  a = a<<14;
21748  a |= *p;
21749  /* a: p0<<14 | p2 (unmasked) */
21750  if (!(a&0x80))
21751  {
21752    a &= SLOT_2_0;
21753    b &= 0x7f;
21754    b = b<<7;
21755    a |= b;
21756    *v = a;
21757    return 3;
21758  }
21759
21760  /* CSE1 from below */
21761  a &= SLOT_2_0;
21762  p++;
21763  b = b<<14;
21764  b |= *p;
21765  /* b: p1<<14 | p3 (unmasked) */
21766  if (!(b&0x80))
21767  {
21768    b &= SLOT_2_0;
21769    /* moved CSE1 up */
21770    /* a &= (0x7f<<14)|(0x7f); */
21771    a = a<<7;
21772    a |= b;
21773    *v = a;
21774    return 4;
21775  }
21776
21777  /* a: p0<<14 | p2 (masked) */
21778  /* b: p1<<14 | p3 (unmasked) */
21779  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21780  /* moved CSE1 up */
21781  /* a &= (0x7f<<14)|(0x7f); */
21782  b &= SLOT_2_0;
21783  s = a;
21784  /* s: p0<<14 | p2 (masked) */
21785
21786  p++;
21787  a = a<<14;
21788  a |= *p;
21789  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21790  if (!(a&0x80))
21791  {
21792    /* we can skip these cause they were (effectively) done above in calc'ing s */
21793    /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21794    /* b &= (0x7f<<14)|(0x7f); */
21795    b = b<<7;
21796    a |= b;
21797    s = s>>18;
21798    *v = ((u64)s)<<32 | a;
21799    return 5;
21800  }
21801
21802  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21803  s = s<<7;
21804  s |= b;
21805  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21806
21807  p++;
21808  b = b<<14;
21809  b |= *p;
21810  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
21811  if (!(b&0x80))
21812  {
21813    /* we can skip this cause it was (effectively) done above in calc'ing s */
21814    /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
21815    a &= SLOT_2_0;
21816    a = a<<7;
21817    a |= b;
21818    s = s>>18;
21819    *v = ((u64)s)<<32 | a;
21820    return 6;
21821  }
21822
21823  p++;
21824  a = a<<14;
21825  a |= *p;
21826  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
21827  if (!(a&0x80))
21828  {
21829    a &= SLOT_4_2_0;
21830    b &= SLOT_2_0;
21831    b = b<<7;
21832    a |= b;
21833    s = s>>11;
21834    *v = ((u64)s)<<32 | a;
21835    return 7;
21836  }
21837
21838  /* CSE2 from below */
21839  a &= SLOT_2_0;
21840  p++;
21841  b = b<<14;
21842  b |= *p;
21843  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
21844  if (!(b&0x80))
21845  {
21846    b &= SLOT_4_2_0;
21847    /* moved CSE2 up */
21848    /* a &= (0x7f<<14)|(0x7f); */
21849    a = a<<7;
21850    a |= b;
21851    s = s>>4;
21852    *v = ((u64)s)<<32 | a;
21853    return 8;
21854  }
21855
21856  p++;
21857  a = a<<15;
21858  a |= *p;
21859  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
21860
21861  /* moved CSE2 up */
21862  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
21863  b &= SLOT_2_0;
21864  b = b<<8;
21865  a |= b;
21866
21867  s = s<<4;
21868  b = p[-4];
21869  b &= 0x7f;
21870  b = b>>3;
21871  s |= b;
21872
21873  *v = ((u64)s)<<32 | a;
21874
21875  return 9;
21876}
21877
21878/*
21879** Read a 32-bit variable-length integer from memory starting at p[0].
21880** Return the number of bytes read.  The value is stored in *v.
21881**
21882** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
21883** integer, then set *v to 0xffffffff.
21884**
21885** A MACRO version, getVarint32, is provided which inlines the
21886** single-byte case.  All code should use the MACRO version as
21887** this function assumes the single-byte case has already been handled.
21888*/
21889SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
21890  u32 a,b;
21891
21892  /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
21893  ** by the getVarin32() macro */
21894  a = *p;
21895  /* a: p0 (unmasked) */
21896#ifndef getVarint32
21897  if (!(a&0x80))
21898  {
21899    /* Values between 0 and 127 */
21900    *v = a;
21901    return 1;
21902  }
21903#endif
21904
21905  /* The 2-byte case */
21906  p++;
21907  b = *p;
21908  /* b: p1 (unmasked) */
21909  if (!(b&0x80))
21910  {
21911    /* Values between 128 and 16383 */
21912    a &= 0x7f;
21913    a = a<<7;
21914    *v = a | b;
21915    return 2;
21916  }
21917
21918  /* The 3-byte case */
21919  p++;
21920  a = a<<14;
21921  a |= *p;
21922  /* a: p0<<14 | p2 (unmasked) */
21923  if (!(a&0x80))
21924  {
21925    /* Values between 16384 and 2097151 */
21926    a &= (0x7f<<14)|(0x7f);
21927    b &= 0x7f;
21928    b = b<<7;
21929    *v = a | b;
21930    return 3;
21931  }
21932
21933  /* A 32-bit varint is used to store size information in btrees.
21934  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
21935  ** A 3-byte varint is sufficient, for example, to record the size
21936  ** of a 1048569-byte BLOB or string.
21937  **
21938  ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
21939  ** rare larger cases can be handled by the slower 64-bit varint
21940  ** routine.
21941  */
21942#if 1
21943  {
21944    u64 v64;
21945    u8 n;
21946
21947    p -= 2;
21948    n = sqlite3GetVarint(p, &v64);
21949    assert( n>3 && n<=9 );
21950    if( (v64 & SQLITE_MAX_U32)!=v64 ){
21951      *v = 0xffffffff;
21952    }else{
21953      *v = (u32)v64;
21954    }
21955    return n;
21956  }
21957
21958#else
21959  /* For following code (kept for historical record only) shows an
21960  ** unrolling for the 3- and 4-byte varint cases.  This code is
21961  ** slightly faster, but it is also larger and much harder to test.
21962  */
21963  p++;
21964  b = b<<14;
21965  b |= *p;
21966  /* b: p1<<14 | p3 (unmasked) */
21967  if (!(b&0x80))
21968  {
21969    /* Values between 2097152 and 268435455 */
21970    b &= (0x7f<<14)|(0x7f);
21971    a &= (0x7f<<14)|(0x7f);
21972    a = a<<7;
21973    *v = a | b;
21974    return 4;
21975  }
21976
21977  p++;
21978  a = a<<14;
21979  a |= *p;
21980  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21981  if (!(a&0x80))
21982  {
21983    /* Values  between 268435456 and 34359738367 */
21984    a &= SLOT_4_2_0;
21985    b &= SLOT_4_2_0;
21986    b = b<<7;
21987    *v = a | b;
21988    return 5;
21989  }
21990
21991  /* We can only reach this point when reading a corrupt database
21992  ** file.  In that case we are not in any hurry.  Use the (relatively
21993  ** slow) general-purpose sqlite3GetVarint() routine to extract the
21994  ** value. */
21995  {
21996    u64 v64;
21997    u8 n;
21998
21999    p -= 4;
22000    n = sqlite3GetVarint(p, &v64);
22001    assert( n>5 && n<=9 );
22002    *v = (u32)v64;
22003    return n;
22004  }
22005#endif
22006}
22007
22008/*
22009** Return the number of bytes that will be needed to store the given
22010** 64-bit integer.
22011*/
22012SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22013  int i = 0;
22014  do{
22015    i++;
22016    v >>= 7;
22017  }while( v!=0 && ALWAYS(i<9) );
22018  return i;
22019}
22020
22021
22022/*
22023** Read or write a four-byte big-endian integer value.
22024*/
22025SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22026  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22027}
22028SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22029  p[0] = (u8)(v>>24);
22030  p[1] = (u8)(v>>16);
22031  p[2] = (u8)(v>>8);
22032  p[3] = (u8)v;
22033}
22034
22035
22036
22037/*
22038** Translate a single byte of Hex into an integer.
22039** This routine only works if h really is a valid hexadecimal
22040** character:  0..9a..fA..F
22041*/
22042SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22043  assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22044#ifdef SQLITE_ASCII
22045  h += 9*(1&(h>>6));
22046#endif
22047#ifdef SQLITE_EBCDIC
22048  h += 9*(1&~(h>>4));
22049#endif
22050  return (u8)(h & 0xf);
22051}
22052
22053#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22054/*
22055** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22056** value.  Return a pointer to its binary value.  Space to hold the
22057** binary value has been obtained from malloc and must be freed by
22058** the calling routine.
22059*/
22060SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22061  char *zBlob;
22062  int i;
22063
22064  zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22065  n--;
22066  if( zBlob ){
22067    for(i=0; i<n; i+=2){
22068      zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22069    }
22070    zBlob[i/2] = 0;
22071  }
22072  return zBlob;
22073}
22074#endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22075
22076/*
22077** Log an error that is an API call on a connection pointer that should
22078** not have been used.  The "type" of connection pointer is given as the
22079** argument.  The zType is a word like "NULL" or "closed" or "invalid".
22080*/
22081static void logBadConnection(const char *zType){
22082  sqlite3_log(SQLITE_MISUSE,
22083     "API call with %s database connection pointer",
22084     zType
22085  );
22086}
22087
22088/*
22089** Check to make sure we have a valid db pointer.  This test is not
22090** foolproof but it does provide some measure of protection against
22091** misuse of the interface such as passing in db pointers that are
22092** NULL or which have been previously closed.  If this routine returns
22093** 1 it means that the db pointer is valid and 0 if it should not be
22094** dereferenced for any reason.  The calling function should invoke
22095** SQLITE_MISUSE immediately.
22096**
22097** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22098** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22099** open properly and is not fit for general use but which can be
22100** used as an argument to sqlite3_errmsg() or sqlite3_close().
22101*/
22102SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22103  u32 magic;
22104  if( db==0 ){
22105    logBadConnection("NULL");
22106    return 0;
22107  }
22108  magic = db->magic;
22109  if( magic!=SQLITE_MAGIC_OPEN ){
22110    if( sqlite3SafetyCheckSickOrOk(db) ){
22111      testcase( sqlite3GlobalConfig.xLog!=0 );
22112      logBadConnection("unopened");
22113    }
22114    return 0;
22115  }else{
22116    return 1;
22117  }
22118}
22119SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22120  u32 magic;
22121  magic = db->magic;
22122  if( magic!=SQLITE_MAGIC_SICK &&
22123      magic!=SQLITE_MAGIC_OPEN &&
22124      magic!=SQLITE_MAGIC_BUSY ){
22125    testcase( sqlite3GlobalConfig.xLog!=0 );
22126    logBadConnection("invalid");
22127    return 0;
22128  }else{
22129    return 1;
22130  }
22131}
22132
22133/*
22134** Attempt to add, substract, or multiply the 64-bit signed value iB against
22135** the other 64-bit signed integer at *pA and store the result in *pA.
22136** Return 0 on success.  Or if the operation would have resulted in an
22137** overflow, leave *pA unchanged and return 1.
22138*/
22139SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22140  i64 iA = *pA;
22141  testcase( iA==0 ); testcase( iA==1 );
22142  testcase( iB==-1 ); testcase( iB==0 );
22143  if( iB>=0 ){
22144    testcase( iA>0 && LARGEST_INT64 - iA == iB );
22145    testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22146    if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22147    *pA += iB;
22148  }else{
22149    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22150    testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22151    if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22152    *pA += iB;
22153  }
22154  return 0;
22155}
22156SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22157  testcase( iB==SMALLEST_INT64+1 );
22158  if( iB==SMALLEST_INT64 ){
22159    testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22160    if( (*pA)>=0 ) return 1;
22161    *pA -= iB;
22162    return 0;
22163  }else{
22164    return sqlite3AddInt64(pA, -iB);
22165  }
22166}
22167#define TWOPOWER32 (((i64)1)<<32)
22168#define TWOPOWER31 (((i64)1)<<31)
22169SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22170  i64 iA = *pA;
22171  i64 iA1, iA0, iB1, iB0, r;
22172
22173  iA1 = iA/TWOPOWER32;
22174  iA0 = iA % TWOPOWER32;
22175  iB1 = iB/TWOPOWER32;
22176  iB0 = iB % TWOPOWER32;
22177  if( iA1*iB1 != 0 ) return 1;
22178  assert( iA1*iB0==0 || iA0*iB1==0 );
22179  r = iA1*iB0 + iA0*iB1;
22180  testcase( r==(-TWOPOWER31)-1 );
22181  testcase( r==(-TWOPOWER31) );
22182  testcase( r==TWOPOWER31 );
22183  testcase( r==TWOPOWER31-1 );
22184  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22185  r *= TWOPOWER32;
22186  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22187  *pA = r;
22188  return 0;
22189}
22190
22191/*
22192** Compute the absolute value of a 32-bit signed integer, of possible.  Or
22193** if the integer has a value of -2147483648, return +2147483647
22194*/
22195SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22196  if( x>=0 ) return x;
22197  if( x==(int)0x80000000 ) return 0x7fffffff;
22198  return -x;
22199}
22200
22201#ifdef SQLITE_ENABLE_8_3_NAMES
22202/*
22203** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22204** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22205** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22206** three characters, then shorten the suffix on z[] to be the last three
22207** characters of the original suffix.
22208**
22209** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22210** do the suffix shortening regardless of URI parameter.
22211**
22212** Examples:
22213**
22214**     test.db-journal    =>   test.nal
22215**     test.db-wal        =>   test.wal
22216**     test.db-shm        =>   test.shm
22217**     test.db-mj7f3319fa =>   test.9fa
22218*/
22219SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22220#if SQLITE_ENABLE_8_3_NAMES<2
22221  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22222#endif
22223  {
22224    int i, sz;
22225    sz = sqlite3Strlen30(z);
22226    for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22227    if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22228  }
22229}
22230#endif
22231
22232/************** End of util.c ************************************************/
22233/************** Begin file hash.c ********************************************/
22234/*
22235** 2001 September 22
22236**
22237** The author disclaims copyright to this source code.  In place of
22238** a legal notice, here is a blessing:
22239**
22240**    May you do good and not evil.
22241**    May you find forgiveness for yourself and forgive others.
22242**    May you share freely, never taking more than you give.
22243**
22244*************************************************************************
22245** This is the implementation of generic hash-tables
22246** used in SQLite.
22247*/
22248/* #include <assert.h> */
22249
22250/* Turn bulk memory into a hash table object by initializing the
22251** fields of the Hash structure.
22252**
22253** "pNew" is a pointer to the hash table that is to be initialized.
22254*/
22255SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22256  assert( pNew!=0 );
22257  pNew->first = 0;
22258  pNew->count = 0;
22259  pNew->htsize = 0;
22260  pNew->ht = 0;
22261}
22262
22263/* Remove all entries from a hash table.  Reclaim all memory.
22264** Call this routine to delete a hash table or to reset a hash table
22265** to the empty state.
22266*/
22267SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22268  HashElem *elem;         /* For looping over all elements of the table */
22269
22270  assert( pH!=0 );
22271  elem = pH->first;
22272  pH->first = 0;
22273  sqlite3_free(pH->ht);
22274  pH->ht = 0;
22275  pH->htsize = 0;
22276  while( elem ){
22277    HashElem *next_elem = elem->next;
22278    sqlite3_free(elem);
22279    elem = next_elem;
22280  }
22281  pH->count = 0;
22282}
22283
22284/*
22285** The hashing function.
22286*/
22287static unsigned int strHash(const char *z, int nKey){
22288  int h = 0;
22289  assert( nKey>=0 );
22290  while( nKey > 0  ){
22291    h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22292    nKey--;
22293  }
22294  return h;
22295}
22296
22297
22298/* Link pNew element into the hash table pH.  If pEntry!=0 then also
22299** insert pNew into the pEntry hash bucket.
22300*/
22301static void insertElement(
22302  Hash *pH,              /* The complete hash table */
22303  struct _ht *pEntry,    /* The entry into which pNew is inserted */
22304  HashElem *pNew         /* The element to be inserted */
22305){
22306  HashElem *pHead;       /* First element already in pEntry */
22307  if( pEntry ){
22308    pHead = pEntry->count ? pEntry->chain : 0;
22309    pEntry->count++;
22310    pEntry->chain = pNew;
22311  }else{
22312    pHead = 0;
22313  }
22314  if( pHead ){
22315    pNew->next = pHead;
22316    pNew->prev = pHead->prev;
22317    if( pHead->prev ){ pHead->prev->next = pNew; }
22318    else             { pH->first = pNew; }
22319    pHead->prev = pNew;
22320  }else{
22321    pNew->next = pH->first;
22322    if( pH->first ){ pH->first->prev = pNew; }
22323    pNew->prev = 0;
22324    pH->first = pNew;
22325  }
22326}
22327
22328
22329/* Resize the hash table so that it cantains "new_size" buckets.
22330**
22331** The hash table might fail to resize if sqlite3_malloc() fails or
22332** if the new size is the same as the prior size.
22333** Return TRUE if the resize occurs and false if not.
22334*/
22335static int rehash(Hash *pH, unsigned int new_size){
22336  struct _ht *new_ht;            /* The new hash table */
22337  HashElem *elem, *next_elem;    /* For looping over existing elements */
22338
22339#if SQLITE_MALLOC_SOFT_LIMIT>0
22340  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22341    new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22342  }
22343  if( new_size==pH->htsize ) return 0;
22344#endif
22345
22346  /* The inability to allocates space for a larger hash table is
22347  ** a performance hit but it is not a fatal error.  So mark the
22348  ** allocation as a benign.
22349  */
22350  sqlite3BeginBenignMalloc();
22351  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22352  sqlite3EndBenignMalloc();
22353
22354  if( new_ht==0 ) return 0;
22355  sqlite3_free(pH->ht);
22356  pH->ht = new_ht;
22357  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22358  memset(new_ht, 0, new_size*sizeof(struct _ht));
22359  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22360    unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22361    next_elem = elem->next;
22362    insertElement(pH, &new_ht[h], elem);
22363  }
22364  return 1;
22365}
22366
22367/* This function (for internal use only) locates an element in an
22368** hash table that matches the given key.  The hash for this key has
22369** already been computed and is passed as the 4th parameter.
22370*/
22371static HashElem *findElementGivenHash(
22372  const Hash *pH,     /* The pH to be searched */
22373  const char *pKey,   /* The key we are searching for */
22374  int nKey,           /* Bytes in key (not counting zero terminator) */
22375  unsigned int h      /* The hash for this key. */
22376){
22377  HashElem *elem;                /* Used to loop thru the element list */
22378  int count;                     /* Number of elements left to test */
22379
22380  if( pH->ht ){
22381    struct _ht *pEntry = &pH->ht[h];
22382    elem = pEntry->chain;
22383    count = pEntry->count;
22384  }else{
22385    elem = pH->first;
22386    count = pH->count;
22387  }
22388  while( count-- && ALWAYS(elem) ){
22389    if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
22390      return elem;
22391    }
22392    elem = elem->next;
22393  }
22394  return 0;
22395}
22396
22397/* Remove a single entry from the hash table given a pointer to that
22398** element and a hash on the element's key.
22399*/
22400static void removeElementGivenHash(
22401  Hash *pH,         /* The pH containing "elem" */
22402  HashElem* elem,   /* The element to be removed from the pH */
22403  unsigned int h    /* Hash value for the element */
22404){
22405  struct _ht *pEntry;
22406  if( elem->prev ){
22407    elem->prev->next = elem->next;
22408  }else{
22409    pH->first = elem->next;
22410  }
22411  if( elem->next ){
22412    elem->next->prev = elem->prev;
22413  }
22414  if( pH->ht ){
22415    pEntry = &pH->ht[h];
22416    if( pEntry->chain==elem ){
22417      pEntry->chain = elem->next;
22418    }
22419    pEntry->count--;
22420    assert( pEntry->count>=0 );
22421  }
22422  sqlite3_free( elem );
22423  pH->count--;
22424  if( pH->count<=0 ){
22425    assert( pH->first==0 );
22426    assert( pH->count==0 );
22427    sqlite3HashClear(pH);
22428  }
22429}
22430
22431/* Attempt to locate an element of the hash table pH with a key
22432** that matches pKey,nKey.  Return the data for this element if it is
22433** found, or NULL if there is no match.
22434*/
22435SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22436  HashElem *elem;    /* The element that matches key */
22437  unsigned int h;    /* A hash on key */
22438
22439  assert( pH!=0 );
22440  assert( pKey!=0 );
22441  assert( nKey>=0 );
22442  if( pH->ht ){
22443    h = strHash(pKey, nKey) % pH->htsize;
22444  }else{
22445    h = 0;
22446  }
22447  elem = findElementGivenHash(pH, pKey, nKey, h);
22448  return elem ? elem->data : 0;
22449}
22450
22451/* Insert an element into the hash table pH.  The key is pKey,nKey
22452** and the data is "data".
22453**
22454** If no element exists with a matching key, then a new
22455** element is created and NULL is returned.
22456**
22457** If another element already exists with the same key, then the
22458** new data replaces the old data and the old data is returned.
22459** The key is not copied in this instance.  If a malloc fails, then
22460** the new data is returned and the hash table is unchanged.
22461**
22462** If the "data" parameter to this function is NULL, then the
22463** element corresponding to "key" is removed from the hash table.
22464*/
22465SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22466  unsigned int h;       /* the hash of the key modulo hash table size */
22467  HashElem *elem;       /* Used to loop thru the element list */
22468  HashElem *new_elem;   /* New element added to the pH */
22469
22470  assert( pH!=0 );
22471  assert( pKey!=0 );
22472  assert( nKey>=0 );
22473  if( pH->htsize ){
22474    h = strHash(pKey, nKey) % pH->htsize;
22475  }else{
22476    h = 0;
22477  }
22478  elem = findElementGivenHash(pH,pKey,nKey,h);
22479  if( elem ){
22480    void *old_data = elem->data;
22481    if( data==0 ){
22482      removeElementGivenHash(pH,elem,h);
22483    }else{
22484      elem->data = data;
22485      elem->pKey = pKey;
22486      assert(nKey==elem->nKey);
22487    }
22488    return old_data;
22489  }
22490  if( data==0 ) return 0;
22491  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22492  if( new_elem==0 ) return data;
22493  new_elem->pKey = pKey;
22494  new_elem->nKey = nKey;
22495  new_elem->data = data;
22496  pH->count++;
22497  if( pH->count>=10 && pH->count > 2*pH->htsize ){
22498    if( rehash(pH, pH->count*2) ){
22499      assert( pH->htsize>0 );
22500      h = strHash(pKey, nKey) % pH->htsize;
22501    }
22502  }
22503  if( pH->ht ){
22504    insertElement(pH, &pH->ht[h], new_elem);
22505  }else{
22506    insertElement(pH, 0, new_elem);
22507  }
22508  return 0;
22509}
22510
22511/************** End of hash.c ************************************************/
22512/************** Begin file opcodes.c *****************************************/
22513/* Automatically generated.  Do not edit */
22514/* See the mkopcodec.awk script for details. */
22515#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22516SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22517 static const char *const azName[] = { "?",
22518     /*   1 */ "Goto",
22519     /*   2 */ "Gosub",
22520     /*   3 */ "Return",
22521     /*   4 */ "Yield",
22522     /*   5 */ "HaltIfNull",
22523     /*   6 */ "Halt",
22524     /*   7 */ "Integer",
22525     /*   8 */ "Int64",
22526     /*   9 */ "String",
22527     /*  10 */ "Null",
22528     /*  11 */ "Blob",
22529     /*  12 */ "Variable",
22530     /*  13 */ "Move",
22531     /*  14 */ "Copy",
22532     /*  15 */ "SCopy",
22533     /*  16 */ "ResultRow",
22534     /*  17 */ "CollSeq",
22535     /*  18 */ "Function",
22536     /*  19 */ "Not",
22537     /*  20 */ "AddImm",
22538     /*  21 */ "MustBeInt",
22539     /*  22 */ "RealAffinity",
22540     /*  23 */ "Permutation",
22541     /*  24 */ "Compare",
22542     /*  25 */ "Jump",
22543     /*  26 */ "Once",
22544     /*  27 */ "If",
22545     /*  28 */ "IfNot",
22546     /*  29 */ "Column",
22547     /*  30 */ "Affinity",
22548     /*  31 */ "MakeRecord",
22549     /*  32 */ "Count",
22550     /*  33 */ "Savepoint",
22551     /*  34 */ "AutoCommit",
22552     /*  35 */ "Transaction",
22553     /*  36 */ "ReadCookie",
22554     /*  37 */ "SetCookie",
22555     /*  38 */ "VerifyCookie",
22556     /*  39 */ "OpenRead",
22557     /*  40 */ "OpenWrite",
22558     /*  41 */ "OpenAutoindex",
22559     /*  42 */ "OpenEphemeral",
22560     /*  43 */ "SorterOpen",
22561     /*  44 */ "OpenPseudo",
22562     /*  45 */ "Close",
22563     /*  46 */ "SeekLt",
22564     /*  47 */ "SeekLe",
22565     /*  48 */ "SeekGe",
22566     /*  49 */ "SeekGt",
22567     /*  50 */ "Seek",
22568     /*  51 */ "NotFound",
22569     /*  52 */ "Found",
22570     /*  53 */ "IsUnique",
22571     /*  54 */ "NotExists",
22572     /*  55 */ "Sequence",
22573     /*  56 */ "NewRowid",
22574     /*  57 */ "Insert",
22575     /*  58 */ "InsertInt",
22576     /*  59 */ "Delete",
22577     /*  60 */ "ResetCount",
22578     /*  61 */ "SorterCompare",
22579     /*  62 */ "SorterData",
22580     /*  63 */ "RowKey",
22581     /*  64 */ "RowData",
22582     /*  65 */ "Rowid",
22583     /*  66 */ "NullRow",
22584     /*  67 */ "Last",
22585     /*  68 */ "Or",
22586     /*  69 */ "And",
22587     /*  70 */ "SorterSort",
22588     /*  71 */ "Sort",
22589     /*  72 */ "Rewind",
22590     /*  73 */ "IsNull",
22591     /*  74 */ "NotNull",
22592     /*  75 */ "Ne",
22593     /*  76 */ "Eq",
22594     /*  77 */ "Gt",
22595     /*  78 */ "Le",
22596     /*  79 */ "Lt",
22597     /*  80 */ "Ge",
22598     /*  81 */ "SorterNext",
22599     /*  82 */ "BitAnd",
22600     /*  83 */ "BitOr",
22601     /*  84 */ "ShiftLeft",
22602     /*  85 */ "ShiftRight",
22603     /*  86 */ "Add",
22604     /*  87 */ "Subtract",
22605     /*  88 */ "Multiply",
22606     /*  89 */ "Divide",
22607     /*  90 */ "Remainder",
22608     /*  91 */ "Concat",
22609     /*  92 */ "Prev",
22610     /*  93 */ "BitNot",
22611     /*  94 */ "String8",
22612     /*  95 */ "Next",
22613     /*  96 */ "SorterInsert",
22614     /*  97 */ "IdxInsert",
22615     /*  98 */ "IdxDelete",
22616     /*  99 */ "IdxRowid",
22617     /* 100 */ "IdxLT",
22618     /* 101 */ "IdxGE",
22619     /* 102 */ "Destroy",
22620     /* 103 */ "Clear",
22621     /* 104 */ "CreateIndex",
22622     /* 105 */ "CreateTable",
22623     /* 106 */ "ParseSchema",
22624     /* 107 */ "LoadAnalysis",
22625     /* 108 */ "DropTable",
22626     /* 109 */ "DropIndex",
22627     /* 110 */ "DropTrigger",
22628     /* 111 */ "IntegrityCk",
22629     /* 112 */ "RowSetAdd",
22630     /* 113 */ "RowSetRead",
22631     /* 114 */ "RowSetTest",
22632     /* 115 */ "Program",
22633     /* 116 */ "Param",
22634     /* 117 */ "FkCounter",
22635     /* 118 */ "FkIfZero",
22636     /* 119 */ "MemMax",
22637     /* 120 */ "IfPos",
22638     /* 121 */ "IfNeg",
22639     /* 122 */ "IfZero",
22640     /* 123 */ "AggStep",
22641     /* 124 */ "AggFinal",
22642     /* 125 */ "Checkpoint",
22643     /* 126 */ "JournalMode",
22644     /* 127 */ "Vacuum",
22645     /* 128 */ "IncrVacuum",
22646     /* 129 */ "Expire",
22647     /* 130 */ "Real",
22648     /* 131 */ "TableLock",
22649     /* 132 */ "VBegin",
22650     /* 133 */ "VCreate",
22651     /* 134 */ "VDestroy",
22652     /* 135 */ "VOpen",
22653     /* 136 */ "VFilter",
22654     /* 137 */ "VColumn",
22655     /* 138 */ "VNext",
22656     /* 139 */ "VRename",
22657     /* 140 */ "VUpdate",
22658     /* 141 */ "ToText",
22659     /* 142 */ "ToBlob",
22660     /* 143 */ "ToNumeric",
22661     /* 144 */ "ToInt",
22662     /* 145 */ "ToReal",
22663     /* 146 */ "Pagecount",
22664     /* 147 */ "MaxPgcnt",
22665     /* 148 */ "Trace",
22666     /* 149 */ "Noop",
22667     /* 150 */ "Explain",
22668  };
22669  return azName[i];
22670}
22671#endif
22672
22673/************** End of opcodes.c *********************************************/
22674/************** Begin file os_os2.c ******************************************/
22675/*
22676** 2006 Feb 14
22677**
22678** The author disclaims copyright to this source code.  In place of
22679** a legal notice, here is a blessing:
22680**
22681**    May you do good and not evil.
22682**    May you find forgiveness for yourself and forgive others.
22683**    May you share freely, never taking more than you give.
22684**
22685******************************************************************************
22686**
22687** This file contains code that is specific to OS/2.
22688*/
22689
22690
22691#if SQLITE_OS_OS2
22692
22693/*
22694** A Note About Memory Allocation:
22695**
22696** This driver uses malloc()/free() directly rather than going through
22697** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
22698** are designed for use on embedded systems where memory is scarce and
22699** malloc failures happen frequently.  OS/2 does not typically run on
22700** embedded systems, and when it does the developers normally have bigger
22701** problems to worry about than running out of memory.  So there is not
22702** a compelling need to use the wrappers.
22703**
22704** But there is a good reason to not use the wrappers.  If we use the
22705** wrappers then we will get simulated malloc() failures within this
22706** driver.  And that causes all kinds of problems for our tests.  We
22707** could enhance SQLite to deal with simulated malloc failures within
22708** the OS driver, but the code to deal with those failure would not
22709** be exercised on Linux (which does not need to malloc() in the driver)
22710** and so we would have difficulty writing coverage tests for that
22711** code.  Better to leave the code out, we think.
22712**
22713** The point of this discussion is as follows:  When creating a new
22714** OS layer for an embedded system, if you use this file as an example,
22715** avoid the use of malloc()/free().  Those routines work ok on OS/2
22716** desktops but not so well in embedded systems.
22717*/
22718
22719/*
22720** Macros used to determine whether or not to use threads.
22721*/
22722#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
22723# define SQLITE_OS2_THREADS 1
22724#endif
22725
22726/*
22727** Include code that is common to all os_*.c files
22728*/
22729/************** Include os_common.h in the middle of os_os2.c ****************/
22730/************** Begin file os_common.h ***************************************/
22731/*
22732** 2004 May 22
22733**
22734** The author disclaims copyright to this source code.  In place of
22735** a legal notice, here is a blessing:
22736**
22737**    May you do good and not evil.
22738**    May you find forgiveness for yourself and forgive others.
22739**    May you share freely, never taking more than you give.
22740**
22741******************************************************************************
22742**
22743** This file contains macros and a little bit of code that is common to
22744** all of the platform-specific files (os_*.c) and is #included into those
22745** files.
22746**
22747** This file should be #included by the os_*.c files only.  It is not a
22748** general purpose header file.
22749*/
22750#ifndef _OS_COMMON_H_
22751#define _OS_COMMON_H_
22752
22753/*
22754** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22755** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22756** switch.  The following code should catch this problem at compile-time.
22757*/
22758#ifdef MEMORY_DEBUG
22759# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22760#endif
22761
22762#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
22763# ifndef SQLITE_DEBUG_OS_TRACE
22764#   define SQLITE_DEBUG_OS_TRACE 0
22765# endif
22766  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
22767# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
22768#else
22769# define OSTRACE(X)
22770#endif
22771
22772/*
22773** Macros for performance tracing.  Normally turned off.  Only works
22774** on i486 hardware.
22775*/
22776#ifdef SQLITE_PERFORMANCE_TRACE
22777
22778/*
22779** hwtime.h contains inline assembler code for implementing
22780** high-performance timing routines.
22781*/
22782/************** Include hwtime.h in the middle of os_common.h ****************/
22783/************** Begin file hwtime.h ******************************************/
22784/*
22785** 2008 May 27
22786**
22787** The author disclaims copyright to this source code.  In place of
22788** a legal notice, here is a blessing:
22789**
22790**    May you do good and not evil.
22791**    May you find forgiveness for yourself and forgive others.
22792**    May you share freely, never taking more than you give.
22793**
22794******************************************************************************
22795**
22796** This file contains inline asm code for retrieving "high-performance"
22797** counters for x86 class CPUs.
22798*/
22799#ifndef _HWTIME_H_
22800#define _HWTIME_H_
22801
22802/*
22803** The following routine only works on pentium-class (or newer) processors.
22804** It uses the RDTSC opcode to read the cycle count value out of the
22805** processor and returns that value.  This can be used for high-res
22806** profiling.
22807*/
22808#if (defined(__GNUC__) || defined(_MSC_VER)) && \
22809      (defined(i386) || defined(__i386__) || defined(_M_IX86))
22810
22811  #if defined(__GNUC__)
22812
22813  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22814     unsigned int lo, hi;
22815     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22816     return (sqlite_uint64)hi << 32 | lo;
22817  }
22818
22819  #elif defined(_MSC_VER)
22820
22821  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22822     __asm {
22823        rdtsc
22824        ret       ; return value at EDX:EAX
22825     }
22826  }
22827
22828  #endif
22829
22830#elif (defined(__GNUC__) && defined(__x86_64__))
22831
22832  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22833      unsigned long val;
22834      __asm__ __volatile__ ("rdtsc" : "=A" (val));
22835      return val;
22836  }
22837
22838#elif (defined(__GNUC__) && defined(__ppc__))
22839
22840  __inline__ sqlite_uint64 sqlite3Hwtime(void){
22841      unsigned long long retval;
22842      unsigned long junk;
22843      __asm__ __volatile__ ("\n\
22844          1:      mftbu   %1\n\
22845                  mftb    %L0\n\
22846                  mftbu   %0\n\
22847                  cmpw    %0,%1\n\
22848                  bne     1b"
22849                  : "=r" (retval), "=r" (junk));
22850      return retval;
22851  }
22852
22853#else
22854
22855  #error Need implementation of sqlite3Hwtime() for your platform.
22856
22857  /*
22858  ** To compile without implementing sqlite3Hwtime() for your platform,
22859  ** you can remove the above #error and use the following
22860  ** stub function.  You will lose timing support for many
22861  ** of the debugging and testing utilities, but it should at
22862  ** least compile and run.
22863  */
22864SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22865
22866#endif
22867
22868#endif /* !defined(_HWTIME_H_) */
22869
22870/************** End of hwtime.h **********************************************/
22871/************** Continuing where we left off in os_common.h ******************/
22872
22873static sqlite_uint64 g_start;
22874static sqlite_uint64 g_elapsed;
22875#define TIMER_START       g_start=sqlite3Hwtime()
22876#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22877#define TIMER_ELAPSED     g_elapsed
22878#else
22879#define TIMER_START
22880#define TIMER_END
22881#define TIMER_ELAPSED     ((sqlite_uint64)0)
22882#endif
22883
22884/*
22885** If we compile with the SQLITE_TEST macro set, then the following block
22886** of code will give us the ability to simulate a disk I/O error.  This
22887** is used for testing the I/O recovery logic.
22888*/
22889#ifdef SQLITE_TEST
22890SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22891SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22892SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22893SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22894SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22895SQLITE_API int sqlite3_diskfull_pending = 0;
22896SQLITE_API int sqlite3_diskfull = 0;
22897#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22898#define SimulateIOError(CODE)  \
22899  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22900       || sqlite3_io_error_pending-- == 1 )  \
22901              { local_ioerr(); CODE; }
22902static void local_ioerr(){
22903  IOTRACE(("IOERR\n"));
22904  sqlite3_io_error_hit++;
22905  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22906}
22907#define SimulateDiskfullError(CODE) \
22908   if( sqlite3_diskfull_pending ){ \
22909     if( sqlite3_diskfull_pending == 1 ){ \
22910       local_ioerr(); \
22911       sqlite3_diskfull = 1; \
22912       sqlite3_io_error_hit = 1; \
22913       CODE; \
22914     }else{ \
22915       sqlite3_diskfull_pending--; \
22916     } \
22917   }
22918#else
22919#define SimulateIOErrorBenign(X)
22920#define SimulateIOError(A)
22921#define SimulateDiskfullError(A)
22922#endif
22923
22924/*
22925** When testing, keep a count of the number of open files.
22926*/
22927#ifdef SQLITE_TEST
22928SQLITE_API int sqlite3_open_file_count = 0;
22929#define OpenCounter(X)  sqlite3_open_file_count+=(X)
22930#else
22931#define OpenCounter(X)
22932#endif
22933
22934#endif /* !defined(_OS_COMMON_H_) */
22935
22936/************** End of os_common.h *******************************************/
22937/************** Continuing where we left off in os_os2.c *********************/
22938
22939/* Forward references */
22940typedef struct os2File os2File;         /* The file structure */
22941typedef struct os2ShmNode os2ShmNode;   /* A shared descritive memory node */
22942typedef struct os2ShmLink os2ShmLink;   /* A connection to shared-memory */
22943
22944/*
22945** The os2File structure is subclass of sqlite3_file specific for the OS/2
22946** protability layer.
22947*/
22948struct os2File {
22949  const sqlite3_io_methods *pMethod;  /* Always the first entry */
22950  HFILE h;                  /* Handle for accessing the file */
22951  int flags;                /* Flags provided to os2Open() */
22952  int locktype;             /* Type of lock currently held on this file */
22953  int szChunk;              /* Chunk size configured by FCNTL_CHUNK_SIZE */
22954  char *zFullPathCp;        /* Full path name of this file */
22955  os2ShmLink *pShmLink;     /* Instance of shared memory on this file */
22956};
22957
22958#define LOCK_TIMEOUT 10L /* the default locking timeout */
22959
22960/*
22961** Missing from some versions of the OS/2 toolkit -
22962** used to allocate from high memory if possible
22963*/
22964#ifndef OBJ_ANY
22965# define OBJ_ANY 0x00000400
22966#endif
22967
22968/*****************************************************************************
22969** The next group of routines implement the I/O methods specified
22970** by the sqlite3_io_methods object.
22971******************************************************************************/
22972
22973/*
22974** Close a file.
22975*/
22976static int os2Close( sqlite3_file *id ){
22977  APIRET rc;
22978  os2File *pFile = (os2File*)id;
22979
22980  assert( id!=0 );
22981  OSTRACE(( "CLOSE %d (%s)\n", pFile->h, pFile->zFullPathCp ));
22982
22983  rc = DosClose( pFile->h );
22984
22985  if( pFile->flags & SQLITE_OPEN_DELETEONCLOSE )
22986    DosForceDelete( (PSZ)pFile->zFullPathCp );
22987
22988  free( pFile->zFullPathCp );
22989  pFile->zFullPathCp = NULL;
22990  pFile->locktype = NO_LOCK;
22991  pFile->h = (HFILE)-1;
22992  pFile->flags = 0;
22993
22994  OpenCounter( -1 );
22995  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
22996}
22997
22998/*
22999** Read data from a file into a buffer.  Return SQLITE_OK if all
23000** bytes were read successfully and SQLITE_IOERR if anything goes
23001** wrong.
23002*/
23003static int os2Read(
23004  sqlite3_file *id,               /* File to read from */
23005  void *pBuf,                     /* Write content into this buffer */
23006  int amt,                        /* Number of bytes to read */
23007  sqlite3_int64 offset            /* Begin reading at this offset */
23008){
23009  ULONG fileLocation = 0L;
23010  ULONG got;
23011  os2File *pFile = (os2File*)id;
23012  assert( id!=0 );
23013  SimulateIOError( return SQLITE_IOERR_READ );
23014  OSTRACE(( "READ %d lock=%d\n", pFile->h, pFile->locktype ));
23015  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
23016    return SQLITE_IOERR;
23017  }
23018  if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
23019    return SQLITE_IOERR_READ;
23020  }
23021  if( got == (ULONG)amt )
23022    return SQLITE_OK;
23023  else {
23024    /* Unread portions of the input buffer must be zero-filled */
23025    memset(&((char*)pBuf)[got], 0, amt-got);
23026    return SQLITE_IOERR_SHORT_READ;
23027  }
23028}
23029
23030/*
23031** Write data from a buffer into a file.  Return SQLITE_OK on success
23032** or some other error code on failure.
23033*/
23034static int os2Write(
23035  sqlite3_file *id,               /* File to write into */
23036  const void *pBuf,               /* The bytes to be written */
23037  int amt,                        /* Number of bytes to write */
23038  sqlite3_int64 offset            /* Offset into the file to begin writing at */
23039){
23040  ULONG fileLocation = 0L;
23041  APIRET rc = NO_ERROR;
23042  ULONG wrote;
23043  os2File *pFile = (os2File*)id;
23044  assert( id!=0 );
23045  SimulateIOError( return SQLITE_IOERR_WRITE );
23046  SimulateDiskfullError( return SQLITE_FULL );
23047  OSTRACE(( "WRITE %d lock=%d\n", pFile->h, pFile->locktype ));
23048  if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
23049    return SQLITE_IOERR;
23050  }
23051  assert( amt>0 );
23052  while( amt > 0 &&
23053         ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
23054         wrote > 0
23055  ){
23056    amt -= wrote;
23057    pBuf = &((char*)pBuf)[wrote];
23058  }
23059
23060  return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
23061}
23062
23063/*
23064** Truncate an open file to a specified size
23065*/
23066static int os2Truncate( sqlite3_file *id, i64 nByte ){
23067  APIRET rc;
23068  os2File *pFile = (os2File*)id;
23069  assert( id!=0 );
23070  OSTRACE(( "TRUNCATE %d %lld\n", pFile->h, nByte ));
23071  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
23072
23073  /* If the user has configured a chunk-size for this file, truncate the
23074  ** file so that it consists of an integer number of chunks (i.e. the
23075  ** actual file size after the operation may be larger than the requested
23076  ** size).
23077  */
23078  if( pFile->szChunk ){
23079    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
23080  }
23081
23082  rc = DosSetFileSize( pFile->h, nByte );
23083  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
23084}
23085
23086#ifdef SQLITE_TEST
23087/*
23088** Count the number of fullsyncs and normal syncs.  This is used to test
23089** that syncs and fullsyncs are occuring at the right times.
23090*/
23091SQLITE_API int sqlite3_sync_count = 0;
23092SQLITE_API int sqlite3_fullsync_count = 0;
23093#endif
23094
23095/*
23096** Make sure all writes to a particular file are committed to disk.
23097*/
23098static int os2Sync( sqlite3_file *id, int flags ){
23099  os2File *pFile = (os2File*)id;
23100  OSTRACE(( "SYNC %d lock=%d\n", pFile->h, pFile->locktype ));
23101#ifdef SQLITE_TEST
23102  if( flags & SQLITE_SYNC_FULL){
23103    sqlite3_fullsync_count++;
23104  }
23105  sqlite3_sync_count++;
23106#endif
23107  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
23108  ** no-op
23109  */
23110#ifdef SQLITE_NO_SYNC
23111  UNUSED_PARAMETER(pFile);
23112  return SQLITE_OK;
23113#else
23114  return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
23115#endif
23116}
23117
23118/*
23119** Determine the current size of a file in bytes
23120*/
23121static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
23122  APIRET rc = NO_ERROR;
23123  FILESTATUS3 fsts3FileInfo;
23124  memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
23125  assert( id!=0 );
23126  SimulateIOError( return SQLITE_IOERR_FSTAT );
23127  rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
23128  if( rc == NO_ERROR ){
23129    *pSize = fsts3FileInfo.cbFile;
23130    return SQLITE_OK;
23131  }else{
23132    return SQLITE_IOERR_FSTAT;
23133  }
23134}
23135
23136/*
23137** Acquire a reader lock.
23138*/
23139static int getReadLock( os2File *pFile ){
23140  FILELOCK  LockArea,
23141            UnlockArea;
23142  APIRET res;
23143  memset(&LockArea, 0, sizeof(LockArea));
23144  memset(&UnlockArea, 0, sizeof(UnlockArea));
23145  LockArea.lOffset = SHARED_FIRST;
23146  LockArea.lRange = SHARED_SIZE;
23147  UnlockArea.lOffset = 0L;
23148  UnlockArea.lRange = 0L;
23149  res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
23150  OSTRACE(( "GETREADLOCK %d res=%d\n", pFile->h, res ));
23151  return res;
23152}
23153
23154/*
23155** Undo a readlock
23156*/
23157static int unlockReadLock( os2File *id ){
23158  FILELOCK  LockArea,
23159            UnlockArea;
23160  APIRET res;
23161  memset(&LockArea, 0, sizeof(LockArea));
23162  memset(&UnlockArea, 0, sizeof(UnlockArea));
23163  LockArea.lOffset = 0L;
23164  LockArea.lRange = 0L;
23165  UnlockArea.lOffset = SHARED_FIRST;
23166  UnlockArea.lRange = SHARED_SIZE;
23167  res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
23168  OSTRACE(( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res ));
23169  return res;
23170}
23171
23172/*
23173** Lock the file with the lock specified by parameter locktype - one
23174** of the following:
23175**
23176**     (1) SHARED_LOCK
23177**     (2) RESERVED_LOCK
23178**     (3) PENDING_LOCK
23179**     (4) EXCLUSIVE_LOCK
23180**
23181** Sometimes when requesting one lock state, additional lock states
23182** are inserted in between.  The locking might fail on one of the later
23183** transitions leaving the lock state different from what it started but
23184** still short of its goal.  The following chart shows the allowed
23185** transitions and the inserted intermediate states:
23186**
23187**    UNLOCKED -> SHARED
23188**    SHARED -> RESERVED
23189**    SHARED -> (PENDING) -> EXCLUSIVE
23190**    RESERVED -> (PENDING) -> EXCLUSIVE
23191**    PENDING -> EXCLUSIVE
23192**
23193** This routine will only increase a lock.  The os2Unlock() routine
23194** erases all locks at once and returns us immediately to locking level 0.
23195** It is not possible to lower the locking level one step at a time.  You
23196** must go straight to locking level 0.
23197*/
23198static int os2Lock( sqlite3_file *id, int locktype ){
23199  int rc = SQLITE_OK;       /* Return code from subroutines */
23200  APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
23201  int newLocktype;       /* Set pFile->locktype to this value before exiting */
23202  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
23203  FILELOCK  LockArea,
23204            UnlockArea;
23205  os2File *pFile = (os2File*)id;
23206  memset(&LockArea, 0, sizeof(LockArea));
23207  memset(&UnlockArea, 0, sizeof(UnlockArea));
23208  assert( pFile!=0 );
23209  OSTRACE(( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype ));
23210
23211  /* If there is already a lock of this type or more restrictive on the
23212  ** os2File, do nothing. Don't use the end_lock: exit path, as
23213  ** sqlite3_mutex_enter() hasn't been called yet.
23214  */
23215  if( pFile->locktype>=locktype ){
23216    OSTRACE(( "LOCK %d %d ok (already held)\n", pFile->h, locktype ));
23217    return SQLITE_OK;
23218  }
23219
23220  /* Make sure the locking sequence is correct
23221  */
23222  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23223  assert( locktype!=PENDING_LOCK );
23224  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23225
23226  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
23227  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
23228  ** the PENDING_LOCK byte is temporary.
23229  */
23230  newLocktype = pFile->locktype;
23231  if( pFile->locktype==NO_LOCK
23232      || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
23233  ){
23234    LockArea.lOffset = PENDING_BYTE;
23235    LockArea.lRange = 1L;
23236    UnlockArea.lOffset = 0L;
23237    UnlockArea.lRange = 0L;
23238
23239    /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
23240    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
23241    if( res == NO_ERROR ){
23242      gotPendingLock = 1;
23243      OSTRACE(( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res ));
23244    }
23245  }
23246
23247  /* Acquire a shared lock
23248  */
23249  if( locktype==SHARED_LOCK && res == NO_ERROR ){
23250    assert( pFile->locktype==NO_LOCK );
23251    res = getReadLock(pFile);
23252    if( res == NO_ERROR ){
23253      newLocktype = SHARED_LOCK;
23254    }
23255    OSTRACE(( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res ));
23256  }
23257
23258  /* Acquire a RESERVED lock
23259  */
23260  if( locktype==RESERVED_LOCK && res == NO_ERROR ){
23261    assert( pFile->locktype==SHARED_LOCK );
23262    LockArea.lOffset = RESERVED_BYTE;
23263    LockArea.lRange = 1L;
23264    UnlockArea.lOffset = 0L;
23265    UnlockArea.lRange = 0L;
23266    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23267    if( res == NO_ERROR ){
23268      newLocktype = RESERVED_LOCK;
23269    }
23270    OSTRACE(( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res ));
23271  }
23272
23273  /* Acquire a PENDING lock
23274  */
23275  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
23276    newLocktype = PENDING_LOCK;
23277    gotPendingLock = 0;
23278    OSTRACE(( "LOCK %d acquire pending lock. pending lock boolean unset.\n",
23279               pFile->h ));
23280  }
23281
23282  /* Acquire an EXCLUSIVE lock
23283  */
23284  if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
23285    assert( pFile->locktype>=SHARED_LOCK );
23286    res = unlockReadLock(pFile);
23287    OSTRACE(( "unreadlock = %d\n", res ));
23288    LockArea.lOffset = SHARED_FIRST;
23289    LockArea.lRange = SHARED_SIZE;
23290    UnlockArea.lOffset = 0L;
23291    UnlockArea.lRange = 0L;
23292    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23293    if( res == NO_ERROR ){
23294      newLocktype = EXCLUSIVE_LOCK;
23295    }else{
23296      OSTRACE(( "OS/2 error-code = %d\n", res ));
23297      getReadLock(pFile);
23298    }
23299    OSTRACE(( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res ));
23300  }
23301
23302  /* If we are holding a PENDING lock that ought to be released, then
23303  ** release it now.
23304  */
23305  if( gotPendingLock && locktype==SHARED_LOCK ){
23306    int r;
23307    LockArea.lOffset = 0L;
23308    LockArea.lRange = 0L;
23309    UnlockArea.lOffset = PENDING_BYTE;
23310    UnlockArea.lRange = 1L;
23311    r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23312    OSTRACE(( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r ));
23313  }
23314
23315  /* Update the state of the lock has held in the file descriptor then
23316  ** return the appropriate result code.
23317  */
23318  if( res == NO_ERROR ){
23319    rc = SQLITE_OK;
23320  }else{
23321    OSTRACE(( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
23322              locktype, newLocktype ));
23323    rc = SQLITE_BUSY;
23324  }
23325  pFile->locktype = newLocktype;
23326  OSTRACE(( "LOCK %d now %d\n", pFile->h, pFile->locktype ));
23327  return rc;
23328}
23329
23330/*
23331** This routine checks if there is a RESERVED lock held on the specified
23332** file by this or any other process. If such a lock is held, return
23333** non-zero, otherwise zero.
23334*/
23335static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
23336  int r = 0;
23337  os2File *pFile = (os2File*)id;
23338  assert( pFile!=0 );
23339  if( pFile->locktype>=RESERVED_LOCK ){
23340    r = 1;
23341    OSTRACE(( "TEST WR-LOCK %d %d (local)\n", pFile->h, r ));
23342  }else{
23343    FILELOCK  LockArea,
23344              UnlockArea;
23345    APIRET rc = NO_ERROR;
23346    memset(&LockArea, 0, sizeof(LockArea));
23347    memset(&UnlockArea, 0, sizeof(UnlockArea));
23348    LockArea.lOffset = RESERVED_BYTE;
23349    LockArea.lRange = 1L;
23350    UnlockArea.lOffset = 0L;
23351    UnlockArea.lRange = 0L;
23352    rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23353    OSTRACE(( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc ));
23354    if( rc == NO_ERROR ){
23355      APIRET rcu = NO_ERROR; /* return code for unlocking */
23356      LockArea.lOffset = 0L;
23357      LockArea.lRange = 0L;
23358      UnlockArea.lOffset = RESERVED_BYTE;
23359      UnlockArea.lRange = 1L;
23360      rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23361      OSTRACE(( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu ));
23362    }
23363    r = !(rc == NO_ERROR);
23364    OSTRACE(( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r ));
23365  }
23366  *pOut = r;
23367  return SQLITE_OK;
23368}
23369
23370/*
23371** Lower the locking level on file descriptor id to locktype.  locktype
23372** must be either NO_LOCK or SHARED_LOCK.
23373**
23374** If the locking level of the file descriptor is already at or below
23375** the requested locking level, this routine is a no-op.
23376**
23377** It is not possible for this routine to fail if the second argument
23378** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
23379** might return SQLITE_IOERR;
23380*/
23381static int os2Unlock( sqlite3_file *id, int locktype ){
23382  int type;
23383  os2File *pFile = (os2File*)id;
23384  APIRET rc = SQLITE_OK;
23385  APIRET res = NO_ERROR;
23386  FILELOCK  LockArea,
23387            UnlockArea;
23388  memset(&LockArea, 0, sizeof(LockArea));
23389  memset(&UnlockArea, 0, sizeof(UnlockArea));
23390  assert( pFile!=0 );
23391  assert( locktype<=SHARED_LOCK );
23392  OSTRACE(( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype ));
23393  type = pFile->locktype;
23394  if( type>=EXCLUSIVE_LOCK ){
23395    LockArea.lOffset = 0L;
23396    LockArea.lRange = 0L;
23397    UnlockArea.lOffset = SHARED_FIRST;
23398    UnlockArea.lRange = SHARED_SIZE;
23399    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23400    OSTRACE(( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res ));
23401    if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
23402      /* This should never happen.  We should always be able to
23403      ** reacquire the read lock */
23404      OSTRACE(( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype ));
23405      rc = SQLITE_IOERR_UNLOCK;
23406    }
23407  }
23408  if( type>=RESERVED_LOCK ){
23409    LockArea.lOffset = 0L;
23410    LockArea.lRange = 0L;
23411    UnlockArea.lOffset = RESERVED_BYTE;
23412    UnlockArea.lRange = 1L;
23413    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23414    OSTRACE(( "UNLOCK %d reserved res=%d\n", pFile->h, res ));
23415  }
23416  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
23417    res = unlockReadLock(pFile);
23418    OSTRACE(( "UNLOCK %d is %d want %d res=%d\n",
23419              pFile->h, type, locktype, res ));
23420  }
23421  if( type>=PENDING_LOCK ){
23422    LockArea.lOffset = 0L;
23423    LockArea.lRange = 0L;
23424    UnlockArea.lOffset = PENDING_BYTE;
23425    UnlockArea.lRange = 1L;
23426    res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
23427    OSTRACE(( "UNLOCK %d pending res=%d\n", pFile->h, res ));
23428  }
23429  pFile->locktype = locktype;
23430  OSTRACE(( "UNLOCK %d now %d\n", pFile->h, pFile->locktype ));
23431  return rc;
23432}
23433
23434/*
23435** Control and query of the open file handle.
23436*/
23437static int os2FileControl(sqlite3_file *id, int op, void *pArg){
23438  switch( op ){
23439    case SQLITE_FCNTL_LOCKSTATE: {
23440      *(int*)pArg = ((os2File*)id)->locktype;
23441      OSTRACE(( "FCNTL_LOCKSTATE %d lock=%d\n",
23442                ((os2File*)id)->h, ((os2File*)id)->locktype ));
23443      return SQLITE_OK;
23444    }
23445    case SQLITE_FCNTL_CHUNK_SIZE: {
23446      ((os2File*)id)->szChunk = *(int*)pArg;
23447      return SQLITE_OK;
23448    }
23449    case SQLITE_FCNTL_SIZE_HINT: {
23450      sqlite3_int64 sz = *(sqlite3_int64*)pArg;
23451      SimulateIOErrorBenign(1);
23452      os2Truncate(id, sz);
23453      SimulateIOErrorBenign(0);
23454      return SQLITE_OK;
23455    }
23456    case SQLITE_FCNTL_SYNC_OMITTED: {
23457      return SQLITE_OK;
23458    }
23459  }
23460  return SQLITE_NOTFOUND;
23461}
23462
23463/*
23464** Return the sector size in bytes of the underlying block device for
23465** the specified file. This is almost always 512 bytes, but may be
23466** larger for some devices.
23467**
23468** SQLite code assumes this function cannot fail. It also assumes that
23469** if two files are created in the same file-system directory (i.e.
23470** a database and its journal file) that the sector size will be the
23471** same for both.
23472*/
23473static int os2SectorSize(sqlite3_file *id){
23474  UNUSED_PARAMETER(id);
23475  return SQLITE_DEFAULT_SECTOR_SIZE;
23476}
23477
23478/*
23479** Return a vector of device characteristics.
23480*/
23481static int os2DeviceCharacteristics(sqlite3_file *id){
23482  UNUSED_PARAMETER(id);
23483  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN;
23484}
23485
23486
23487/*
23488** Character set conversion objects used by conversion routines.
23489*/
23490static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
23491static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
23492
23493/*
23494** Helper function to initialize the conversion objects from and to UTF-8.
23495*/
23496static void initUconvObjects( void ){
23497  if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
23498    ucUtf8 = NULL;
23499  if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
23500    uclCp = NULL;
23501}
23502
23503/*
23504** Helper function to free the conversion objects from and to UTF-8.
23505*/
23506static void freeUconvObjects( void ){
23507  if ( ucUtf8 )
23508    UniFreeUconvObject( ucUtf8 );
23509  if ( uclCp )
23510    UniFreeUconvObject( uclCp );
23511  ucUtf8 = NULL;
23512  uclCp = NULL;
23513}
23514
23515/*
23516** Helper function to convert UTF-8 filenames to local OS/2 codepage.
23517** The two-step process: first convert the incoming UTF-8 string
23518** into UCS-2 and then from UCS-2 to the current codepage.
23519** The returned char pointer has to be freed.
23520*/
23521static char *convertUtf8PathToCp( const char *in ){
23522  UniChar tempPath[CCHMAXPATH];
23523  char *out = (char *)calloc( CCHMAXPATH, 1 );
23524
23525  if( !out )
23526    return NULL;
23527
23528  if( !ucUtf8 || !uclCp )
23529    initUconvObjects();
23530
23531  /* determine string for the conversion of UTF-8 which is CP1208 */
23532  if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23533    return out; /* if conversion fails, return the empty string */
23534
23535  /* conversion for current codepage which can be used for paths */
23536  UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
23537
23538  return out;
23539}
23540
23541/*
23542** Helper function to convert filenames from local codepage to UTF-8.
23543** The two-step process: first convert the incoming codepage-specific
23544** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
23545** The returned char pointer has to be freed.
23546**
23547** This function is non-static to be able to use this in shell.c and
23548** similar applications that take command line arguments.
23549*/
23550char *convertCpPathToUtf8( const char *in ){
23551  UniChar tempPath[CCHMAXPATH];
23552  char *out = (char *)calloc( CCHMAXPATH, 1 );
23553
23554  if( !out )
23555    return NULL;
23556
23557  if( !ucUtf8 || !uclCp )
23558    initUconvObjects();
23559
23560  /* conversion for current codepage which can be used for paths */
23561  if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
23562    return out; /* if conversion fails, return the empty string */
23563
23564  /* determine string for the conversion of UTF-8 which is CP1208 */
23565  UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
23566
23567  return out;
23568}
23569
23570
23571#ifndef SQLITE_OMIT_WAL
23572
23573/*
23574** Use main database file for interprocess locking. If un-defined
23575** a separate file is created for this purpose. The file will be
23576** used only to set file locks. There will be no data written to it.
23577*/
23578#define SQLITE_OS2_NO_WAL_LOCK_FILE
23579
23580#if 0
23581static void _ERR_TRACE( const char *fmt, ... ) {
23582  va_list  ap;
23583  va_start(ap, fmt);
23584  vfprintf(stderr, fmt, ap);
23585  fflush(stderr);
23586}
23587#define ERR_TRACE(rc, msg)        \
23588        if( (rc) != SQLITE_OK ) _ERR_TRACE msg;
23589#else
23590#define ERR_TRACE(rc, msg)
23591#endif
23592
23593/*
23594** Helper functions to obtain and relinquish the global mutex. The
23595** global mutex is used to protect os2ShmNodeList.
23596**
23597** Function os2ShmMutexHeld() is used to assert() that the global mutex
23598** is held when required. This function is only used as part of assert()
23599** statements. e.g.
23600**
23601**   os2ShmEnterMutex()
23602**     assert( os2ShmMutexHeld() );
23603**   os2ShmLeaveMutex()
23604*/
23605static void os2ShmEnterMutex(void){
23606  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23607}
23608static void os2ShmLeaveMutex(void){
23609  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23610}
23611#ifdef SQLITE_DEBUG
23612static int os2ShmMutexHeld(void) {
23613  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23614}
23615int GetCurrentProcessId(void) {
23616  PPIB pib;
23617  DosGetInfoBlocks(NULL, &pib);
23618  return (int)pib->pib_ulpid;
23619}
23620#endif
23621
23622/*
23623** Object used to represent a the shared memory area for a single log file.
23624** When multiple threads all reference the same log-summary, each thread has
23625** its own os2File object, but they all point to a single instance of this
23626** object.  In other words, each log-summary is opened only once per process.
23627**
23628** os2ShmMutexHeld() must be true when creating or destroying
23629** this object or while reading or writing the following fields:
23630**
23631**      nRef
23632**      pNext
23633**
23634** The following fields are read-only after the object is created:
23635**
23636**      szRegion
23637**      hLockFile
23638**      shmBaseName
23639**
23640** Either os2ShmNode.mutex must be held or os2ShmNode.nRef==0 and
23641** os2ShmMutexHeld() is true when reading or writing any other field
23642** in this structure.
23643**
23644*/
23645struct os2ShmNode {
23646  sqlite3_mutex *mutex;      /* Mutex to access this object */
23647  os2ShmNode *pNext;         /* Next in list of all os2ShmNode objects */
23648
23649  int szRegion;              /* Size of shared-memory regions */
23650
23651  int nRegion;               /* Size of array apRegion */
23652  void **apRegion;           /* Array of pointers to shared-memory regions */
23653
23654  int nRef;                  /* Number of os2ShmLink objects pointing to this */
23655  os2ShmLink *pFirst;        /* First os2ShmLink object pointing to this */
23656
23657  HFILE hLockFile;           /* File used for inter-process memory locking */
23658  char shmBaseName[1];       /* Name of the memory object !!! must last !!! */
23659};
23660
23661
23662/*
23663** Structure used internally by this VFS to record the state of an
23664** open shared memory connection.
23665**
23666** The following fields are initialized when this object is created and
23667** are read-only thereafter:
23668**
23669**    os2Shm.pShmNode
23670**    os2Shm.id
23671**
23672** All other fields are read/write.  The os2Shm.pShmNode->mutex must be held
23673** while accessing any read/write fields.
23674*/
23675struct os2ShmLink {
23676  os2ShmNode *pShmNode;      /* The underlying os2ShmNode object */
23677  os2ShmLink *pNext;         /* Next os2Shm with the same os2ShmNode */
23678  u32 sharedMask;            /* Mask of shared locks held */
23679  u32 exclMask;              /* Mask of exclusive locks held */
23680#ifdef SQLITE_DEBUG
23681  u8 id;                     /* Id of this connection with its os2ShmNode */
23682#endif
23683};
23684
23685
23686/*
23687** A global list of all os2ShmNode objects.
23688**
23689** The os2ShmMutexHeld() must be true while reading or writing this list.
23690*/
23691static os2ShmNode *os2ShmNodeList = NULL;
23692
23693/*
23694** Constants used for locking
23695*/
23696#ifdef  SQLITE_OS2_NO_WAL_LOCK_FILE
23697#define OS2_SHM_BASE   (PENDING_BYTE + 0x10000)         /* first lock byte */
23698#else
23699#define OS2_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
23700#endif
23701
23702#define OS2_SHM_DMS    (OS2_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
23703
23704/*
23705** Apply advisory locks for all n bytes beginning at ofst.
23706*/
23707#define _SHM_UNLCK  1   /* no lock */
23708#define _SHM_RDLCK  2   /* shared lock, no wait */
23709#define _SHM_WRLCK  3   /* exlusive lock, no wait */
23710#define _SHM_WRLCK_WAIT 4 /* exclusive lock, wait */
23711static int os2ShmSystemLock(
23712  os2ShmNode *pNode,    /* Apply locks to this open shared-memory segment */
23713  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, _SHM_WRLCK or _SHM_WRLCK_WAIT */
23714  int ofst,             /* Offset to first byte to be locked/unlocked */
23715  int nByte             /* Number of bytes to lock or unlock */
23716){
23717  APIRET rc;
23718  FILELOCK area;
23719  ULONG mode, timeout;
23720
23721  /* Access to the os2ShmNode object is serialized by the caller */
23722  assert( sqlite3_mutex_held(pNode->mutex) || pNode->nRef==0 );
23723
23724  mode = 1;     /* shared lock */
23725  timeout = 0;  /* no wait */
23726  area.lOffset = ofst;
23727  area.lRange = nByte;
23728
23729  switch( lockType ) {
23730    case _SHM_WRLCK_WAIT:
23731      timeout = (ULONG)-1;      /* wait forever */
23732    case _SHM_WRLCK:
23733      mode = 0;                 /* exclusive lock */
23734    case _SHM_RDLCK:
23735      rc = DosSetFileLocks(pNode->hLockFile,
23736                           NULL, &area, timeout, mode);
23737      break;
23738    /* case _SHM_UNLCK: */
23739    default:
23740      rc = DosSetFileLocks(pNode->hLockFile,
23741                           &area, NULL, 0, 0);
23742      break;
23743  }
23744
23745  OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
23746           pNode->hLockFile,
23747           rc==SQLITE_OK ? "ok" : "failed",
23748           lockType==_SHM_UNLCK ? "Unlock" : "Lock",
23749           rc));
23750
23751  ERR_TRACE(rc, ("os2ShmSystemLock: %d %s\n", rc, pNode->shmBaseName))
23752
23753  return ( rc == 0 ) ?  SQLITE_OK : SQLITE_BUSY;
23754}
23755
23756/*
23757** Find an os2ShmNode in global list or allocate a new one, if not found.
23758**
23759** This is not a VFS shared-memory method; it is a utility function called
23760** by VFS shared-memory methods.
23761*/
23762static int os2OpenSharedMemory( os2File *fd, int szRegion ) {
23763  os2ShmLink *pLink;
23764  os2ShmNode *pNode;
23765  int cbShmName, rc = SQLITE_OK;
23766  char shmName[CCHMAXPATH + 30];
23767#ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23768  ULONG action;
23769#endif
23770
23771  /* We need some additional space at the end to append the region number */
23772  cbShmName = sprintf(shmName, "\\SHAREMEM\\%s", fd->zFullPathCp );
23773  if( cbShmName >= CCHMAXPATH-8 )
23774    return SQLITE_IOERR_SHMOPEN;
23775
23776  /* Replace colon in file name to form a valid shared memory name */
23777  shmName[10+1] = '!';
23778
23779  /* Allocate link object (we free it later in case of failure) */
23780  pLink = sqlite3_malloc( sizeof(*pLink) );
23781  if( !pLink )
23782    return SQLITE_NOMEM;
23783
23784  /* Access node list */
23785  os2ShmEnterMutex();
23786
23787  /* Find node by it's shared memory base name */
23788  for( pNode = os2ShmNodeList;
23789       pNode && stricmp(shmName, pNode->shmBaseName) != 0;
23790       pNode = pNode->pNext )   ;
23791
23792  /* Not found: allocate a new node */
23793  if( !pNode ) {
23794    pNode = sqlite3_malloc( sizeof(*pNode) + cbShmName );
23795    if( pNode ) {
23796      memset(pNode, 0, sizeof(*pNode) );
23797      pNode->szRegion = szRegion;
23798      pNode->hLockFile = (HFILE)-1;
23799      strcpy(pNode->shmBaseName, shmName);
23800
23801#ifdef SQLITE_OS2_NO_WAL_LOCK_FILE
23802      if( DosDupHandle(fd->h, &pNode->hLockFile) != 0 ) {
23803#else
23804      sprintf(shmName, "%s-lck", fd->zFullPathCp);
23805      if( DosOpen((PSZ)shmName, &pNode->hLockFile, &action, 0, FILE_NORMAL,
23806                  OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW,
23807                  OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYNONE |
23808                  OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR,
23809                  NULL) != 0 ) {
23810#endif
23811        sqlite3_free(pNode);
23812        rc = SQLITE_IOERR;
23813      } else {
23814        pNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
23815        if( !pNode->mutex ) {
23816          sqlite3_free(pNode);
23817          rc = SQLITE_NOMEM;
23818        }
23819      }
23820    } else {
23821      rc = SQLITE_NOMEM;
23822    }
23823
23824    if( rc == SQLITE_OK ) {
23825      pNode->pNext = os2ShmNodeList;
23826      os2ShmNodeList = pNode;
23827    } else {
23828      pNode = NULL;
23829    }
23830  } else if( pNode->szRegion != szRegion ) {
23831    rc = SQLITE_IOERR_SHMSIZE;
23832    pNode = NULL;
23833  }
23834
23835  if( pNode ) {
23836    sqlite3_mutex_enter(pNode->mutex);
23837
23838    memset(pLink, 0, sizeof(*pLink));
23839
23840    pLink->pShmNode = pNode;
23841    pLink->pNext = pNode->pFirst;
23842    pNode->pFirst = pLink;
23843    pNode->nRef++;
23844
23845    fd->pShmLink = pLink;
23846
23847    sqlite3_mutex_leave(pNode->mutex);
23848
23849  } else {
23850    /* Error occured. Free our link object. */
23851    sqlite3_free(pLink);
23852  }
23853
23854  os2ShmLeaveMutex();
23855
23856  ERR_TRACE(rc, ("os2OpenSharedMemory: %d  %s\n", rc, fd->zFullPathCp))
23857
23858  return rc;
23859}
23860
23861/*
23862** Purge the os2ShmNodeList list of all entries with nRef==0.
23863**
23864** This is not a VFS shared-memory method; it is a utility function called
23865** by VFS shared-memory methods.
23866*/
23867static void os2PurgeShmNodes( int deleteFlag ) {
23868  os2ShmNode *pNode;
23869  os2ShmNode **ppNode;
23870
23871  os2ShmEnterMutex();
23872
23873  ppNode = &os2ShmNodeList;
23874
23875  while( *ppNode ) {
23876    pNode = *ppNode;
23877
23878    if( pNode->nRef == 0 ) {
23879      *ppNode = pNode->pNext;
23880
23881      if( pNode->apRegion ) {
23882        /* Prevent other processes from resizing the shared memory */
23883        os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23884
23885        while( pNode->nRegion-- ) {
23886#ifdef SQLITE_DEBUG
23887          int rc =
23888#endif
23889          DosFreeMem(pNode->apRegion[pNode->nRegion]);
23890
23891          OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
23892                  (int)GetCurrentProcessId(), pNode->nRegion,
23893                  rc == 0 ? "ok" : "failed"));
23894        }
23895
23896        /* Allow other processes to resize the shared memory */
23897        os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
23898
23899        sqlite3_free(pNode->apRegion);
23900      }
23901
23902      DosClose(pNode->hLockFile);
23903
23904#ifndef SQLITE_OS2_NO_WAL_LOCK_FILE
23905      if( deleteFlag ) {
23906         char fileName[CCHMAXPATH];
23907         /* Skip "\\SHAREMEM\\" */
23908         sprintf(fileName, "%s-lck", pNode->shmBaseName + 10);
23909         /* restore colon */
23910         fileName[1] = ':';
23911
23912         DosForceDelete(fileName);
23913      }
23914#endif
23915
23916      sqlite3_mutex_free(pNode->mutex);
23917
23918      sqlite3_free(pNode);
23919
23920    } else {
23921      ppNode = &pNode->pNext;
23922    }
23923  }
23924
23925  os2ShmLeaveMutex();
23926}
23927
23928/*
23929** This function is called to obtain a pointer to region iRegion of the
23930** shared-memory associated with the database file id. Shared-memory regions
23931** are numbered starting from zero. Each shared-memory region is szRegion
23932** bytes in size.
23933**
23934** If an error occurs, an error code is returned and *pp is set to NULL.
23935**
23936** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
23937** region has not been allocated (by any client, including one running in a
23938** separate process), then *pp is set to NULL and SQLITE_OK returned. If
23939** bExtend is non-zero and the requested shared-memory region has not yet
23940** been allocated, it is allocated by this function.
23941**
23942** If the shared-memory region has already been allocated or is allocated by
23943** this call as described above, then it is mapped into this processes
23944** address space (if it is not already), *pp is set to point to the mapped
23945** memory and SQLITE_OK returned.
23946*/
23947static int os2ShmMap(
23948  sqlite3_file *id,               /* Handle open on database file */
23949  int iRegion,                    /* Region to retrieve */
23950  int szRegion,                   /* Size of regions */
23951  int bExtend,                    /* True to extend block if necessary */
23952  void volatile **pp              /* OUT: Mapped memory */
23953){
23954  PVOID pvTemp;
23955  void **apRegion;
23956  os2ShmNode *pNode;
23957  int n, rc = SQLITE_OK;
23958  char shmName[CCHMAXPATH];
23959  os2File *pFile = (os2File*)id;
23960
23961  *pp = NULL;
23962
23963  if( !pFile->pShmLink )
23964    rc = os2OpenSharedMemory( pFile, szRegion );
23965
23966  if( rc == SQLITE_OK ) {
23967    pNode = pFile->pShmLink->pShmNode ;
23968
23969    sqlite3_mutex_enter(pNode->mutex);
23970
23971    assert( szRegion==pNode->szRegion );
23972
23973    /* Unmapped region ? */
23974    if( iRegion >= pNode->nRegion ) {
23975      /* Prevent other processes from resizing the shared memory */
23976      os2ShmSystemLock(pNode, _SHM_WRLCK_WAIT, OS2_SHM_DMS, 1);
23977
23978      apRegion = sqlite3_realloc(
23979        pNode->apRegion, (iRegion + 1) * sizeof(apRegion[0]));
23980
23981      if( apRegion ) {
23982        pNode->apRegion = apRegion;
23983
23984        while( pNode->nRegion <= iRegion ) {
23985          sprintf(shmName, "%s-%u",
23986                  pNode->shmBaseName, pNode->nRegion);
23987
23988          if( DosGetNamedSharedMem(&pvTemp, (PSZ)shmName,
23989                PAG_READ | PAG_WRITE) != NO_ERROR ) {
23990            if( !bExtend )
23991              break;
23992
23993            if( DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23994                  PAG_READ | PAG_WRITE | PAG_COMMIT | OBJ_ANY) != NO_ERROR &&
23995                DosAllocSharedMem(&pvTemp, (PSZ)shmName, szRegion,
23996                  PAG_READ | PAG_WRITE | PAG_COMMIT) != NO_ERROR ) {
23997              rc = SQLITE_NOMEM;
23998              break;
23999            }
24000          }
24001
24002          apRegion[pNode->nRegion++] = pvTemp;
24003        }
24004
24005        /* zero out remaining entries */
24006        for( n = pNode->nRegion; n <= iRegion; n++ )
24007          pNode->apRegion[n] = NULL;
24008
24009        /* Return this region (maybe zero) */
24010        *pp = pNode->apRegion[iRegion];
24011      } else {
24012        rc = SQLITE_NOMEM;
24013      }
24014
24015      /* Allow other processes to resize the shared memory */
24016      os2ShmSystemLock(pNode, _SHM_UNLCK, OS2_SHM_DMS, 1);
24017
24018    } else {
24019      /* Region has been mapped previously */
24020      *pp = pNode->apRegion[iRegion];
24021    }
24022
24023    sqlite3_mutex_leave(pNode->mutex);
24024  }
24025
24026  ERR_TRACE(rc, ("os2ShmMap: %s iRgn = %d, szRgn = %d, bExt = %d : %d\n",
24027                 pFile->zFullPathCp, iRegion, szRegion, bExtend, rc))
24028
24029  return rc;
24030}
24031
24032/*
24033** Close a connection to shared-memory.  Delete the underlying
24034** storage if deleteFlag is true.
24035**
24036** If there is no shared memory associated with the connection then this
24037** routine is a harmless no-op.
24038*/
24039static int os2ShmUnmap(
24040  sqlite3_file *id,               /* The underlying database file */
24041  int deleteFlag                  /* Delete shared-memory if true */
24042){
24043  os2File *pFile = (os2File*)id;
24044  os2ShmLink *pLink = pFile->pShmLink;
24045
24046  if( pLink ) {
24047    int nRef = -1;
24048    os2ShmLink **ppLink;
24049    os2ShmNode *pNode = pLink->pShmNode;
24050
24051    sqlite3_mutex_enter(pNode->mutex);
24052
24053    for( ppLink = &pNode->pFirst;
24054         *ppLink && *ppLink != pLink;
24055         ppLink = &(*ppLink)->pNext )   ;
24056
24057    assert(*ppLink);
24058
24059    if( *ppLink ) {
24060      *ppLink = pLink->pNext;
24061      nRef = --pNode->nRef;
24062    } else {
24063      ERR_TRACE(1, ("os2ShmUnmap: link not found ! %s\n",
24064                    pNode->shmBaseName))
24065    }
24066
24067    pFile->pShmLink = NULL;
24068    sqlite3_free(pLink);
24069
24070    sqlite3_mutex_leave(pNode->mutex);
24071
24072    if( nRef == 0 )
24073      os2PurgeShmNodes( deleteFlag );
24074  }
24075
24076  return SQLITE_OK;
24077}
24078
24079/*
24080** Change the lock state for a shared-memory segment.
24081**
24082** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
24083** different here than in posix.  In xShmLock(), one can go from unlocked
24084** to shared and back or from unlocked to exclusive and back.  But one may
24085** not go from shared to exclusive or from exclusive to shared.
24086*/
24087static int os2ShmLock(
24088  sqlite3_file *id,          /* Database file holding the shared memory */
24089  int ofst,                  /* First lock to acquire or release */
24090  int n,                     /* Number of locks to acquire or release */
24091  int flags                  /* What to do with the lock */
24092){
24093  u32 mask;                             /* Mask of locks to take or release */
24094  int rc = SQLITE_OK;                   /* Result code */
24095  os2File *pFile = (os2File*)id;
24096  os2ShmLink *p = pFile->pShmLink;      /* The shared memory being locked */
24097  os2ShmLink *pX;                       /* For looping over all siblings */
24098  os2ShmNode *pShmNode = p->pShmNode;   /* Our node */
24099
24100  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
24101  assert( n>=1 );
24102  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
24103       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
24104       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
24105       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
24106  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
24107
24108  mask = (u32)((1U<<(ofst+n)) - (1U<<ofst));
24109  assert( n>1 || mask==(1<<ofst) );
24110
24111
24112  sqlite3_mutex_enter(pShmNode->mutex);
24113
24114  if( flags & SQLITE_SHM_UNLOCK ){
24115    u32 allMask = 0; /* Mask of locks held by siblings */
24116
24117    /* See if any siblings hold this same lock */
24118    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
24119      if( pX==p ) continue;
24120      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
24121      allMask |= pX->sharedMask;
24122    }
24123
24124    /* Unlock the system-level locks */
24125    if( (mask & allMask)==0 ){
24126      rc = os2ShmSystemLock(pShmNode, _SHM_UNLCK, ofst+OS2_SHM_BASE, n);
24127    }else{
24128      rc = SQLITE_OK;
24129    }
24130
24131    /* Undo the local locks */
24132    if( rc==SQLITE_OK ){
24133      p->exclMask &= ~mask;
24134      p->sharedMask &= ~mask;
24135    }
24136  }else if( flags & SQLITE_SHM_SHARED ){
24137    u32 allShared = 0;  /* Union of locks held by connections other than "p" */
24138
24139    /* Find out which shared locks are already held by sibling connections.
24140    ** If any sibling already holds an exclusive lock, go ahead and return
24141    ** SQLITE_BUSY.
24142    */
24143    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
24144      if( (pX->exclMask & mask)!=0 ){
24145        rc = SQLITE_BUSY;
24146        break;
24147      }
24148      allShared |= pX->sharedMask;
24149    }
24150
24151    /* Get shared locks at the system level, if necessary */
24152    if( rc==SQLITE_OK ){
24153      if( (allShared & mask)==0 ){
24154        rc = os2ShmSystemLock(pShmNode, _SHM_RDLCK, ofst+OS2_SHM_BASE, n);
24155      }else{
24156        rc = SQLITE_OK;
24157      }
24158    }
24159
24160    /* Get the local shared locks */
24161    if( rc==SQLITE_OK ){
24162      p->sharedMask |= mask;
24163    }
24164  }else{
24165    /* Make sure no sibling connections hold locks that will block this
24166    ** lock.  If any do, return SQLITE_BUSY right away.
24167    */
24168    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
24169      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
24170        rc = SQLITE_BUSY;
24171        break;
24172      }
24173    }
24174
24175    /* Get the exclusive locks at the system level.  Then if successful
24176    ** also mark the local connection as being locked.
24177    */
24178    if( rc==SQLITE_OK ){
24179      rc = os2ShmSystemLock(pShmNode, _SHM_WRLCK, ofst+OS2_SHM_BASE, n);
24180      if( rc==SQLITE_OK ){
24181        assert( (p->sharedMask & mask)==0 );
24182        p->exclMask |= mask;
24183      }
24184    }
24185  }
24186
24187  sqlite3_mutex_leave(pShmNode->mutex);
24188
24189  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
24190           p->id, (int)GetCurrentProcessId(), p->sharedMask, p->exclMask,
24191           rc ? "failed" : "ok"));
24192
24193  ERR_TRACE(rc, ("os2ShmLock: ofst = %d, n = %d, flags = 0x%x -> %d \n",
24194                 ofst, n, flags, rc))
24195
24196  return rc;
24197}
24198
24199/*
24200** Implement a memory barrier or memory fence on shared memory.
24201**
24202** All loads and stores begun before the barrier must complete before
24203** any load or store begun after the barrier.
24204*/
24205static void os2ShmBarrier(
24206  sqlite3_file *id                /* Database file holding the shared memory */
24207){
24208  UNUSED_PARAMETER(id);
24209  os2ShmEnterMutex();
24210  os2ShmLeaveMutex();
24211}
24212
24213#else
24214# define os2ShmMap     0
24215# define os2ShmLock    0
24216# define os2ShmBarrier 0
24217# define os2ShmUnmap   0
24218#endif /* #ifndef SQLITE_OMIT_WAL */
24219
24220
24221/*
24222** This vector defines all the methods that can operate on an
24223** sqlite3_file for os2.
24224*/
24225static const sqlite3_io_methods os2IoMethod = {
24226  2,                              /* iVersion */
24227  os2Close,                       /* xClose */
24228  os2Read,                        /* xRead */
24229  os2Write,                       /* xWrite */
24230  os2Truncate,                    /* xTruncate */
24231  os2Sync,                        /* xSync */
24232  os2FileSize,                    /* xFileSize */
24233  os2Lock,                        /* xLock */
24234  os2Unlock,                      /* xUnlock */
24235  os2CheckReservedLock,           /* xCheckReservedLock */
24236  os2FileControl,                 /* xFileControl */
24237  os2SectorSize,                  /* xSectorSize */
24238  os2DeviceCharacteristics,       /* xDeviceCharacteristics */
24239  os2ShmMap,                      /* xShmMap */
24240  os2ShmLock,                     /* xShmLock */
24241  os2ShmBarrier,                  /* xShmBarrier */
24242  os2ShmUnmap                     /* xShmUnmap */
24243};
24244
24245
24246/***************************************************************************
24247** Here ends the I/O methods that form the sqlite3_io_methods object.
24248**
24249** The next block of code implements the VFS methods.
24250****************************************************************************/
24251
24252/*
24253** Create a temporary file name in zBuf.  zBuf must be big enough to
24254** hold at pVfs->mxPathname characters.
24255*/
24256static int getTempname(int nBuf, char *zBuf ){
24257  static const char zChars[] =
24258    "abcdefghijklmnopqrstuvwxyz"
24259    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
24260    "0123456789";
24261  int i, j;
24262  PSZ zTempPathCp;
24263  char zTempPath[CCHMAXPATH];
24264  ULONG ulDriveNum, ulDriveMap;
24265
24266  /* It's odd to simulate an io-error here, but really this is just
24267  ** using the io-error infrastructure to test that SQLite handles this
24268  ** function failing.
24269  */
24270  SimulateIOError( return SQLITE_IOERR );
24271
24272  if( sqlite3_temp_directory ) {
24273    sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", sqlite3_temp_directory);
24274  } else if( DosScanEnv( (PSZ)"TEMP",   &zTempPathCp ) == NO_ERROR ||
24275             DosScanEnv( (PSZ)"TMP",    &zTempPathCp ) == NO_ERROR ||
24276             DosScanEnv( (PSZ)"TMPDIR", &zTempPathCp ) == NO_ERROR ) {
24277    char *zTempPathUTF = convertCpPathToUtf8( (char *)zTempPathCp );
24278    sqlite3_snprintf(CCHMAXPATH-30, zTempPath, "%s", zTempPathUTF);
24279    free( zTempPathUTF );
24280  } else if( DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ) == NO_ERROR ) {
24281    zTempPath[0] = (char)('A' + ulDriveNum - 1);
24282    zTempPath[1] = ':';
24283    zTempPath[2] = '\0';
24284  } else {
24285    zTempPath[0] = '\0';
24286  }
24287
24288  /* Strip off a trailing slashes or backslashes, otherwise we would get *
24289   * multiple (back)slashes which causes DosOpen() to fail.              *
24290   * Trailing spaces are not allowed, either.                            */
24291  j = sqlite3Strlen30(zTempPath);
24292  while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/' ||
24293                    zTempPath[j-1] == ' ' ) ){
24294    j--;
24295  }
24296  zTempPath[j] = '\0';
24297
24298  /* We use 20 bytes to randomize the name */
24299  sqlite3_snprintf(nBuf-22, zBuf,
24300                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
24301  j = sqlite3Strlen30(zBuf);
24302  sqlite3_randomness( 20, &zBuf[j] );
24303  for( i = 0; i < 20; i++, j++ ){
24304    zBuf[j] = zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
24305  }
24306  zBuf[j] = 0;
24307
24308  OSTRACE(( "TEMP FILENAME: %s\n", zBuf ));
24309  return SQLITE_OK;
24310}
24311
24312
24313/*
24314** Turn a relative pathname into a full pathname.  Write the full
24315** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
24316** bytes in size.
24317*/
24318static int os2FullPathname(
24319  sqlite3_vfs *pVfs,          /* Pointer to vfs object */
24320  const char *zRelative,      /* Possibly relative input path */
24321  int nFull,                  /* Size of output buffer in bytes */
24322  char *zFull                 /* Output buffer */
24323){
24324  char *zRelativeCp = convertUtf8PathToCp( zRelative );
24325  char zFullCp[CCHMAXPATH] = "\0";
24326  char *zFullUTF;
24327  APIRET rc = DosQueryPathInfo( (PSZ)zRelativeCp, FIL_QUERYFULLNAME,
24328                                zFullCp, CCHMAXPATH );
24329  free( zRelativeCp );
24330  zFullUTF = convertCpPathToUtf8( zFullCp );
24331  sqlite3_snprintf( nFull, zFull, zFullUTF );
24332  free( zFullUTF );
24333  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
24334}
24335
24336
24337/*
24338** Open a file.
24339*/
24340static int os2Open(
24341  sqlite3_vfs *pVfs,            /* Not used */
24342  const char *zName,            /* Name of the file (UTF-8) */
24343  sqlite3_file *id,             /* Write the SQLite file handle here */
24344  int flags,                    /* Open mode flags */
24345  int *pOutFlags                /* Status return flags */
24346){
24347  HFILE h;
24348  ULONG ulOpenFlags = 0;
24349  ULONG ulOpenMode = 0;
24350  ULONG ulAction = 0;
24351  ULONG rc;
24352  os2File *pFile = (os2File*)id;
24353  const char *zUtf8Name = zName;
24354  char *zNameCp;
24355  char  zTmpname[CCHMAXPATH];
24356
24357  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
24358  int isCreate     = (flags & SQLITE_OPEN_CREATE);
24359  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
24360#ifndef NDEBUG
24361  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
24362  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
24363  int eType        = (flags & 0xFFFFFF00);
24364  int isOpenJournal = (isCreate && (
24365        eType==SQLITE_OPEN_MASTER_JOURNAL
24366     || eType==SQLITE_OPEN_MAIN_JOURNAL
24367     || eType==SQLITE_OPEN_WAL
24368  ));
24369#endif
24370
24371  UNUSED_PARAMETER(pVfs);
24372  assert( id!=0 );
24373
24374  /* Check the following statements are true:
24375  **
24376  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
24377  **   (b) if CREATE is set, then READWRITE must also be set, and
24378  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
24379  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
24380  */
24381  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
24382  assert(isCreate==0 || isReadWrite);
24383  assert(isExclusive==0 || isCreate);
24384  assert(isDelete==0 || isCreate);
24385
24386  /* The main DB, main journal, WAL file and master journal are never
24387  ** automatically deleted. Nor are they ever temporary files.  */
24388  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
24389  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
24390  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
24391  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
24392
24393  /* Assert that the upper layer has set one of the "file-type" flags. */
24394  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
24395       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
24396       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
24397       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
24398  );
24399
24400  memset( pFile, 0, sizeof(*pFile) );
24401  pFile->h = (HFILE)-1;
24402
24403  /* If the second argument to this function is NULL, generate a
24404  ** temporary file name to use
24405  */
24406  if( !zUtf8Name ){
24407    assert(isDelete && !isOpenJournal);
24408    rc = getTempname(CCHMAXPATH, zTmpname);
24409    if( rc!=SQLITE_OK ){
24410      return rc;
24411    }
24412    zUtf8Name = zTmpname;
24413  }
24414
24415  if( isReadWrite ){
24416    ulOpenMode |= OPEN_ACCESS_READWRITE;
24417  }else{
24418    ulOpenMode |= OPEN_ACCESS_READONLY;
24419  }
24420
24421  /* Open in random access mode for possibly better speed.  Allow full
24422  ** sharing because file locks will provide exclusive access when needed.
24423  ** The handle should not be inherited by child processes and we don't
24424  ** want popups from the critical error handler.
24425  */
24426  ulOpenMode |= OPEN_FLAGS_RANDOM | OPEN_SHARE_DENYNONE |
24427                OPEN_FLAGS_NOINHERIT | OPEN_FLAGS_FAIL_ON_ERROR;
24428
24429  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
24430  ** created. SQLite doesn't use it to indicate "exclusive access"
24431  ** as it is usually understood.
24432  */
24433  if( isExclusive ){
24434    /* Creates a new file, only if it does not already exist. */
24435    /* If the file exists, it fails. */
24436    ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_FAIL_IF_EXISTS;
24437  }else if( isCreate ){
24438    /* Open existing file, or create if it doesn't exist */
24439    ulOpenFlags |= OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24440  }else{
24441    /* Opens a file, only if it exists. */
24442    ulOpenFlags |= OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS;
24443  }
24444
24445  zNameCp = convertUtf8PathToCp( zUtf8Name );
24446  rc = DosOpen( (PSZ)zNameCp,
24447                &h,
24448                &ulAction,
24449                0L,
24450                FILE_NORMAL,
24451                ulOpenFlags,
24452                ulOpenMode,
24453                (PEAOP2)NULL );
24454  free( zNameCp );
24455
24456  if( rc != NO_ERROR ){
24457    OSTRACE(( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
24458              rc, zUtf8Name, ulAction, ulOpenFlags, ulOpenMode ));
24459
24460    if( isReadWrite ){
24461      return os2Open( pVfs, zName, id,
24462                      ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
24463                      pOutFlags );
24464    }else{
24465      return SQLITE_CANTOPEN;
24466    }
24467  }
24468
24469  if( pOutFlags ){
24470    *pOutFlags = isReadWrite ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
24471  }
24472
24473  os2FullPathname( pVfs, zUtf8Name, sizeof( zTmpname ), zTmpname );
24474  pFile->zFullPathCp = convertUtf8PathToCp( zTmpname );
24475  pFile->pMethod = &os2IoMethod;
24476  pFile->flags = flags;
24477  pFile->h = h;
24478
24479  OpenCounter(+1);
24480  OSTRACE(( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags ));
24481  return SQLITE_OK;
24482}
24483
24484/*
24485** Delete the named file.
24486*/
24487static int os2Delete(
24488  sqlite3_vfs *pVfs,                     /* Not used on os2 */
24489  const char *zFilename,                 /* Name of file to delete */
24490  int syncDir                            /* Not used on os2 */
24491){
24492  APIRET rc;
24493  char *zFilenameCp;
24494  SimulateIOError( return SQLITE_IOERR_DELETE );
24495  zFilenameCp = convertUtf8PathToCp( zFilename );
24496  rc = DosDelete( (PSZ)zFilenameCp );
24497  free( zFilenameCp );
24498  OSTRACE(( "DELETE \"%s\"\n", zFilename ));
24499  return (rc == NO_ERROR ||
24500          rc == ERROR_FILE_NOT_FOUND ||
24501          rc == ERROR_PATH_NOT_FOUND ) ? SQLITE_OK : SQLITE_IOERR_DELETE;
24502}
24503
24504/*
24505** Check the existance and status of a file.
24506*/
24507static int os2Access(
24508  sqlite3_vfs *pVfs,        /* Not used on os2 */
24509  const char *zFilename,    /* Name of file to check */
24510  int flags,                /* Type of test to make on this file */
24511  int *pOut                 /* Write results here */
24512){
24513  APIRET rc;
24514  FILESTATUS3 fsts3ConfigInfo;
24515  char *zFilenameCp;
24516
24517  UNUSED_PARAMETER(pVfs);
24518  SimulateIOError( return SQLITE_IOERR_ACCESS; );
24519
24520  zFilenameCp = convertUtf8PathToCp( zFilename );
24521  rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
24522                         &fsts3ConfigInfo, sizeof(FILESTATUS3) );
24523  free( zFilenameCp );
24524  OSTRACE(( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
24525            fsts3ConfigInfo.attrFile, flags, rc ));
24526
24527  switch( flags ){
24528    case SQLITE_ACCESS_EXISTS:
24529      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
24530      ** as if it does not exist.
24531      */
24532      if( fsts3ConfigInfo.cbFile == 0 )
24533        rc = ERROR_FILE_NOT_FOUND;
24534      break;
24535    case SQLITE_ACCESS_READ:
24536      break;
24537    case SQLITE_ACCESS_READWRITE:
24538      if( fsts3ConfigInfo.attrFile & FILE_READONLY )
24539        rc = ERROR_ACCESS_DENIED;
24540      break;
24541    default:
24542      rc = ERROR_FILE_NOT_FOUND;
24543      assert( !"Invalid flags argument" );
24544  }
24545
24546  *pOut = (rc == NO_ERROR);
24547  OSTRACE(( "ACCESS %s flags %d: rc=%d\n", zFilename, flags, *pOut ));
24548
24549  return SQLITE_OK;
24550}
24551
24552
24553#ifndef SQLITE_OMIT_LOAD_EXTENSION
24554/*
24555** Interfaces for opening a shared library, finding entry points
24556** within the shared library, and closing the shared library.
24557*/
24558/*
24559** Interfaces for opening a shared library, finding entry points
24560** within the shared library, and closing the shared library.
24561*/
24562static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
24563  HMODULE hmod;
24564  APIRET rc;
24565  char *zFilenameCp = convertUtf8PathToCp(zFilename);
24566  rc = DosLoadModule(NULL, 0, (PSZ)zFilenameCp, &hmod);
24567  free(zFilenameCp);
24568  return rc != NO_ERROR ? 0 : (void*)hmod;
24569}
24570/*
24571** A no-op since the error code is returned on the DosLoadModule call.
24572** os2Dlopen returns zero if DosLoadModule is not successful.
24573*/
24574static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
24575/* no-op */
24576}
24577static void (*os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
24578  PFN pfn;
24579  APIRET rc;
24580  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)zSymbol, &pfn);
24581  if( rc != NO_ERROR ){
24582    /* if the symbol itself was not found, search again for the same
24583     * symbol with an extra underscore, that might be needed depending
24584     * on the calling convention */
24585    char _zSymbol[256] = "_";
24586    strncat(_zSymbol, zSymbol, 254);
24587    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, (PSZ)_zSymbol, &pfn);
24588  }
24589  return rc != NO_ERROR ? 0 : (void(*)(void))pfn;
24590}
24591static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
24592  DosFreeModule((HMODULE)pHandle);
24593}
24594#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
24595  #define os2DlOpen 0
24596  #define os2DlError 0
24597  #define os2DlSym 0
24598  #define os2DlClose 0
24599#endif
24600
24601
24602/*
24603** Write up to nBuf bytes of randomness into zBuf.
24604*/
24605static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
24606  int n = 0;
24607#if defined(SQLITE_TEST)
24608  n = nBuf;
24609  memset(zBuf, 0, nBuf);
24610#else
24611  int i;
24612  PPIB ppib;
24613  PTIB ptib;
24614  DATETIME dt;
24615  static unsigned c = 0;
24616  /* Ordered by variation probability */
24617  static ULONG svIdx[6] = { QSV_MS_COUNT, QSV_TIME_LOW,
24618                            QSV_MAXPRMEM, QSV_MAXSHMEM,
24619                            QSV_TOTAVAILMEM, QSV_TOTRESMEM };
24620
24621  /* 8 bytes; timezone and weekday don't increase the randomness much */
24622  if( (int)sizeof(dt)-3 <= nBuf - n ){
24623    c += 0x0100;
24624    DosGetDateTime(&dt);
24625    dt.year = (USHORT)((dt.year - 1900) | c);
24626    memcpy(&zBuf[n], &dt, sizeof(dt)-3);
24627    n += sizeof(dt)-3;
24628  }
24629
24630  /* 4 bytes; PIDs and TIDs are 16 bit internally, so combine them */
24631  if( (int)sizeof(ULONG) <= nBuf - n ){
24632    DosGetInfoBlocks(&ptib, &ppib);
24633    *(PULONG)&zBuf[n] = MAKELONG(ppib->pib_ulpid,
24634                                 ptib->tib_ptib2->tib2_ultid);
24635    n += sizeof(ULONG);
24636  }
24637
24638  /* Up to 6 * 4 bytes; variables depend on the system state */
24639  for( i = 0; i < 6 && (int)sizeof(ULONG) <= nBuf - n; i++ ){
24640    DosQuerySysInfo(svIdx[i], svIdx[i],
24641                    (PULONG)&zBuf[n], sizeof(ULONG));
24642    n += sizeof(ULONG);
24643  }
24644#endif
24645
24646  return n;
24647}
24648
24649/*
24650** Sleep for a little while.  Return the amount of time slept.
24651** The argument is the number of microseconds we want to sleep.
24652** The return value is the number of microseconds of sleep actually
24653** requested from the underlying operating system, a number which
24654** might be greater than or equal to the argument, but not less
24655** than the argument.
24656*/
24657static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
24658  DosSleep( (microsec/1000) );
24659  return microsec;
24660}
24661
24662/*
24663** The following variable, if set to a non-zero value, becomes the result
24664** returned from sqlite3OsCurrentTime().  This is used for testing.
24665*/
24666#ifdef SQLITE_TEST
24667SQLITE_API int sqlite3_current_time = 0;
24668#endif
24669
24670/*
24671** Find the current time (in Universal Coordinated Time).  Write into *piNow
24672** the current time and date as a Julian Day number times 86_400_000.  In
24673** other words, write into *piNow the number of milliseconds since the Julian
24674** epoch of noon in Greenwich on November 24, 4714 B.C according to the
24675** proleptic Gregorian calendar.
24676**
24677** On success, return 0.  Return 1 if the time and date cannot be found.
24678*/
24679static int os2CurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
24680#ifdef SQLITE_TEST
24681  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
24682#endif
24683  int year, month, datepart, timepart;
24684
24685  DATETIME dt;
24686  DosGetDateTime( &dt );
24687
24688  year = dt.year;
24689  month = dt.month;
24690
24691  /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
24692  ** http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c
24693  ** Calculate the Julian days
24694  */
24695  datepart = (int)dt.day - 32076 +
24696    1461*(year + 4800 + (month - 14)/12)/4 +
24697    367*(month - 2 - (month - 14)/12*12)/12 -
24698    3*((year + 4900 + (month - 14)/12)/100)/4;
24699
24700  /* Time in milliseconds, hours to noon added */
24701  timepart = 12*3600*1000 + dt.hundredths*10 + dt.seconds*1000 +
24702    ((int)dt.minutes + dt.timezone)*60*1000 + dt.hours*3600*1000;
24703
24704  *piNow = (sqlite3_int64)datepart*86400*1000 + timepart;
24705
24706#ifdef SQLITE_TEST
24707  if( sqlite3_current_time ){
24708    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
24709  }
24710#endif
24711
24712  UNUSED_PARAMETER(pVfs);
24713  return 0;
24714}
24715
24716/*
24717** Find the current time (in Universal Coordinated Time).  Write the
24718** current time and date as a Julian Day number into *prNow and
24719** return 0.  Return 1 if the time and date cannot be found.
24720*/
24721static int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
24722  int rc;
24723  sqlite3_int64 i;
24724  rc = os2CurrentTimeInt64(pVfs, &i);
24725  if( !rc ){
24726    *prNow = i/86400000.0;
24727  }
24728  return rc;
24729}
24730
24731/*
24732** The idea is that this function works like a combination of
24733** GetLastError() and FormatMessage() on windows (or errno and
24734** strerror_r() on unix). After an error is returned by an OS
24735** function, SQLite calls this function with zBuf pointing to
24736** a buffer of nBuf bytes. The OS layer should populate the
24737** buffer with a nul-terminated UTF-8 encoded error message
24738** describing the last IO error to have occurred within the calling
24739** thread.
24740**
24741** If the error message is too large for the supplied buffer,
24742** it should be truncated. The return value of xGetLastError
24743** is zero if the error message fits in the buffer, or non-zero
24744** otherwise (if the message was truncated). If non-zero is returned,
24745** then it is not necessary to include the nul-terminator character
24746** in the output buffer.
24747**
24748** Not supplying an error message will have no adverse effect
24749** on SQLite. It is fine to have an implementation that never
24750** returns an error message:
24751**
24752**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24753**     assert(zBuf[0]=='\0');
24754**     return 0;
24755**   }
24756**
24757** However if an error message is supplied, it will be incorporated
24758** by sqlite into the error message available to the user using
24759** sqlite3_errmsg(), possibly making IO errors easier to debug.
24760*/
24761static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
24762  assert(zBuf[0]=='\0');
24763  return 0;
24764}
24765
24766/*
24767** Initialize and deinitialize the operating system interface.
24768*/
24769SQLITE_API int sqlite3_os_init(void){
24770  static sqlite3_vfs os2Vfs = {
24771    3,                 /* iVersion */
24772    sizeof(os2File),   /* szOsFile */
24773    CCHMAXPATH,        /* mxPathname */
24774    0,                 /* pNext */
24775    "os2",             /* zName */
24776    0,                 /* pAppData */
24777
24778    os2Open,           /* xOpen */
24779    os2Delete,         /* xDelete */
24780    os2Access,         /* xAccess */
24781    os2FullPathname,   /* xFullPathname */
24782    os2DlOpen,         /* xDlOpen */
24783    os2DlError,        /* xDlError */
24784    os2DlSym,          /* xDlSym */
24785    os2DlClose,        /* xDlClose */
24786    os2Randomness,     /* xRandomness */
24787    os2Sleep,          /* xSleep */
24788    os2CurrentTime,    /* xCurrentTime */
24789    os2GetLastError,   /* xGetLastError */
24790    os2CurrentTimeInt64, /* xCurrentTimeInt64 */
24791    0,                 /* xSetSystemCall */
24792    0,                 /* xGetSystemCall */
24793    0                  /* xNextSystemCall */
24794  };
24795  sqlite3_vfs_register(&os2Vfs, 1);
24796  initUconvObjects();
24797/*  sqlite3OSTrace = 1; */
24798  return SQLITE_OK;
24799}
24800SQLITE_API int sqlite3_os_end(void){
24801  freeUconvObjects();
24802  return SQLITE_OK;
24803}
24804
24805#endif /* SQLITE_OS_OS2 */
24806
24807/************** End of os_os2.c **********************************************/
24808/************** Begin file os_unix.c *****************************************/
24809/*
24810** 2004 May 22
24811**
24812** The author disclaims copyright to this source code.  In place of
24813** a legal notice, here is a blessing:
24814**
24815**    May you do good and not evil.
24816**    May you find forgiveness for yourself and forgive others.
24817**    May you share freely, never taking more than you give.
24818**
24819******************************************************************************
24820**
24821** This file contains the VFS implementation for unix-like operating systems
24822** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
24823**
24824** There are actually several different VFS implementations in this file.
24825** The differences are in the way that file locking is done.  The default
24826** implementation uses Posix Advisory Locks.  Alternative implementations
24827** use flock(), dot-files, various proprietary locking schemas, or simply
24828** skip locking all together.
24829**
24830** This source file is organized into divisions where the logic for various
24831** subfunctions is contained within the appropriate division.  PLEASE
24832** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
24833** in the correct division and should be clearly labeled.
24834**
24835** The layout of divisions is as follows:
24836**
24837**   *  General-purpose declarations and utility functions.
24838**   *  Unique file ID logic used by VxWorks.
24839**   *  Various locking primitive implementations (all except proxy locking):
24840**      + for Posix Advisory Locks
24841**      + for no-op locks
24842**      + for dot-file locks
24843**      + for flock() locking
24844**      + for named semaphore locks (VxWorks only)
24845**      + for AFP filesystem locks (MacOSX only)
24846**   *  sqlite3_file methods not associated with locking.
24847**   *  Definitions of sqlite3_io_methods objects for all locking
24848**      methods plus "finder" functions for each locking method.
24849**   *  sqlite3_vfs method implementations.
24850**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
24851**   *  Definitions of sqlite3_vfs objects for all locking methods
24852**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
24853*/
24854#if SQLITE_OS_UNIX              /* This file is used on unix only */
24855
24856/*
24857** There are various methods for file locking used for concurrency
24858** control:
24859**
24860**   1. POSIX locking (the default),
24861**   2. No locking,
24862**   3. Dot-file locking,
24863**   4. flock() locking,
24864**   5. AFP locking (OSX only),
24865**   6. Named POSIX semaphores (VXWorks only),
24866**   7. proxy locking. (OSX only)
24867**
24868** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
24869** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
24870** selection of the appropriate locking style based on the filesystem
24871** where the database is located.
24872*/
24873#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
24874#  if defined(__APPLE__)
24875#    define SQLITE_ENABLE_LOCKING_STYLE 1
24876#  else
24877#    define SQLITE_ENABLE_LOCKING_STYLE 0
24878#  endif
24879#endif
24880
24881/*
24882** Define the OS_VXWORKS pre-processor macro to 1 if building on
24883** vxworks, or 0 otherwise.
24884*/
24885#ifndef OS_VXWORKS
24886#  if defined(__RTP__) || defined(_WRS_KERNEL)
24887#    define OS_VXWORKS 1
24888#  else
24889#    define OS_VXWORKS 0
24890#  endif
24891#endif
24892
24893/*
24894** These #defines should enable >2GB file support on Posix if the
24895** underlying operating system supports it.  If the OS lacks
24896** large file support, these should be no-ops.
24897**
24898** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
24899** on the compiler command line.  This is necessary if you are compiling
24900** on a recent machine (ex: RedHat 7.2) but you want your code to work
24901** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
24902** without this option, LFS is enable.  But LFS does not exist in the kernel
24903** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
24904** portability you should omit LFS.
24905**
24906** The previous paragraph was written in 2005.  (This paragraph is written
24907** on 2008-11-28.) These days, all Linux kernels support large files, so
24908** you should probably leave LFS enabled.  But some embedded platforms might
24909** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
24910*/
24911#ifndef SQLITE_DISABLE_LFS
24912# define _LARGE_FILE       1
24913# ifndef _FILE_OFFSET_BITS
24914#   define _FILE_OFFSET_BITS 64
24915# endif
24916# define _LARGEFILE_SOURCE 1
24917#endif
24918
24919/*
24920** standard include files.
24921*/
24922#include <sys/types.h>
24923#include <sys/stat.h>
24924#include <fcntl.h>
24925#include <unistd.h>
24926/* #include <time.h> */
24927#include <sys/time.h>
24928#include <errno.h>
24929#ifndef SQLITE_OMIT_WAL
24930#include <sys/mman.h>
24931#endif
24932
24933
24934#if SQLITE_ENABLE_LOCKING_STYLE
24935# include <sys/ioctl.h>
24936# if OS_VXWORKS
24937#  include <semaphore.h>
24938#  include <limits.h>
24939# else
24940#  include <sys/file.h>
24941#  include <sys/param.h>
24942# endif
24943#endif /* SQLITE_ENABLE_LOCKING_STYLE */
24944
24945#if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
24946# include <sys/mount.h>
24947#endif
24948
24949#ifdef HAVE_UTIME
24950# include <utime.h>
24951#endif
24952
24953/*
24954** Allowed values of unixFile.fsFlags
24955*/
24956#define SQLITE_FSFLAGS_IS_MSDOS     0x1
24957
24958/*
24959** If we are to be thread-safe, include the pthreads header and define
24960** the SQLITE_UNIX_THREADS macro.
24961*/
24962#if SQLITE_THREADSAFE
24963/* # include <pthread.h> */
24964# define SQLITE_UNIX_THREADS 1
24965#endif
24966
24967/*
24968** Default permissions when creating a new file
24969*/
24970#ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
24971# define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
24972#endif
24973
24974/*
24975 ** Default permissions when creating auto proxy dir
24976 */
24977#ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
24978# define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
24979#endif
24980
24981/*
24982** Maximum supported path-length.
24983*/
24984#define MAX_PATHNAME 512
24985
24986/*
24987** Only set the lastErrno if the error code is a real error and not
24988** a normal expected return code of SQLITE_BUSY or SQLITE_OK
24989*/
24990#define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
24991
24992/* Forward references */
24993typedef struct unixShm unixShm;               /* Connection shared memory */
24994typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
24995typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
24996typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
24997
24998/*
24999** Sometimes, after a file handle is closed by SQLite, the file descriptor
25000** cannot be closed immediately. In these cases, instances of the following
25001** structure are used to store the file descriptor while waiting for an
25002** opportunity to either close or reuse it.
25003*/
25004struct UnixUnusedFd {
25005  int fd;                   /* File descriptor to close */
25006  int flags;                /* Flags this file descriptor was opened with */
25007  UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
25008};
25009
25010/*
25011** The unixFile structure is subclass of sqlite3_file specific to the unix
25012** VFS implementations.
25013*/
25014typedef struct unixFile unixFile;
25015struct unixFile {
25016  sqlite3_io_methods const *pMethod;  /* Always the first entry */
25017  sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
25018  unixInodeInfo *pInode;              /* Info about locks on this inode */
25019  int h;                              /* The file descriptor */
25020  unsigned char eFileLock;            /* The type of lock held on this fd */
25021  unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
25022  int lastErrno;                      /* The unix errno from last I/O error */
25023  void *lockingContext;               /* Locking style specific state */
25024  UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
25025  const char *zPath;                  /* Name of the file */
25026  unixShm *pShm;                      /* Shared memory segment information */
25027  int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
25028#if SQLITE_ENABLE_LOCKING_STYLE
25029  int openFlags;                      /* The flags specified at open() */
25030#endif
25031#if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
25032  unsigned fsFlags;                   /* cached details from statfs() */
25033#endif
25034#if OS_VXWORKS
25035  struct vxworksFileId *pId;          /* Unique file ID */
25036#endif
25037#ifndef NDEBUG
25038  /* The next group of variables are used to track whether or not the
25039  ** transaction counter in bytes 24-27 of database files are updated
25040  ** whenever any part of the database changes.  An assertion fault will
25041  ** occur if a file is updated without also updating the transaction
25042  ** counter.  This test is made to avoid new problems similar to the
25043  ** one described by ticket #3584.
25044  */
25045  unsigned char transCntrChng;   /* True if the transaction counter changed */
25046  unsigned char dbUpdate;        /* True if any part of database file changed */
25047  unsigned char inNormalWrite;   /* True if in a normal write operation */
25048#endif
25049#ifdef SQLITE_TEST
25050  /* In test mode, increase the size of this structure a bit so that
25051  ** it is larger than the struct CrashFile defined in test6.c.
25052  */
25053  char aPadding[32];
25054#endif
25055};
25056
25057/*
25058** Allowed values for the unixFile.ctrlFlags bitmask:
25059*/
25060#define UNIXFILE_EXCL        0x01     /* Connections from one process only */
25061#define UNIXFILE_RDONLY      0x02     /* Connection is read only */
25062#define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
25063#ifndef SQLITE_DISABLE_DIRSYNC
25064# define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
25065#else
25066# define UNIXFILE_DIRSYNC    0x00
25067#endif
25068#define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
25069#define UNIXFILE_DELETE      0x20     /* Delete on close */
25070#define UNIXFILE_URI         0x40     /* Filename might have query parameters */
25071#define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
25072#define UNIXFILE_CHOWN      0x100     /* File ownership was changed */
25073
25074/*
25075** Include code that is common to all os_*.c files
25076*/
25077/************** Include os_common.h in the middle of os_unix.c ***************/
25078/************** Begin file os_common.h ***************************************/
25079/*
25080** 2004 May 22
25081**
25082** The author disclaims copyright to this source code.  In place of
25083** a legal notice, here is a blessing:
25084**
25085**    May you do good and not evil.
25086**    May you find forgiveness for yourself and forgive others.
25087**    May you share freely, never taking more than you give.
25088**
25089******************************************************************************
25090**
25091** This file contains macros and a little bit of code that is common to
25092** all of the platform-specific files (os_*.c) and is #included into those
25093** files.
25094**
25095** This file should be #included by the os_*.c files only.  It is not a
25096** general purpose header file.
25097*/
25098#ifndef _OS_COMMON_H_
25099#define _OS_COMMON_H_
25100
25101/*
25102** At least two bugs have slipped in because we changed the MEMORY_DEBUG
25103** macro to SQLITE_DEBUG and some older makefiles have not yet made the
25104** switch.  The following code should catch this problem at compile-time.
25105*/
25106#ifdef MEMORY_DEBUG
25107# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
25108#endif
25109
25110#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25111# ifndef SQLITE_DEBUG_OS_TRACE
25112#   define SQLITE_DEBUG_OS_TRACE 0
25113# endif
25114  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
25115# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
25116#else
25117# define OSTRACE(X)
25118#endif
25119
25120/*
25121** Macros for performance tracing.  Normally turned off.  Only works
25122** on i486 hardware.
25123*/
25124#ifdef SQLITE_PERFORMANCE_TRACE
25125
25126/*
25127** hwtime.h contains inline assembler code for implementing
25128** high-performance timing routines.
25129*/
25130/************** Include hwtime.h in the middle of os_common.h ****************/
25131/************** Begin file hwtime.h ******************************************/
25132/*
25133** 2008 May 27
25134**
25135** The author disclaims copyright to this source code.  In place of
25136** a legal notice, here is a blessing:
25137**
25138**    May you do good and not evil.
25139**    May you find forgiveness for yourself and forgive others.
25140**    May you share freely, never taking more than you give.
25141**
25142******************************************************************************
25143**
25144** This file contains inline asm code for retrieving "high-performance"
25145** counters for x86 class CPUs.
25146*/
25147#ifndef _HWTIME_H_
25148#define _HWTIME_H_
25149
25150/*
25151** The following routine only works on pentium-class (or newer) processors.
25152** It uses the RDTSC opcode to read the cycle count value out of the
25153** processor and returns that value.  This can be used for high-res
25154** profiling.
25155*/
25156#if (defined(__GNUC__) || defined(_MSC_VER)) && \
25157      (defined(i386) || defined(__i386__) || defined(_M_IX86))
25158
25159  #if defined(__GNUC__)
25160
25161  __inline__ sqlite_uint64 sqlite3Hwtime(void){
25162     unsigned int lo, hi;
25163     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
25164     return (sqlite_uint64)hi << 32 | lo;
25165  }
25166
25167  #elif defined(_MSC_VER)
25168
25169  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
25170     __asm {
25171        rdtsc
25172        ret       ; return value at EDX:EAX
25173     }
25174  }
25175
25176  #endif
25177
25178#elif (defined(__GNUC__) && defined(__x86_64__))
25179
25180  __inline__ sqlite_uint64 sqlite3Hwtime(void){
25181      unsigned long val;
25182      __asm__ __volatile__ ("rdtsc" : "=A" (val));
25183      return val;
25184  }
25185
25186#elif (defined(__GNUC__) && defined(__ppc__))
25187
25188  __inline__ sqlite_uint64 sqlite3Hwtime(void){
25189      unsigned long long retval;
25190      unsigned long junk;
25191      __asm__ __volatile__ ("\n\
25192          1:      mftbu   %1\n\
25193                  mftb    %L0\n\
25194                  mftbu   %0\n\
25195                  cmpw    %0,%1\n\
25196                  bne     1b"
25197                  : "=r" (retval), "=r" (junk));
25198      return retval;
25199  }
25200
25201#else
25202
25203  #error Need implementation of sqlite3Hwtime() for your platform.
25204
25205  /*
25206  ** To compile without implementing sqlite3Hwtime() for your platform,
25207  ** you can remove the above #error and use the following
25208  ** stub function.  You will lose timing support for many
25209  ** of the debugging and testing utilities, but it should at
25210  ** least compile and run.
25211  */
25212SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25213
25214#endif
25215
25216#endif /* !defined(_HWTIME_H_) */
25217
25218/************** End of hwtime.h **********************************************/
25219/************** Continuing where we left off in os_common.h ******************/
25220
25221static sqlite_uint64 g_start;
25222static sqlite_uint64 g_elapsed;
25223#define TIMER_START       g_start=sqlite3Hwtime()
25224#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
25225#define TIMER_ELAPSED     g_elapsed
25226#else
25227#define TIMER_START
25228#define TIMER_END
25229#define TIMER_ELAPSED     ((sqlite_uint64)0)
25230#endif
25231
25232/*
25233** If we compile with the SQLITE_TEST macro set, then the following block
25234** of code will give us the ability to simulate a disk I/O error.  This
25235** is used for testing the I/O recovery logic.
25236*/
25237#ifdef SQLITE_TEST
25238SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
25239SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
25240SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
25241SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
25242SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
25243SQLITE_API int sqlite3_diskfull_pending = 0;
25244SQLITE_API int sqlite3_diskfull = 0;
25245#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25246#define SimulateIOError(CODE)  \
25247  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25248       || sqlite3_io_error_pending-- == 1 )  \
25249              { local_ioerr(); CODE; }
25250static void local_ioerr(){
25251  IOTRACE(("IOERR\n"));
25252  sqlite3_io_error_hit++;
25253  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25254}
25255#define SimulateDiskfullError(CODE) \
25256   if( sqlite3_diskfull_pending ){ \
25257     if( sqlite3_diskfull_pending == 1 ){ \
25258       local_ioerr(); \
25259       sqlite3_diskfull = 1; \
25260       sqlite3_io_error_hit = 1; \
25261       CODE; \
25262     }else{ \
25263       sqlite3_diskfull_pending--; \
25264     } \
25265   }
25266#else
25267#define SimulateIOErrorBenign(X)
25268#define SimulateIOError(A)
25269#define SimulateDiskfullError(A)
25270#endif
25271
25272/*
25273** When testing, keep a count of the number of open files.
25274*/
25275#ifdef SQLITE_TEST
25276SQLITE_API int sqlite3_open_file_count = 0;
25277#define OpenCounter(X)  sqlite3_open_file_count+=(X)
25278#else
25279#define OpenCounter(X)
25280#endif
25281
25282#endif /* !defined(_OS_COMMON_H_) */
25283
25284/************** End of os_common.h *******************************************/
25285/************** Continuing where we left off in os_unix.c ********************/
25286
25287/*
25288** Define various macros that are missing from some systems.
25289*/
25290#ifndef O_LARGEFILE
25291# define O_LARGEFILE 0
25292#endif
25293#ifdef SQLITE_DISABLE_LFS
25294# undef O_LARGEFILE
25295# define O_LARGEFILE 0
25296#endif
25297#ifndef O_NOFOLLOW
25298# define O_NOFOLLOW 0
25299#endif
25300#ifndef O_BINARY
25301# define O_BINARY 0
25302#endif
25303
25304/*
25305** The threadid macro resolves to the thread-id or to 0.  Used for
25306** testing and debugging only.
25307*/
25308#if SQLITE_THREADSAFE
25309#define threadid pthread_self()
25310#else
25311#define threadid 0
25312#endif
25313
25314/*
25315** Different Unix systems declare open() in different ways.  Same use
25316** open(const char*,int,mode_t).  Others use open(const char*,int,...).
25317** The difference is important when using a pointer to the function.
25318**
25319** The safest way to deal with the problem is to always use this wrapper
25320** which always has the same well-defined interface.
25321*/
25322static int posixOpen(const char *zFile, int flags, int mode){
25323  return open(zFile, flags, mode);
25324}
25325
25326/* Forward reference */
25327static int openDirectory(const char*, int*);
25328
25329/*
25330** Many system calls are accessed through pointer-to-functions so that
25331** they may be overridden at runtime to facilitate fault injection during
25332** testing and sandboxing.  The following array holds the names and pointers
25333** to all overrideable system calls.
25334*/
25335static struct unix_syscall {
25336  const char *zName;            /* Name of the sytem call */
25337  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
25338  sqlite3_syscall_ptr pDefault; /* Default value */
25339} aSyscall[] = {
25340  { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
25341#define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
25342
25343  { "close",        (sqlite3_syscall_ptr)close,      0  },
25344#define osClose     ((int(*)(int))aSyscall[1].pCurrent)
25345
25346  { "access",       (sqlite3_syscall_ptr)access,     0  },
25347#define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
25348
25349  { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
25350#define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
25351
25352  { "stat",         (sqlite3_syscall_ptr)stat,       0  },
25353#define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
25354
25355/*
25356** The DJGPP compiler environment looks mostly like Unix, but it
25357** lacks the fcntl() system call.  So redefine fcntl() to be something
25358** that always succeeds.  This means that locking does not occur under
25359** DJGPP.  But it is DOS - what did you expect?
25360*/
25361#ifdef __DJGPP__
25362  { "fstat",        0,                 0  },
25363#define osFstat(a,b,c)    0
25364#else
25365  { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
25366#define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
25367#endif
25368
25369  { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
25370#define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
25371
25372  { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
25373#define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
25374
25375  { "read",         (sqlite3_syscall_ptr)read,       0  },
25376#define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
25377
25378#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25379  { "pread",        (sqlite3_syscall_ptr)pread,      0  },
25380#else
25381  { "pread",        (sqlite3_syscall_ptr)0,          0  },
25382#endif
25383#define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
25384
25385#if defined(USE_PREAD64)
25386  { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
25387#else
25388  { "pread64",      (sqlite3_syscall_ptr)0,          0  },
25389#endif
25390#define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
25391
25392  { "write",        (sqlite3_syscall_ptr)write,      0  },
25393#define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
25394
25395#if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25396  { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
25397#else
25398  { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
25399#endif
25400#define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
25401                    aSyscall[12].pCurrent)
25402
25403#if defined(USE_PREAD64)
25404  { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
25405#else
25406  { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
25407#endif
25408#define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
25409                    aSyscall[13].pCurrent)
25410
25411#if SQLITE_ENABLE_LOCKING_STYLE
25412  { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
25413#else
25414  { "fchmod",       (sqlite3_syscall_ptr)0,          0  },
25415#endif
25416#define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25417
25418#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25419  { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
25420#else
25421  { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
25422#endif
25423#define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25424
25425  { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
25426#define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
25427
25428  { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
25429#define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25430
25431  { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
25432#define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
25433
25434  { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
25435#define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
25436
25437  { "fchown",       (sqlite3_syscall_ptr)fchown,          0 },
25438#define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
25439
25440  { "umask",        (sqlite3_syscall_ptr)umask,           0 },
25441#define osUmask     ((mode_t(*)(mode_t))aSyscall[21].pCurrent)
25442
25443}; /* End of the overrideable system calls */
25444
25445/*
25446** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25447** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
25448** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25449** system call named zName.
25450*/
25451static int unixSetSystemCall(
25452  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
25453  const char *zName,            /* Name of system call to override */
25454  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
25455){
25456  unsigned int i;
25457  int rc = SQLITE_NOTFOUND;
25458
25459  UNUSED_PARAMETER(pNotUsed);
25460  if( zName==0 ){
25461    /* If no zName is given, restore all system calls to their default
25462    ** settings and return NULL
25463    */
25464    rc = SQLITE_OK;
25465    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25466      if( aSyscall[i].pDefault ){
25467        aSyscall[i].pCurrent = aSyscall[i].pDefault;
25468      }
25469    }
25470  }else{
25471    /* If zName is specified, operate on only the one system call
25472    ** specified.
25473    */
25474    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25475      if( strcmp(zName, aSyscall[i].zName)==0 ){
25476        if( aSyscall[i].pDefault==0 ){
25477          aSyscall[i].pDefault = aSyscall[i].pCurrent;
25478        }
25479        rc = SQLITE_OK;
25480        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25481        aSyscall[i].pCurrent = pNewFunc;
25482        break;
25483      }
25484    }
25485  }
25486  return rc;
25487}
25488
25489/*
25490** Return the value of a system call.  Return NULL if zName is not a
25491** recognized system call name.  NULL is also returned if the system call
25492** is currently undefined.
25493*/
25494static sqlite3_syscall_ptr unixGetSystemCall(
25495  sqlite3_vfs *pNotUsed,
25496  const char *zName
25497){
25498  unsigned int i;
25499
25500  UNUSED_PARAMETER(pNotUsed);
25501  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25502    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25503  }
25504  return 0;
25505}
25506
25507/*
25508** Return the name of the first system call after zName.  If zName==NULL
25509** then return the name of the first system call.  Return NULL if zName
25510** is the last system call or if zName is not the name of a valid
25511** system call.
25512*/
25513static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25514  int i = -1;
25515
25516  UNUSED_PARAMETER(p);
25517  if( zName ){
25518    for(i=0; i<ArraySize(aSyscall)-1; i++){
25519      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25520    }
25521  }
25522  for(i++; i<ArraySize(aSyscall); i++){
25523    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25524  }
25525  return 0;
25526}
25527
25528/*
25529** Invoke open().  Do so multiple times, until it either succeeds or
25530** files for some reason other than EINTR.
25531**
25532** If the file creation mode "m" is 0 then set it to the default for
25533** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
25534** 0644) as modified by the system umask.  If m is not 0, then
25535** make the file creation mode be exactly m ignoring the umask.
25536**
25537** The m parameter will be non-zero only when creating -wal, -journal,
25538** and -shm files.  We want those files to have *exactly* the same
25539** permissions as their original database, unadulterated by the umask.
25540** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
25541** transaction crashes and leaves behind hot journals, then any
25542** process that is able to write to the database will also be able to
25543** recover the hot journals.
25544*/
25545static int robust_open(const char *z, int f, mode_t m){
25546  int rc;
25547  mode_t m2;
25548  mode_t origM = 0;
25549  if( m==0 ){
25550    m2 = SQLITE_DEFAULT_FILE_PERMISSIONS;
25551  }else{
25552    m2 = m;
25553    origM = osUmask(0);
25554  }
25555  do{ rc = osOpen(z,f,m2); }while( rc<0 && errno==EINTR );
25556  if( m ){
25557    osUmask(origM);
25558  }
25559  return rc;
25560}
25561
25562/*
25563** Helper functions to obtain and relinquish the global mutex. The
25564** global mutex is used to protect the unixInodeInfo and
25565** vxworksFileId objects used by this file, all of which may be
25566** shared by multiple threads.
25567**
25568** Function unixMutexHeld() is used to assert() that the global mutex
25569** is held when required. This function is only used as part of assert()
25570** statements. e.g.
25571**
25572**   unixEnterMutex()
25573**     assert( unixMutexHeld() );
25574**   unixEnterLeave()
25575*/
25576static void unixEnterMutex(void){
25577  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25578}
25579static void unixLeaveMutex(void){
25580  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25581}
25582#ifdef SQLITE_DEBUG
25583static int unixMutexHeld(void) {
25584  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
25585}
25586#endif
25587
25588
25589#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25590/*
25591** Helper function for printing out trace information from debugging
25592** binaries. This returns the string represetation of the supplied
25593** integer lock-type.
25594*/
25595static const char *azFileLock(int eFileLock){
25596  switch( eFileLock ){
25597    case NO_LOCK: return "NONE";
25598    case SHARED_LOCK: return "SHARED";
25599    case RESERVED_LOCK: return "RESERVED";
25600    case PENDING_LOCK: return "PENDING";
25601    case EXCLUSIVE_LOCK: return "EXCLUSIVE";
25602  }
25603  return "ERROR";
25604}
25605#endif
25606
25607#ifdef SQLITE_LOCK_TRACE
25608/*
25609** Print out information about all locking operations.
25610**
25611** This routine is used for troubleshooting locks on multithreaded
25612** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
25613** command-line option on the compiler.  This code is normally
25614** turned off.
25615*/
25616static int lockTrace(int fd, int op, struct flock *p){
25617  char *zOpName, *zType;
25618  int s;
25619  int savedErrno;
25620  if( op==F_GETLK ){
25621    zOpName = "GETLK";
25622  }else if( op==F_SETLK ){
25623    zOpName = "SETLK";
25624  }else{
25625    s = osFcntl(fd, op, p);
25626    sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
25627    return s;
25628  }
25629  if( p->l_type==F_RDLCK ){
25630    zType = "RDLCK";
25631  }else if( p->l_type==F_WRLCK ){
25632    zType = "WRLCK";
25633  }else if( p->l_type==F_UNLCK ){
25634    zType = "UNLCK";
25635  }else{
25636    assert( 0 );
25637  }
25638  assert( p->l_whence==SEEK_SET );
25639  s = osFcntl(fd, op, p);
25640  savedErrno = errno;
25641  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
25642     threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
25643     (int)p->l_pid, s);
25644  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
25645    struct flock l2;
25646    l2 = *p;
25647    osFcntl(fd, F_GETLK, &l2);
25648    if( l2.l_type==F_RDLCK ){
25649      zType = "RDLCK";
25650    }else if( l2.l_type==F_WRLCK ){
25651      zType = "WRLCK";
25652    }else if( l2.l_type==F_UNLCK ){
25653      zType = "UNLCK";
25654    }else{
25655      assert( 0 );
25656    }
25657    sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
25658       zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
25659  }
25660  errno = savedErrno;
25661  return s;
25662}
25663#undef osFcntl
25664#define osFcntl lockTrace
25665#endif /* SQLITE_LOCK_TRACE */
25666
25667/*
25668** Retry ftruncate() calls that fail due to EINTR
25669*/
25670static int robust_ftruncate(int h, sqlite3_int64 sz){
25671  int rc;
25672  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
25673  return rc;
25674}
25675
25676/*
25677** This routine translates a standard POSIX errno code into something
25678** useful to the clients of the sqlite3 functions.  Specifically, it is
25679** intended to translate a variety of "try again" errors into SQLITE_BUSY
25680** and a variety of "please close the file descriptor NOW" errors into
25681** SQLITE_IOERR
25682**
25683** Errors during initialization of locks, or file system support for locks,
25684** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
25685*/
25686static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
25687  switch (posixError) {
25688#if 0
25689  /* At one point this code was not commented out. In theory, this branch
25690  ** should never be hit, as this function should only be called after
25691  ** a locking-related function (i.e. fcntl()) has returned non-zero with
25692  ** the value of errno as the first argument. Since a system call has failed,
25693  ** errno should be non-zero.
25694  **
25695  ** Despite this, if errno really is zero, we still don't want to return
25696  ** SQLITE_OK. The system call failed, and *some* SQLite error should be
25697  ** propagated back to the caller. Commenting this branch out means errno==0
25698  ** will be handled by the "default:" case below.
25699  */
25700  case 0:
25701    return SQLITE_OK;
25702#endif
25703
25704  case EAGAIN:
25705  case ETIMEDOUT:
25706  case EBUSY:
25707  case EINTR:
25708  case ENOLCK:
25709    /* random NFS retry error, unless during file system support
25710     * introspection, in which it actually means what it says */
25711    return SQLITE_BUSY;
25712
25713  case EACCES:
25714    /* EACCES is like EAGAIN during locking operations, but not any other time*/
25715    if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
25716	(sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
25717	(sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
25718	(sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
25719      return SQLITE_BUSY;
25720    }
25721    /* else fall through */
25722  case EPERM:
25723    return SQLITE_PERM;
25724
25725  /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
25726  ** this module never makes such a call. And the code in SQLite itself
25727  ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
25728  ** this case is also commented out. If the system does set errno to EDEADLK,
25729  ** the default SQLITE_IOERR_XXX code will be returned. */
25730#if 0
25731  case EDEADLK:
25732    return SQLITE_IOERR_BLOCKED;
25733#endif
25734
25735#if EOPNOTSUPP!=ENOTSUP
25736  case EOPNOTSUPP:
25737    /* something went terribly awry, unless during file system support
25738     * introspection, in which it actually means what it says */
25739#endif
25740#ifdef ENOTSUP
25741  case ENOTSUP:
25742    /* invalid fd, unless during file system support introspection, in which
25743     * it actually means what it says */
25744#endif
25745  case EIO:
25746  case EBADF:
25747  case EINVAL:
25748  case ENOTCONN:
25749  case ENODEV:
25750  case ENXIO:
25751  case ENOENT:
25752#ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
25753  case ESTALE:
25754#endif
25755  case ENOSYS:
25756    /* these should force the client to close the file and reconnect */
25757
25758  default:
25759    return sqliteIOErr;
25760  }
25761}
25762
25763
25764
25765/******************************************************************************
25766****************** Begin Unique File ID Utility Used By VxWorks ***************
25767**
25768** On most versions of unix, we can get a unique ID for a file by concatenating
25769** the device number and the inode number.  But this does not work on VxWorks.
25770** On VxWorks, a unique file id must be based on the canonical filename.
25771**
25772** A pointer to an instance of the following structure can be used as a
25773** unique file ID in VxWorks.  Each instance of this structure contains
25774** a copy of the canonical filename.  There is also a reference count.
25775** The structure is reclaimed when the number of pointers to it drops to
25776** zero.
25777**
25778** There are never very many files open at one time and lookups are not
25779** a performance-critical path, so it is sufficient to put these
25780** structures on a linked list.
25781*/
25782struct vxworksFileId {
25783  struct vxworksFileId *pNext;  /* Next in a list of them all */
25784  int nRef;                     /* Number of references to this one */
25785  int nName;                    /* Length of the zCanonicalName[] string */
25786  char *zCanonicalName;         /* Canonical filename */
25787};
25788
25789#if OS_VXWORKS
25790/*
25791** All unique filenames are held on a linked list headed by this
25792** variable:
25793*/
25794static struct vxworksFileId *vxworksFileList = 0;
25795
25796/*
25797** Simplify a filename into its canonical form
25798** by making the following changes:
25799**
25800**  * removing any trailing and duplicate /
25801**  * convert /./ into just /
25802**  * convert /A/../ where A is any simple name into just /
25803**
25804** Changes are made in-place.  Return the new name length.
25805**
25806** The original filename is in z[0..n-1].  Return the number of
25807** characters in the simplified name.
25808*/
25809static int vxworksSimplifyName(char *z, int n){
25810  int i, j;
25811  while( n>1 && z[n-1]=='/' ){ n--; }
25812  for(i=j=0; i<n; i++){
25813    if( z[i]=='/' ){
25814      if( z[i+1]=='/' ) continue;
25815      if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
25816        i += 1;
25817        continue;
25818      }
25819      if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
25820        while( j>0 && z[j-1]!='/' ){ j--; }
25821        if( j>0 ){ j--; }
25822        i += 2;
25823        continue;
25824      }
25825    }
25826    z[j++] = z[i];
25827  }
25828  z[j] = 0;
25829  return j;
25830}
25831
25832/*
25833** Find a unique file ID for the given absolute pathname.  Return
25834** a pointer to the vxworksFileId object.  This pointer is the unique
25835** file ID.
25836**
25837** The nRef field of the vxworksFileId object is incremented before
25838** the object is returned.  A new vxworksFileId object is created
25839** and added to the global list if necessary.
25840**
25841** If a memory allocation error occurs, return NULL.
25842*/
25843static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
25844  struct vxworksFileId *pNew;         /* search key and new file ID */
25845  struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
25846  int n;                              /* Length of zAbsoluteName string */
25847
25848  assert( zAbsoluteName[0]=='/' );
25849  n = (int)strlen(zAbsoluteName);
25850  pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
25851  if( pNew==0 ) return 0;
25852  pNew->zCanonicalName = (char*)&pNew[1];
25853  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
25854  n = vxworksSimplifyName(pNew->zCanonicalName, n);
25855
25856  /* Search for an existing entry that matching the canonical name.
25857  ** If found, increment the reference count and return a pointer to
25858  ** the existing file ID.
25859  */
25860  unixEnterMutex();
25861  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
25862    if( pCandidate->nName==n
25863     && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
25864    ){
25865       sqlite3_free(pNew);
25866       pCandidate->nRef++;
25867       unixLeaveMutex();
25868       return pCandidate;
25869    }
25870  }
25871
25872  /* No match was found.  We will make a new file ID */
25873  pNew->nRef = 1;
25874  pNew->nName = n;
25875  pNew->pNext = vxworksFileList;
25876  vxworksFileList = pNew;
25877  unixLeaveMutex();
25878  return pNew;
25879}
25880
25881/*
25882** Decrement the reference count on a vxworksFileId object.  Free
25883** the object when the reference count reaches zero.
25884*/
25885static void vxworksReleaseFileId(struct vxworksFileId *pId){
25886  unixEnterMutex();
25887  assert( pId->nRef>0 );
25888  pId->nRef--;
25889  if( pId->nRef==0 ){
25890    struct vxworksFileId **pp;
25891    for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
25892    assert( *pp==pId );
25893    *pp = pId->pNext;
25894    sqlite3_free(pId);
25895  }
25896  unixLeaveMutex();
25897}
25898#endif /* OS_VXWORKS */
25899/*************** End of Unique File ID Utility Used By VxWorks ****************
25900******************************************************************************/
25901
25902
25903/******************************************************************************
25904*************************** Posix Advisory Locking ****************************
25905**
25906** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
25907** section 6.5.2.2 lines 483 through 490 specify that when a process
25908** sets or clears a lock, that operation overrides any prior locks set
25909** by the same process.  It does not explicitly say so, but this implies
25910** that it overrides locks set by the same process using a different
25911** file descriptor.  Consider this test case:
25912**
25913**       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
25914**       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
25915**
25916** Suppose ./file1 and ./file2 are really the same file (because
25917** one is a hard or symbolic link to the other) then if you set
25918** an exclusive lock on fd1, then try to get an exclusive lock
25919** on fd2, it works.  I would have expected the second lock to
25920** fail since there was already a lock on the file due to fd1.
25921** But not so.  Since both locks came from the same process, the
25922** second overrides the first, even though they were on different
25923** file descriptors opened on different file names.
25924**
25925** This means that we cannot use POSIX locks to synchronize file access
25926** among competing threads of the same process.  POSIX locks will work fine
25927** to synchronize access for threads in separate processes, but not
25928** threads within the same process.
25929**
25930** To work around the problem, SQLite has to manage file locks internally
25931** on its own.  Whenever a new database is opened, we have to find the
25932** specific inode of the database file (the inode is determined by the
25933** st_dev and st_ino fields of the stat structure that fstat() fills in)
25934** and check for locks already existing on that inode.  When locks are
25935** created or removed, we have to look at our own internal record of the
25936** locks to see if another thread has previously set a lock on that same
25937** inode.
25938**
25939** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
25940** For VxWorks, we have to use the alternative unique ID system based on
25941** canonical filename and implemented in the previous division.)
25942**
25943** The sqlite3_file structure for POSIX is no longer just an integer file
25944** descriptor.  It is now a structure that holds the integer file
25945** descriptor and a pointer to a structure that describes the internal
25946** locks on the corresponding inode.  There is one locking structure
25947** per inode, so if the same inode is opened twice, both unixFile structures
25948** point to the same locking structure.  The locking structure keeps
25949** a reference count (so we will know when to delete it) and a "cnt"
25950** field that tells us its internal lock status.  cnt==0 means the
25951** file is unlocked.  cnt==-1 means the file has an exclusive lock.
25952** cnt>0 means there are cnt shared locks on the file.
25953**
25954** Any attempt to lock or unlock a file first checks the locking
25955** structure.  The fcntl() system call is only invoked to set a
25956** POSIX lock if the internal lock structure transitions between
25957** a locked and an unlocked state.
25958**
25959** But wait:  there are yet more problems with POSIX advisory locks.
25960**
25961** If you close a file descriptor that points to a file that has locks,
25962** all locks on that file that are owned by the current process are
25963** released.  To work around this problem, each unixInodeInfo object
25964** maintains a count of the number of pending locks on tha inode.
25965** When an attempt is made to close an unixFile, if there are
25966** other unixFile open on the same inode that are holding locks, the call
25967** to close() the file descriptor is deferred until all of the locks clear.
25968** The unixInodeInfo structure keeps a list of file descriptors that need to
25969** be closed and that list is walked (and cleared) when the last lock
25970** clears.
25971**
25972** Yet another problem:  LinuxThreads do not play well with posix locks.
25973**
25974** Many older versions of linux use the LinuxThreads library which is
25975** not posix compliant.  Under LinuxThreads, a lock created by thread
25976** A cannot be modified or overridden by a different thread B.
25977** Only thread A can modify the lock.  Locking behavior is correct
25978** if the appliation uses the newer Native Posix Thread Library (NPTL)
25979** on linux - with NPTL a lock created by thread A can override locks
25980** in thread B.  But there is no way to know at compile-time which
25981** threading library is being used.  So there is no way to know at
25982** compile-time whether or not thread A can override locks on thread B.
25983** One has to do a run-time check to discover the behavior of the
25984** current process.
25985**
25986** SQLite used to support LinuxThreads.  But support for LinuxThreads
25987** was dropped beginning with version 3.7.0.  SQLite will still work with
25988** LinuxThreads provided that (1) there is no more than one connection
25989** per database file in the same process and (2) database connections
25990** do not move across threads.
25991*/
25992
25993/*
25994** An instance of the following structure serves as the key used
25995** to locate a particular unixInodeInfo object.
25996*/
25997struct unixFileId {
25998  dev_t dev;                  /* Device number */
25999#if OS_VXWORKS
26000  struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
26001#else
26002  ino_t ino;                  /* Inode number */
26003#endif
26004};
26005
26006/*
26007** An instance of the following structure is allocated for each open
26008** inode.  Or, on LinuxThreads, there is one of these structures for
26009** each inode opened by each thread.
26010**
26011** A single inode can have multiple file descriptors, so each unixFile
26012** structure contains a pointer to an instance of this object and this
26013** object keeps a count of the number of unixFile pointing to it.
26014*/
26015struct unixInodeInfo {
26016  struct unixFileId fileId;       /* The lookup key */
26017  int nShared;                    /* Number of SHARED locks held */
26018  unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
26019  unsigned char bProcessLock;     /* An exclusive process lock is held */
26020  int nRef;                       /* Number of pointers to this structure */
26021  unixShmNode *pShmNode;          /* Shared memory associated with this inode */
26022  int nLock;                      /* Number of outstanding file locks */
26023  UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
26024  unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
26025  unixInodeInfo *pPrev;           /*    .... doubly linked */
26026#if SQLITE_ENABLE_LOCKING_STYLE
26027  unsigned long long sharedByte;  /* for AFP simulated shared lock */
26028#endif
26029#if OS_VXWORKS
26030  sem_t *pSem;                    /* Named POSIX semaphore */
26031  char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
26032#endif
26033};
26034
26035/*
26036** A lists of all unixInodeInfo objects.
26037*/
26038static unixInodeInfo *inodeList = 0;
26039
26040/*
26041**
26042** This function - unixLogError_x(), is only ever called via the macro
26043** unixLogError().
26044**
26045** It is invoked after an error occurs in an OS function and errno has been
26046** set. It logs a message using sqlite3_log() containing the current value of
26047** errno and, if possible, the human-readable equivalent from strerror() or
26048** strerror_r().
26049**
26050** The first argument passed to the macro should be the error code that
26051** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
26052** The two subsequent arguments should be the name of the OS function that
26053** failed (e.g. "unlink", "open") and the the associated file-system path,
26054** if any.
26055*/
26056#define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
26057static int unixLogErrorAtLine(
26058  int errcode,                    /* SQLite error code */
26059  const char *zFunc,              /* Name of OS function that failed */
26060  const char *zPath,              /* File path associated with error */
26061  int iLine                       /* Source line number where error occurred */
26062){
26063  char *zErr;                     /* Message from strerror() or equivalent */
26064  int iErrno = errno;             /* Saved syscall error number */
26065
26066  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
26067  ** the strerror() function to obtain the human-readable error message
26068  ** equivalent to errno. Otherwise, use strerror_r().
26069  */
26070#if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
26071  char aErr[80];
26072  memset(aErr, 0, sizeof(aErr));
26073  zErr = aErr;
26074
26075  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
26076  ** assume that the system provides the the GNU version of strerror_r() that
26077  ** returns a pointer to a buffer containing the error message. That pointer
26078  ** may point to aErr[], or it may point to some static storage somewhere.
26079  ** Otherwise, assume that the system provides the POSIX version of
26080  ** strerror_r(), which always writes an error message into aErr[].
26081  **
26082  ** If the code incorrectly assumes that it is the POSIX version that is
26083  ** available, the error message will often be an empty string. Not a
26084  ** huge problem. Incorrectly concluding that the GNU version is available
26085  ** could lead to a segfault though.
26086  */
26087#if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
26088  zErr =
26089# endif
26090  strerror_r(iErrno, aErr, sizeof(aErr)-1);
26091
26092#elif SQLITE_THREADSAFE
26093  /* This is a threadsafe build, but strerror_r() is not available. */
26094  zErr = "";
26095#else
26096  /* Non-threadsafe build, use strerror(). */
26097  zErr = strerror(iErrno);
26098#endif
26099
26100  assert( errcode!=SQLITE_OK );
26101  if( zPath==0 ) zPath = "";
26102  sqlite3_log(errcode,
26103      "os_unix.c:%d: (%d) %s(%s) - %s",
26104      iLine, iErrno, zFunc, zPath, zErr
26105  );
26106
26107  return errcode;
26108}
26109
26110/*
26111** Close a file descriptor.
26112**
26113** We assume that close() almost always works, since it is only in a
26114** very sick application or on a very sick platform that it might fail.
26115** If it does fail, simply leak the file descriptor, but do log the
26116** error.
26117**
26118** Note that it is not safe to retry close() after EINTR since the
26119** file descriptor might have already been reused by another thread.
26120** So we don't even try to recover from an EINTR.  Just log the error
26121** and move on.
26122*/
26123static void robust_close(unixFile *pFile, int h, int lineno){
26124  if( osClose(h) ){
26125    unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
26126                       pFile ? pFile->zPath : 0, lineno);
26127  }
26128}
26129
26130/*
26131** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
26132*/
26133static void closePendingFds(unixFile *pFile){
26134  unixInodeInfo *pInode = pFile->pInode;
26135  UnixUnusedFd *p;
26136  UnixUnusedFd *pNext;
26137  for(p=pInode->pUnused; p; p=pNext){
26138    pNext = p->pNext;
26139    robust_close(pFile, p->fd, __LINE__);
26140    sqlite3_free(p);
26141  }
26142  pInode->pUnused = 0;
26143}
26144
26145/*
26146** Release a unixInodeInfo structure previously allocated by findInodeInfo().
26147**
26148** The mutex entered using the unixEnterMutex() function must be held
26149** when this function is called.
26150*/
26151static void releaseInodeInfo(unixFile *pFile){
26152  unixInodeInfo *pInode = pFile->pInode;
26153  assert( unixMutexHeld() );
26154  if( ALWAYS(pInode) ){
26155    pInode->nRef--;
26156    if( pInode->nRef==0 ){
26157      assert( pInode->pShmNode==0 );
26158      closePendingFds(pFile);
26159      if( pInode->pPrev ){
26160        assert( pInode->pPrev->pNext==pInode );
26161        pInode->pPrev->pNext = pInode->pNext;
26162      }else{
26163        assert( inodeList==pInode );
26164        inodeList = pInode->pNext;
26165      }
26166      if( pInode->pNext ){
26167        assert( pInode->pNext->pPrev==pInode );
26168        pInode->pNext->pPrev = pInode->pPrev;
26169      }
26170      sqlite3_free(pInode);
26171    }
26172  }
26173}
26174
26175/*
26176** Given a file descriptor, locate the unixInodeInfo object that
26177** describes that file descriptor.  Create a new one if necessary.  The
26178** return value might be uninitialized if an error occurs.
26179**
26180** The mutex entered using the unixEnterMutex() function must be held
26181** when this function is called.
26182**
26183** Return an appropriate error code.
26184*/
26185static int findInodeInfo(
26186  unixFile *pFile,               /* Unix file with file desc used in the key */
26187  unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
26188){
26189  int rc;                        /* System call return code */
26190  int fd;                        /* The file descriptor for pFile */
26191  struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
26192  struct stat statbuf;           /* Low-level file information */
26193  unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
26194
26195  assert( unixMutexHeld() );
26196
26197  /* Get low-level information about the file that we can used to
26198  ** create a unique name for the file.
26199  */
26200  fd = pFile->h;
26201  rc = osFstat(fd, &statbuf);
26202  if( rc!=0 ){
26203    pFile->lastErrno = errno;
26204#ifdef EOVERFLOW
26205    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
26206#endif
26207    return SQLITE_IOERR;
26208  }
26209
26210#ifdef __APPLE__
26211  /* On OS X on an msdos filesystem, the inode number is reported
26212  ** incorrectly for zero-size files.  See ticket #3260.  To work
26213  ** around this problem (we consider it a bug in OS X, not SQLite)
26214  ** we always increase the file size to 1 by writing a single byte
26215  ** prior to accessing the inode number.  The one byte written is
26216  ** an ASCII 'S' character which also happens to be the first byte
26217  ** in the header of every SQLite database.  In this way, if there
26218  ** is a race condition such that another thread has already populated
26219  ** the first page of the database, no damage is done.
26220  */
26221  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
26222    do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
26223    if( rc!=1 ){
26224      pFile->lastErrno = errno;
26225      return SQLITE_IOERR;
26226    }
26227    rc = osFstat(fd, &statbuf);
26228    if( rc!=0 ){
26229      pFile->lastErrno = errno;
26230      return SQLITE_IOERR;
26231    }
26232  }
26233#endif
26234
26235  memset(&fileId, 0, sizeof(fileId));
26236  fileId.dev = statbuf.st_dev;
26237#if OS_VXWORKS
26238  fileId.pId = pFile->pId;
26239#else
26240  fileId.ino = statbuf.st_ino;
26241#endif
26242  pInode = inodeList;
26243  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
26244    pInode = pInode->pNext;
26245  }
26246  if( pInode==0 ){
26247    pInode = sqlite3_malloc( sizeof(*pInode) );
26248    if( pInode==0 ){
26249      return SQLITE_NOMEM;
26250    }
26251    memset(pInode, 0, sizeof(*pInode));
26252    memcpy(&pInode->fileId, &fileId, sizeof(fileId));
26253    pInode->nRef = 1;
26254    pInode->pNext = inodeList;
26255    pInode->pPrev = 0;
26256    if( inodeList ) inodeList->pPrev = pInode;
26257    inodeList = pInode;
26258  }else{
26259    pInode->nRef++;
26260  }
26261  *ppInode = pInode;
26262  return SQLITE_OK;
26263}
26264
26265
26266/*
26267** This routine checks if there is a RESERVED lock held on the specified
26268** file by this or any other process. If such a lock is held, set *pResOut
26269** to a non-zero value otherwise *pResOut is set to zero.  The return value
26270** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26271*/
26272static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
26273  int rc = SQLITE_OK;
26274  int reserved = 0;
26275  unixFile *pFile = (unixFile*)id;
26276
26277  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26278
26279  assert( pFile );
26280  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26281
26282  /* Check if a thread in this process holds such a lock */
26283  if( pFile->pInode->eFileLock>SHARED_LOCK ){
26284    reserved = 1;
26285  }
26286
26287  /* Otherwise see if some other process holds it.
26288  */
26289#ifndef __DJGPP__
26290  if( !reserved && !pFile->pInode->bProcessLock ){
26291    struct flock lock;
26292    lock.l_whence = SEEK_SET;
26293    lock.l_start = RESERVED_BYTE;
26294    lock.l_len = 1;
26295    lock.l_type = F_WRLCK;
26296    if( osFcntl(pFile->h, F_GETLK, &lock) ){
26297      rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
26298      pFile->lastErrno = errno;
26299    } else if( lock.l_type!=F_UNLCK ){
26300      reserved = 1;
26301    }
26302  }
26303#endif
26304
26305  unixLeaveMutex();
26306  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
26307
26308  *pResOut = reserved;
26309  return rc;
26310}
26311
26312/*
26313** Attempt to set a system-lock on the file pFile.  The lock is
26314** described by pLock.
26315**
26316** If the pFile was opened read/write from unix-excl, then the only lock
26317** ever obtained is an exclusive lock, and it is obtained exactly once
26318** the first time any lock is attempted.  All subsequent system locking
26319** operations become no-ops.  Locking operations still happen internally,
26320** in order to coordinate access between separate database connections
26321** within this process, but all of that is handled in memory and the
26322** operating system does not participate.
26323**
26324** This function is a pass-through to fcntl(F_SETLK) if pFile is using
26325** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
26326** and is read-only.
26327**
26328** Zero is returned if the call completes successfully, or -1 if a call
26329** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
26330*/
26331static int unixFileLock(unixFile *pFile, struct flock *pLock){
26332  int rc;
26333  unixInodeInfo *pInode = pFile->pInode;
26334  assert( unixMutexHeld() );
26335  assert( pInode!=0 );
26336  if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
26337   && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
26338  ){
26339    if( pInode->bProcessLock==0 ){
26340      struct flock lock;
26341      assert( pInode->nLock==0 );
26342      lock.l_whence = SEEK_SET;
26343      lock.l_start = SHARED_FIRST;
26344      lock.l_len = SHARED_SIZE;
26345      lock.l_type = F_WRLCK;
26346      rc = osFcntl(pFile->h, F_SETLK, &lock);
26347      if( rc<0 ) return rc;
26348      pInode->bProcessLock = 1;
26349      pInode->nLock++;
26350    }else{
26351      rc = 0;
26352    }
26353  }else{
26354    rc = osFcntl(pFile->h, F_SETLK, pLock);
26355  }
26356  return rc;
26357}
26358
26359/*
26360** Lock the file with the lock specified by parameter eFileLock - one
26361** of the following:
26362**
26363**     (1) SHARED_LOCK
26364**     (2) RESERVED_LOCK
26365**     (3) PENDING_LOCK
26366**     (4) EXCLUSIVE_LOCK
26367**
26368** Sometimes when requesting one lock state, additional lock states
26369** are inserted in between.  The locking might fail on one of the later
26370** transitions leaving the lock state different from what it started but
26371** still short of its goal.  The following chart shows the allowed
26372** transitions and the inserted intermediate states:
26373**
26374**    UNLOCKED -> SHARED
26375**    SHARED -> RESERVED
26376**    SHARED -> (PENDING) -> EXCLUSIVE
26377**    RESERVED -> (PENDING) -> EXCLUSIVE
26378**    PENDING -> EXCLUSIVE
26379**
26380** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26381** routine to lower a locking level.
26382*/
26383static int unixLock(sqlite3_file *id, int eFileLock){
26384  /* The following describes the implementation of the various locks and
26385  ** lock transitions in terms of the POSIX advisory shared and exclusive
26386  ** lock primitives (called read-locks and write-locks below, to avoid
26387  ** confusion with SQLite lock names). The algorithms are complicated
26388  ** slightly in order to be compatible with windows systems simultaneously
26389  ** accessing the same database file, in case that is ever required.
26390  **
26391  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
26392  ** byte', each single bytes at well known offsets, and the 'shared byte
26393  ** range', a range of 510 bytes at a well known offset.
26394  **
26395  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
26396  ** byte'.  If this is successful, a random byte from the 'shared byte
26397  ** range' is read-locked and the lock on the 'pending byte' released.
26398  **
26399  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
26400  ** A RESERVED lock is implemented by grabbing a write-lock on the
26401  ** 'reserved byte'.
26402  **
26403  ** A process may only obtain a PENDING lock after it has obtained a
26404  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
26405  ** on the 'pending byte'. This ensures that no new SHARED locks can be
26406  ** obtained, but existing SHARED locks are allowed to persist. A process
26407  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
26408  ** This property is used by the algorithm for rolling back a journal file
26409  ** after a crash.
26410  **
26411  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
26412  ** implemented by obtaining a write-lock on the entire 'shared byte
26413  ** range'. Since all other locks require a read-lock on one of the bytes
26414  ** within this range, this ensures that no other locks are held on the
26415  ** database.
26416  **
26417  ** The reason a single byte cannot be used instead of the 'shared byte
26418  ** range' is that some versions of windows do not support read-locks. By
26419  ** locking a random byte from a range, concurrent SHARED locks may exist
26420  ** even if the locking primitive used is always a write-lock.
26421  */
26422  int rc = SQLITE_OK;
26423  unixFile *pFile = (unixFile*)id;
26424  unixInodeInfo *pInode;
26425  struct flock lock;
26426  int tErrno = 0;
26427
26428  assert( pFile );
26429  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
26430      azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26431      azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
26432
26433  /* If there is already a lock of this type or more restrictive on the
26434  ** unixFile, do nothing. Don't use the end_lock: exit path, as
26435  ** unixEnterMutex() hasn't been called yet.
26436  */
26437  if( pFile->eFileLock>=eFileLock ){
26438    OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
26439            azFileLock(eFileLock)));
26440    return SQLITE_OK;
26441  }
26442
26443  /* Make sure the locking sequence is correct.
26444  **  (1) We never move from unlocked to anything higher than shared lock.
26445  **  (2) SQLite never explicitly requests a pendig lock.
26446  **  (3) A shared lock is always held when a reserve lock is requested.
26447  */
26448  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26449  assert( eFileLock!=PENDING_LOCK );
26450  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26451
26452  /* This mutex is needed because pFile->pInode is shared across threads
26453  */
26454  unixEnterMutex();
26455  pInode = pFile->pInode;
26456
26457  /* If some thread using this PID has a lock via a different unixFile*
26458  ** handle that precludes the requested lock, return BUSY.
26459  */
26460  if( (pFile->eFileLock!=pInode->eFileLock &&
26461          (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26462  ){
26463    rc = SQLITE_BUSY;
26464    goto end_lock;
26465  }
26466
26467  /* If a SHARED lock is requested, and some thread using this PID already
26468  ** has a SHARED or RESERVED lock, then increment reference counts and
26469  ** return SQLITE_OK.
26470  */
26471  if( eFileLock==SHARED_LOCK &&
26472      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26473    assert( eFileLock==SHARED_LOCK );
26474    assert( pFile->eFileLock==0 );
26475    assert( pInode->nShared>0 );
26476    pFile->eFileLock = SHARED_LOCK;
26477    pInode->nShared++;
26478    pInode->nLock++;
26479    goto end_lock;
26480  }
26481
26482
26483  /* A PENDING lock is needed before acquiring a SHARED lock and before
26484  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26485  ** be released.
26486  */
26487  lock.l_len = 1L;
26488  lock.l_whence = SEEK_SET;
26489  if( eFileLock==SHARED_LOCK
26490      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26491  ){
26492    lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26493    lock.l_start = PENDING_BYTE;
26494    if( unixFileLock(pFile, &lock) ){
26495      tErrno = errno;
26496      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26497      if( rc!=SQLITE_BUSY ){
26498        pFile->lastErrno = tErrno;
26499      }
26500      goto end_lock;
26501    }
26502  }
26503
26504
26505  /* If control gets to this point, then actually go ahead and make
26506  ** operating system calls for the specified lock.
26507  */
26508  if( eFileLock==SHARED_LOCK ){
26509    assert( pInode->nShared==0 );
26510    assert( pInode->eFileLock==0 );
26511    assert( rc==SQLITE_OK );
26512
26513    /* Now get the read-lock */
26514    lock.l_start = SHARED_FIRST;
26515    lock.l_len = SHARED_SIZE;
26516    if( unixFileLock(pFile, &lock) ){
26517      tErrno = errno;
26518      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26519    }
26520
26521    /* Drop the temporary PENDING lock */
26522    lock.l_start = PENDING_BYTE;
26523    lock.l_len = 1L;
26524    lock.l_type = F_UNLCK;
26525    if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
26526      /* This could happen with a network mount */
26527      tErrno = errno;
26528      rc = SQLITE_IOERR_UNLOCK;
26529    }
26530
26531    if( rc ){
26532      if( rc!=SQLITE_BUSY ){
26533        pFile->lastErrno = tErrno;
26534      }
26535      goto end_lock;
26536    }else{
26537      pFile->eFileLock = SHARED_LOCK;
26538      pInode->nLock++;
26539      pInode->nShared = 1;
26540    }
26541  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
26542    /* We are trying for an exclusive lock but another thread in this
26543    ** same process is still holding a shared lock. */
26544    rc = SQLITE_BUSY;
26545  }else{
26546    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
26547    ** assumed that there is a SHARED or greater lock on the file
26548    ** already.
26549    */
26550    assert( 0!=pFile->eFileLock );
26551    lock.l_type = F_WRLCK;
26552
26553    assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
26554    if( eFileLock==RESERVED_LOCK ){
26555      lock.l_start = RESERVED_BYTE;
26556      lock.l_len = 1L;
26557    }else{
26558      lock.l_start = SHARED_FIRST;
26559      lock.l_len = SHARED_SIZE;
26560    }
26561
26562    if( unixFileLock(pFile, &lock) ){
26563      tErrno = errno;
26564      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26565      if( rc!=SQLITE_BUSY ){
26566        pFile->lastErrno = tErrno;
26567      }
26568    }
26569  }
26570
26571
26572#ifndef NDEBUG
26573  /* Set up the transaction-counter change checking flags when
26574  ** transitioning from a SHARED to a RESERVED lock.  The change
26575  ** from SHARED to RESERVED marks the beginning of a normal
26576  ** write operation (not a hot journal rollback).
26577  */
26578  if( rc==SQLITE_OK
26579   && pFile->eFileLock<=SHARED_LOCK
26580   && eFileLock==RESERVED_LOCK
26581  ){
26582    pFile->transCntrChng = 0;
26583    pFile->dbUpdate = 0;
26584    pFile->inNormalWrite = 1;
26585  }
26586#endif
26587
26588
26589  if( rc==SQLITE_OK ){
26590    pFile->eFileLock = eFileLock;
26591    pInode->eFileLock = eFileLock;
26592  }else if( eFileLock==EXCLUSIVE_LOCK ){
26593    pFile->eFileLock = PENDING_LOCK;
26594    pInode->eFileLock = PENDING_LOCK;
26595  }
26596
26597end_lock:
26598  unixLeaveMutex();
26599  OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
26600      rc==SQLITE_OK ? "ok" : "failed"));
26601  return rc;
26602}
26603
26604/*
26605** Add the file descriptor used by file handle pFile to the corresponding
26606** pUnused list.
26607*/
26608static void setPendingFd(unixFile *pFile){
26609  unixInodeInfo *pInode = pFile->pInode;
26610  UnixUnusedFd *p = pFile->pUnused;
26611  p->pNext = pInode->pUnused;
26612  pInode->pUnused = p;
26613  pFile->h = -1;
26614  pFile->pUnused = 0;
26615}
26616
26617/*
26618** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26619** must be either NO_LOCK or SHARED_LOCK.
26620**
26621** If the locking level of the file descriptor is already at or below
26622** the requested locking level, this routine is a no-op.
26623**
26624** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
26625** the byte range is divided into 2 parts and the first part is unlocked then
26626** set to a read lock, then the other part is simply unlocked.  This works
26627** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
26628** remove the write lock on a region when a read lock is set.
26629*/
26630static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
26631  unixFile *pFile = (unixFile*)id;
26632  unixInodeInfo *pInode;
26633  struct flock lock;
26634  int rc = SQLITE_OK;
26635
26636  assert( pFile );
26637  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
26638      pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26639      getpid()));
26640
26641  assert( eFileLock<=SHARED_LOCK );
26642  if( pFile->eFileLock<=eFileLock ){
26643    return SQLITE_OK;
26644  }
26645  unixEnterMutex();
26646  pInode = pFile->pInode;
26647  assert( pInode->nShared!=0 );
26648  if( pFile->eFileLock>SHARED_LOCK ){
26649    assert( pInode->eFileLock==pFile->eFileLock );
26650
26651#ifndef NDEBUG
26652    /* When reducing a lock such that other processes can start
26653    ** reading the database file again, make sure that the
26654    ** transaction counter was updated if any part of the database
26655    ** file changed.  If the transaction counter is not updated,
26656    ** other connections to the same file might not realize that
26657    ** the file has changed and hence might not know to flush their
26658    ** cache.  The use of a stale cache can lead to database corruption.
26659    */
26660    pFile->inNormalWrite = 0;
26661#endif
26662
26663    /* downgrading to a shared lock on NFS involves clearing the write lock
26664    ** before establishing the readlock - to avoid a race condition we downgrade
26665    ** the lock in 2 blocks, so that part of the range will be covered by a
26666    ** write lock until the rest is covered by a read lock:
26667    **  1:   [WWWWW]
26668    **  2:   [....W]
26669    **  3:   [RRRRW]
26670    **  4:   [RRRR.]
26671    */
26672    if( eFileLock==SHARED_LOCK ){
26673
26674#if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
26675      (void)handleNFSUnlock;
26676      assert( handleNFSUnlock==0 );
26677#endif
26678#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26679      if( handleNFSUnlock ){
26680        int tErrno;               /* Error code from system call errors */
26681        off_t divSize = SHARED_SIZE - 1;
26682
26683        lock.l_type = F_UNLCK;
26684        lock.l_whence = SEEK_SET;
26685        lock.l_start = SHARED_FIRST;
26686        lock.l_len = divSize;
26687        if( unixFileLock(pFile, &lock)==(-1) ){
26688          tErrno = errno;
26689          rc = SQLITE_IOERR_UNLOCK;
26690          if( IS_LOCK_ERROR(rc) ){
26691            pFile->lastErrno = tErrno;
26692          }
26693          goto end_unlock;
26694        }
26695        lock.l_type = F_RDLCK;
26696        lock.l_whence = SEEK_SET;
26697        lock.l_start = SHARED_FIRST;
26698        lock.l_len = divSize;
26699        if( unixFileLock(pFile, &lock)==(-1) ){
26700          tErrno = errno;
26701          rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
26702          if( IS_LOCK_ERROR(rc) ){
26703            pFile->lastErrno = tErrno;
26704          }
26705          goto end_unlock;
26706        }
26707        lock.l_type = F_UNLCK;
26708        lock.l_whence = SEEK_SET;
26709        lock.l_start = SHARED_FIRST+divSize;
26710        lock.l_len = SHARED_SIZE-divSize;
26711        if( unixFileLock(pFile, &lock)==(-1) ){
26712          tErrno = errno;
26713          rc = SQLITE_IOERR_UNLOCK;
26714          if( IS_LOCK_ERROR(rc) ){
26715            pFile->lastErrno = tErrno;
26716          }
26717          goto end_unlock;
26718        }
26719      }else
26720#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26721      {
26722        lock.l_type = F_RDLCK;
26723        lock.l_whence = SEEK_SET;
26724        lock.l_start = SHARED_FIRST;
26725        lock.l_len = SHARED_SIZE;
26726        if( unixFileLock(pFile, &lock) ){
26727          /* In theory, the call to unixFileLock() cannot fail because another
26728          ** process is holding an incompatible lock. If it does, this
26729          ** indicates that the other process is not following the locking
26730          ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
26731          ** SQLITE_BUSY would confuse the upper layer (in practice it causes
26732          ** an assert to fail). */
26733          rc = SQLITE_IOERR_RDLOCK;
26734          pFile->lastErrno = errno;
26735          goto end_unlock;
26736        }
26737      }
26738    }
26739    lock.l_type = F_UNLCK;
26740    lock.l_whence = SEEK_SET;
26741    lock.l_start = PENDING_BYTE;
26742    lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
26743    if( unixFileLock(pFile, &lock)==0 ){
26744      pInode->eFileLock = SHARED_LOCK;
26745    }else{
26746      rc = SQLITE_IOERR_UNLOCK;
26747      pFile->lastErrno = errno;
26748      goto end_unlock;
26749    }
26750  }
26751  if( eFileLock==NO_LOCK ){
26752    /* Decrement the shared lock counter.  Release the lock using an
26753    ** OS call only when all threads in this same process have released
26754    ** the lock.
26755    */
26756    pInode->nShared--;
26757    if( pInode->nShared==0 ){
26758      lock.l_type = F_UNLCK;
26759      lock.l_whence = SEEK_SET;
26760      lock.l_start = lock.l_len = 0L;
26761      if( unixFileLock(pFile, &lock)==0 ){
26762        pInode->eFileLock = NO_LOCK;
26763      }else{
26764        rc = SQLITE_IOERR_UNLOCK;
26765	pFile->lastErrno = errno;
26766        pInode->eFileLock = NO_LOCK;
26767        pFile->eFileLock = NO_LOCK;
26768      }
26769    }
26770
26771    /* Decrement the count of locks against this same file.  When the
26772    ** count reaches zero, close any other file descriptors whose close
26773    ** was deferred because of outstanding locks.
26774    */
26775    pInode->nLock--;
26776    assert( pInode->nLock>=0 );
26777    if( pInode->nLock==0 ){
26778      closePendingFds(pFile);
26779    }
26780  }
26781
26782end_unlock:
26783  unixLeaveMutex();
26784  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26785  return rc;
26786}
26787
26788/*
26789** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26790** must be either NO_LOCK or SHARED_LOCK.
26791**
26792** If the locking level of the file descriptor is already at or below
26793** the requested locking level, this routine is a no-op.
26794*/
26795static int unixUnlock(sqlite3_file *id, int eFileLock){
26796  return posixUnlock(id, eFileLock, 0);
26797}
26798
26799/*
26800** This function performs the parts of the "close file" operation
26801** common to all locking schemes. It closes the directory and file
26802** handles, if they are valid, and sets all fields of the unixFile
26803** structure to 0.
26804**
26805** It is *not* necessary to hold the mutex when this routine is called,
26806** even on VxWorks.  A mutex will be acquired on VxWorks by the
26807** vxworksReleaseFileId() routine.
26808*/
26809static int closeUnixFile(sqlite3_file *id){
26810  unixFile *pFile = (unixFile*)id;
26811  if( pFile->h>=0 ){
26812    robust_close(pFile, pFile->h, __LINE__);
26813    pFile->h = -1;
26814  }
26815#if OS_VXWORKS
26816  if( pFile->pId ){
26817    if( pFile->ctrlFlags & UNIXFILE_DELETE ){
26818      osUnlink(pFile->pId->zCanonicalName);
26819    }
26820    vxworksReleaseFileId(pFile->pId);
26821    pFile->pId = 0;
26822  }
26823#endif
26824  OSTRACE(("CLOSE   %-3d\n", pFile->h));
26825  OpenCounter(-1);
26826  sqlite3_free(pFile->pUnused);
26827  memset(pFile, 0, sizeof(unixFile));
26828  return SQLITE_OK;
26829}
26830
26831/*
26832** Close a file.
26833*/
26834static int unixClose(sqlite3_file *id){
26835  int rc = SQLITE_OK;
26836  unixFile *pFile = (unixFile *)id;
26837  unixUnlock(id, NO_LOCK);
26838  unixEnterMutex();
26839
26840  /* unixFile.pInode is always valid here. Otherwise, a different close
26841  ** routine (e.g. nolockClose()) would be called instead.
26842  */
26843  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
26844  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
26845    /* If there are outstanding locks, do not actually close the file just
26846    ** yet because that would clear those locks.  Instead, add the file
26847    ** descriptor to pInode->pUnused list.  It will be automatically closed
26848    ** when the last lock is cleared.
26849    */
26850    setPendingFd(pFile);
26851  }
26852  releaseInodeInfo(pFile);
26853  rc = closeUnixFile(id);
26854  unixLeaveMutex();
26855  return rc;
26856}
26857
26858/************** End of the posix advisory lock implementation *****************
26859******************************************************************************/
26860
26861/******************************************************************************
26862****************************** No-op Locking **********************************
26863**
26864** Of the various locking implementations available, this is by far the
26865** simplest:  locking is ignored.  No attempt is made to lock the database
26866** file for reading or writing.
26867**
26868** This locking mode is appropriate for use on read-only databases
26869** (ex: databases that are burned into CD-ROM, for example.)  It can
26870** also be used if the application employs some external mechanism to
26871** prevent simultaneous access of the same database by two or more
26872** database connections.  But there is a serious risk of database
26873** corruption if this locking mode is used in situations where multiple
26874** database connections are accessing the same database file at the same
26875** time and one or more of those connections are writing.
26876*/
26877
26878static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
26879  UNUSED_PARAMETER(NotUsed);
26880  *pResOut = 0;
26881  return SQLITE_OK;
26882}
26883static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
26884  UNUSED_PARAMETER2(NotUsed, NotUsed2);
26885  return SQLITE_OK;
26886}
26887static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
26888  UNUSED_PARAMETER2(NotUsed, NotUsed2);
26889  return SQLITE_OK;
26890}
26891
26892/*
26893** Close the file.
26894*/
26895static int nolockClose(sqlite3_file *id) {
26896  return closeUnixFile(id);
26897}
26898
26899/******************* End of the no-op lock implementation *********************
26900******************************************************************************/
26901
26902/******************************************************************************
26903************************* Begin dot-file Locking ******************************
26904**
26905** The dotfile locking implementation uses the existance of separate lock
26906** files (really a directory) to control access to the database.  This works
26907** on just about every filesystem imaginable.  But there are serious downsides:
26908**
26909**    (1)  There is zero concurrency.  A single reader blocks all other
26910**         connections from reading or writing the database.
26911**
26912**    (2)  An application crash or power loss can leave stale lock files
26913**         sitting around that need to be cleared manually.
26914**
26915** Nevertheless, a dotlock is an appropriate locking mode for use if no
26916** other locking strategy is available.
26917**
26918** Dotfile locking works by creating a subdirectory in the same directory as
26919** the database and with the same name but with a ".lock" extension added.
26920** The existance of a lock directory implies an EXCLUSIVE lock.  All other
26921** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
26922*/
26923
26924/*
26925** The file suffix added to the data base filename in order to create the
26926** lock directory.
26927*/
26928#define DOTLOCK_SUFFIX ".lock"
26929
26930/*
26931** This routine checks if there is a RESERVED lock held on the specified
26932** file by this or any other process. If such a lock is held, set *pResOut
26933** to a non-zero value otherwise *pResOut is set to zero.  The return value
26934** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26935**
26936** In dotfile locking, either a lock exists or it does not.  So in this
26937** variation of CheckReservedLock(), *pResOut is set to true if any lock
26938** is held on the file and false if the file is unlocked.
26939*/
26940static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
26941  int rc = SQLITE_OK;
26942  int reserved = 0;
26943  unixFile *pFile = (unixFile*)id;
26944
26945  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26946
26947  assert( pFile );
26948
26949  /* Check if a thread in this process holds such a lock */
26950  if( pFile->eFileLock>SHARED_LOCK ){
26951    /* Either this connection or some other connection in the same process
26952    ** holds a lock on the file.  No need to check further. */
26953    reserved = 1;
26954  }else{
26955    /* The lock is held if and only if the lockfile exists */
26956    const char *zLockFile = (const char*)pFile->lockingContext;
26957    reserved = osAccess(zLockFile, 0)==0;
26958  }
26959  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
26960  *pResOut = reserved;
26961  return rc;
26962}
26963
26964/*
26965** Lock the file with the lock specified by parameter eFileLock - one
26966** of the following:
26967**
26968**     (1) SHARED_LOCK
26969**     (2) RESERVED_LOCK
26970**     (3) PENDING_LOCK
26971**     (4) EXCLUSIVE_LOCK
26972**
26973** Sometimes when requesting one lock state, additional lock states
26974** are inserted in between.  The locking might fail on one of the later
26975** transitions leaving the lock state different from what it started but
26976** still short of its goal.  The following chart shows the allowed
26977** transitions and the inserted intermediate states:
26978**
26979**    UNLOCKED -> SHARED
26980**    SHARED -> RESERVED
26981**    SHARED -> (PENDING) -> EXCLUSIVE
26982**    RESERVED -> (PENDING) -> EXCLUSIVE
26983**    PENDING -> EXCLUSIVE
26984**
26985** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26986** routine to lower a locking level.
26987**
26988** With dotfile locking, we really only support state (4): EXCLUSIVE.
26989** But we track the other locking levels internally.
26990*/
26991static int dotlockLock(sqlite3_file *id, int eFileLock) {
26992  unixFile *pFile = (unixFile*)id;
26993  char *zLockFile = (char *)pFile->lockingContext;
26994  int rc = SQLITE_OK;
26995
26996
26997  /* If we have any lock, then the lock file already exists.  All we have
26998  ** to do is adjust our internal record of the lock level.
26999  */
27000  if( pFile->eFileLock > NO_LOCK ){
27001    pFile->eFileLock = eFileLock;
27002    /* Always update the timestamp on the old file */
27003#ifdef HAVE_UTIME
27004    utime(zLockFile, NULL);
27005#else
27006    utimes(zLockFile, NULL);
27007#endif
27008    return SQLITE_OK;
27009  }
27010
27011  /* grab an exclusive lock */
27012  rc = osMkdir(zLockFile, 0777);
27013  if( rc<0 ){
27014    /* failed to open/create the lock directory */
27015    int tErrno = errno;
27016    if( EEXIST == tErrno ){
27017      rc = SQLITE_BUSY;
27018    } else {
27019      rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27020      if( IS_LOCK_ERROR(rc) ){
27021        pFile->lastErrno = tErrno;
27022      }
27023    }
27024    return rc;
27025  }
27026
27027  /* got it, set the type and return ok */
27028  pFile->eFileLock = eFileLock;
27029  return rc;
27030}
27031
27032/*
27033** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27034** must be either NO_LOCK or SHARED_LOCK.
27035**
27036** If the locking level of the file descriptor is already at or below
27037** the requested locking level, this routine is a no-op.
27038**
27039** When the locking level reaches NO_LOCK, delete the lock file.
27040*/
27041static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
27042  unixFile *pFile = (unixFile*)id;
27043  char *zLockFile = (char *)pFile->lockingContext;
27044  int rc;
27045
27046  assert( pFile );
27047  OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
27048	   pFile->eFileLock, getpid()));
27049  assert( eFileLock<=SHARED_LOCK );
27050
27051  /* no-op if possible */
27052  if( pFile->eFileLock==eFileLock ){
27053    return SQLITE_OK;
27054  }
27055
27056  /* To downgrade to shared, simply update our internal notion of the
27057  ** lock state.  No need to mess with the file on disk.
27058  */
27059  if( eFileLock==SHARED_LOCK ){
27060    pFile->eFileLock = SHARED_LOCK;
27061    return SQLITE_OK;
27062  }
27063
27064  /* To fully unlock the database, delete the lock file */
27065  assert( eFileLock==NO_LOCK );
27066  rc = osRmdir(zLockFile);
27067  if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
27068  if( rc<0 ){
27069    int tErrno = errno;
27070    rc = 0;
27071    if( ENOENT != tErrno ){
27072      rc = SQLITE_IOERR_UNLOCK;
27073    }
27074    if( IS_LOCK_ERROR(rc) ){
27075      pFile->lastErrno = tErrno;
27076    }
27077    return rc;
27078  }
27079  pFile->eFileLock = NO_LOCK;
27080  return SQLITE_OK;
27081}
27082
27083/*
27084** Close a file.  Make sure the lock has been released before closing.
27085*/
27086static int dotlockClose(sqlite3_file *id) {
27087  int rc;
27088  if( id ){
27089    unixFile *pFile = (unixFile*)id;
27090    dotlockUnlock(id, NO_LOCK);
27091    sqlite3_free(pFile->lockingContext);
27092  }
27093  rc = closeUnixFile(id);
27094  return rc;
27095}
27096/****************** End of the dot-file lock implementation *******************
27097******************************************************************************/
27098
27099/******************************************************************************
27100************************** Begin flock Locking ********************************
27101**
27102** Use the flock() system call to do file locking.
27103**
27104** flock() locking is like dot-file locking in that the various
27105** fine-grain locking levels supported by SQLite are collapsed into
27106** a single exclusive lock.  In other words, SHARED, RESERVED, and
27107** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
27108** still works when you do this, but concurrency is reduced since
27109** only a single process can be reading the database at a time.
27110**
27111** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
27112** compiling for VXWORKS.
27113*/
27114#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
27115
27116/*
27117** Retry flock() calls that fail with EINTR
27118*/
27119#ifdef EINTR
27120static int robust_flock(int fd, int op){
27121  int rc;
27122  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
27123  return rc;
27124}
27125#else
27126# define robust_flock(a,b) flock(a,b)
27127#endif
27128
27129
27130/*
27131** This routine checks if there is a RESERVED lock held on the specified
27132** file by this or any other process. If such a lock is held, set *pResOut
27133** to a non-zero value otherwise *pResOut is set to zero.  The return value
27134** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27135*/
27136static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
27137  int rc = SQLITE_OK;
27138  int reserved = 0;
27139  unixFile *pFile = (unixFile*)id;
27140
27141  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27142
27143  assert( pFile );
27144
27145  /* Check if a thread in this process holds such a lock */
27146  if( pFile->eFileLock>SHARED_LOCK ){
27147    reserved = 1;
27148  }
27149
27150  /* Otherwise see if some other process holds it. */
27151  if( !reserved ){
27152    /* attempt to get the lock */
27153    int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
27154    if( !lrc ){
27155      /* got the lock, unlock it */
27156      lrc = robust_flock(pFile->h, LOCK_UN);
27157      if ( lrc ) {
27158        int tErrno = errno;
27159        /* unlock failed with an error */
27160        lrc = SQLITE_IOERR_UNLOCK;
27161        if( IS_LOCK_ERROR(lrc) ){
27162          pFile->lastErrno = tErrno;
27163          rc = lrc;
27164        }
27165      }
27166    } else {
27167      int tErrno = errno;
27168      reserved = 1;
27169      /* someone else might have it reserved */
27170      lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27171      if( IS_LOCK_ERROR(lrc) ){
27172        pFile->lastErrno = tErrno;
27173        rc = lrc;
27174      }
27175    }
27176  }
27177  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
27178
27179#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27180  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27181    rc = SQLITE_OK;
27182    reserved=1;
27183  }
27184#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27185  *pResOut = reserved;
27186  return rc;
27187}
27188
27189/*
27190** Lock the file with the lock specified by parameter eFileLock - one
27191** of the following:
27192**
27193**     (1) SHARED_LOCK
27194**     (2) RESERVED_LOCK
27195**     (3) PENDING_LOCK
27196**     (4) EXCLUSIVE_LOCK
27197**
27198** Sometimes when requesting one lock state, additional lock states
27199** are inserted in between.  The locking might fail on one of the later
27200** transitions leaving the lock state different from what it started but
27201** still short of its goal.  The following chart shows the allowed
27202** transitions and the inserted intermediate states:
27203**
27204**    UNLOCKED -> SHARED
27205**    SHARED -> RESERVED
27206**    SHARED -> (PENDING) -> EXCLUSIVE
27207**    RESERVED -> (PENDING) -> EXCLUSIVE
27208**    PENDING -> EXCLUSIVE
27209**
27210** flock() only really support EXCLUSIVE locks.  We track intermediate
27211** lock states in the sqlite3_file structure, but all locks SHARED or
27212** above are really EXCLUSIVE locks and exclude all other processes from
27213** access the file.
27214**
27215** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27216** routine to lower a locking level.
27217*/
27218static int flockLock(sqlite3_file *id, int eFileLock) {
27219  int rc = SQLITE_OK;
27220  unixFile *pFile = (unixFile*)id;
27221
27222  assert( pFile );
27223
27224  /* if we already have a lock, it is exclusive.
27225  ** Just adjust level and punt on outta here. */
27226  if (pFile->eFileLock > NO_LOCK) {
27227    pFile->eFileLock = eFileLock;
27228    return SQLITE_OK;
27229  }
27230
27231  /* grab an exclusive lock */
27232
27233  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
27234    int tErrno = errno;
27235    /* didn't get, must be busy */
27236    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27237    if( IS_LOCK_ERROR(rc) ){
27238      pFile->lastErrno = tErrno;
27239    }
27240  } else {
27241    /* got it, set the type and return ok */
27242    pFile->eFileLock = eFileLock;
27243  }
27244  OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
27245           rc==SQLITE_OK ? "ok" : "failed"));
27246#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27247  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27248    rc = SQLITE_BUSY;
27249  }
27250#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27251  return rc;
27252}
27253
27254
27255/*
27256** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27257** must be either NO_LOCK or SHARED_LOCK.
27258**
27259** If the locking level of the file descriptor is already at or below
27260** the requested locking level, this routine is a no-op.
27261*/
27262static int flockUnlock(sqlite3_file *id, int eFileLock) {
27263  unixFile *pFile = (unixFile*)id;
27264
27265  assert( pFile );
27266  OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
27267           pFile->eFileLock, getpid()));
27268  assert( eFileLock<=SHARED_LOCK );
27269
27270  /* no-op if possible */
27271  if( pFile->eFileLock==eFileLock ){
27272    return SQLITE_OK;
27273  }
27274
27275  /* shared can just be set because we always have an exclusive */
27276  if (eFileLock==SHARED_LOCK) {
27277    pFile->eFileLock = eFileLock;
27278    return SQLITE_OK;
27279  }
27280
27281  /* no, really, unlock. */
27282  if( robust_flock(pFile->h, LOCK_UN) ){
27283#ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27284    return SQLITE_OK;
27285#endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27286    return SQLITE_IOERR_UNLOCK;
27287  }else{
27288    pFile->eFileLock = NO_LOCK;
27289    return SQLITE_OK;
27290  }
27291}
27292
27293/*
27294** Close a file.
27295*/
27296static int flockClose(sqlite3_file *id) {
27297  if( id ){
27298    flockUnlock(id, NO_LOCK);
27299  }
27300  return closeUnixFile(id);
27301}
27302
27303#endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
27304
27305/******************* End of the flock lock implementation *********************
27306******************************************************************************/
27307
27308/******************************************************************************
27309************************ Begin Named Semaphore Locking ************************
27310**
27311** Named semaphore locking is only supported on VxWorks.
27312**
27313** Semaphore locking is like dot-lock and flock in that it really only
27314** supports EXCLUSIVE locking.  Only a single process can read or write
27315** the database file at a time.  This reduces potential concurrency, but
27316** makes the lock implementation much easier.
27317*/
27318#if OS_VXWORKS
27319
27320/*
27321** This routine checks if there is a RESERVED lock held on the specified
27322** file by this or any other process. If such a lock is held, set *pResOut
27323** to a non-zero value otherwise *pResOut is set to zero.  The return value
27324** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27325*/
27326static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
27327  int rc = SQLITE_OK;
27328  int reserved = 0;
27329  unixFile *pFile = (unixFile*)id;
27330
27331  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27332
27333  assert( pFile );
27334
27335  /* Check if a thread in this process holds such a lock */
27336  if( pFile->eFileLock>SHARED_LOCK ){
27337    reserved = 1;
27338  }
27339
27340  /* Otherwise see if some other process holds it. */
27341  if( !reserved ){
27342    sem_t *pSem = pFile->pInode->pSem;
27343    struct stat statBuf;
27344
27345    if( sem_trywait(pSem)==-1 ){
27346      int tErrno = errno;
27347      if( EAGAIN != tErrno ){
27348        rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
27349        pFile->lastErrno = tErrno;
27350      } else {
27351        /* someone else has the lock when we are in NO_LOCK */
27352        reserved = (pFile->eFileLock < SHARED_LOCK);
27353      }
27354    }else{
27355      /* we could have it if we want it */
27356      sem_post(pSem);
27357    }
27358  }
27359  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
27360
27361  *pResOut = reserved;
27362  return rc;
27363}
27364
27365/*
27366** Lock the file with the lock specified by parameter eFileLock - one
27367** of the following:
27368**
27369**     (1) SHARED_LOCK
27370**     (2) RESERVED_LOCK
27371**     (3) PENDING_LOCK
27372**     (4) EXCLUSIVE_LOCK
27373**
27374** Sometimes when requesting one lock state, additional lock states
27375** are inserted in between.  The locking might fail on one of the later
27376** transitions leaving the lock state different from what it started but
27377** still short of its goal.  The following chart shows the allowed
27378** transitions and the inserted intermediate states:
27379**
27380**    UNLOCKED -> SHARED
27381**    SHARED -> RESERVED
27382**    SHARED -> (PENDING) -> EXCLUSIVE
27383**    RESERVED -> (PENDING) -> EXCLUSIVE
27384**    PENDING -> EXCLUSIVE
27385**
27386** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
27387** lock states in the sqlite3_file structure, but all locks SHARED or
27388** above are really EXCLUSIVE locks and exclude all other processes from
27389** access the file.
27390**
27391** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27392** routine to lower a locking level.
27393*/
27394static int semLock(sqlite3_file *id, int eFileLock) {
27395  unixFile *pFile = (unixFile*)id;
27396  int fd;
27397  sem_t *pSem = pFile->pInode->pSem;
27398  int rc = SQLITE_OK;
27399
27400  /* if we already have a lock, it is exclusive.
27401  ** Just adjust level and punt on outta here. */
27402  if (pFile->eFileLock > NO_LOCK) {
27403    pFile->eFileLock = eFileLock;
27404    rc = SQLITE_OK;
27405    goto sem_end_lock;
27406  }
27407
27408  /* lock semaphore now but bail out when already locked. */
27409  if( sem_trywait(pSem)==-1 ){
27410    rc = SQLITE_BUSY;
27411    goto sem_end_lock;
27412  }
27413
27414  /* got it, set the type and return ok */
27415  pFile->eFileLock = eFileLock;
27416
27417 sem_end_lock:
27418  return rc;
27419}
27420
27421/*
27422** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27423** must be either NO_LOCK or SHARED_LOCK.
27424**
27425** If the locking level of the file descriptor is already at or below
27426** the requested locking level, this routine is a no-op.
27427*/
27428static int semUnlock(sqlite3_file *id, int eFileLock) {
27429  unixFile *pFile = (unixFile*)id;
27430  sem_t *pSem = pFile->pInode->pSem;
27431
27432  assert( pFile );
27433  assert( pSem );
27434  OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
27435	   pFile->eFileLock, getpid()));
27436  assert( eFileLock<=SHARED_LOCK );
27437
27438  /* no-op if possible */
27439  if( pFile->eFileLock==eFileLock ){
27440    return SQLITE_OK;
27441  }
27442
27443  /* shared can just be set because we always have an exclusive */
27444  if (eFileLock==SHARED_LOCK) {
27445    pFile->eFileLock = eFileLock;
27446    return SQLITE_OK;
27447  }
27448
27449  /* no, really unlock. */
27450  if ( sem_post(pSem)==-1 ) {
27451    int rc, tErrno = errno;
27452    rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
27453    if( IS_LOCK_ERROR(rc) ){
27454      pFile->lastErrno = tErrno;
27455    }
27456    return rc;
27457  }
27458  pFile->eFileLock = NO_LOCK;
27459  return SQLITE_OK;
27460}
27461
27462/*
27463 ** Close a file.
27464 */
27465static int semClose(sqlite3_file *id) {
27466  if( id ){
27467    unixFile *pFile = (unixFile*)id;
27468    semUnlock(id, NO_LOCK);
27469    assert( pFile );
27470    unixEnterMutex();
27471    releaseInodeInfo(pFile);
27472    unixLeaveMutex();
27473    closeUnixFile(id);
27474  }
27475  return SQLITE_OK;
27476}
27477
27478#endif /* OS_VXWORKS */
27479/*
27480** Named semaphore locking is only available on VxWorks.
27481**
27482*************** End of the named semaphore lock implementation ****************
27483******************************************************************************/
27484
27485
27486/******************************************************************************
27487*************************** Begin AFP Locking *********************************
27488**
27489** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
27490** on Apple Macintosh computers - both OS9 and OSX.
27491**
27492** Third-party implementations of AFP are available.  But this code here
27493** only works on OSX.
27494*/
27495
27496#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27497/*
27498** The afpLockingContext structure contains all afp lock specific state
27499*/
27500typedef struct afpLockingContext afpLockingContext;
27501struct afpLockingContext {
27502  int reserved;
27503  const char *dbPath;             /* Name of the open file */
27504};
27505
27506struct ByteRangeLockPB2
27507{
27508  unsigned long long offset;        /* offset to first byte to lock */
27509  unsigned long long length;        /* nbr of bytes to lock */
27510  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
27511  unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
27512  unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
27513  int fd;                           /* file desc to assoc this lock with */
27514};
27515
27516#define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
27517
27518/*
27519** This is a utility for setting or clearing a bit-range lock on an
27520** AFP filesystem.
27521**
27522** Return SQLITE_OK on success, SQLITE_BUSY on failure.
27523*/
27524static int afpSetLock(
27525  const char *path,              /* Name of the file to be locked or unlocked */
27526  unixFile *pFile,               /* Open file descriptor on path */
27527  unsigned long long offset,     /* First byte to be locked */
27528  unsigned long long length,     /* Number of bytes to lock */
27529  int setLockFlag                /* True to set lock.  False to clear lock */
27530){
27531  struct ByteRangeLockPB2 pb;
27532  int err;
27533
27534  pb.unLockFlag = setLockFlag ? 0 : 1;
27535  pb.startEndFlag = 0;
27536  pb.offset = offset;
27537  pb.length = length;
27538  pb.fd = pFile->h;
27539
27540  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
27541    (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
27542    offset, length));
27543  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
27544  if ( err==-1 ) {
27545    int rc;
27546    int tErrno = errno;
27547    OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
27548             path, tErrno, strerror(tErrno)));
27549#ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
27550    rc = SQLITE_BUSY;
27551#else
27552    rc = sqliteErrorFromPosixError(tErrno,
27553                    setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
27554#endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
27555    if( IS_LOCK_ERROR(rc) ){
27556      pFile->lastErrno = tErrno;
27557    }
27558    return rc;
27559  } else {
27560    return SQLITE_OK;
27561  }
27562}
27563
27564/*
27565** This routine checks if there is a RESERVED lock held on the specified
27566** file by this or any other process. If such a lock is held, set *pResOut
27567** to a non-zero value otherwise *pResOut is set to zero.  The return value
27568** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27569*/
27570static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
27571  int rc = SQLITE_OK;
27572  int reserved = 0;
27573  unixFile *pFile = (unixFile*)id;
27574  afpLockingContext *context;
27575
27576  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27577
27578  assert( pFile );
27579  context = (afpLockingContext *) pFile->lockingContext;
27580  if( context->reserved ){
27581    *pResOut = 1;
27582    return SQLITE_OK;
27583  }
27584  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
27585
27586  /* Check if a thread in this process holds such a lock */
27587  if( pFile->pInode->eFileLock>SHARED_LOCK ){
27588    reserved = 1;
27589  }
27590
27591  /* Otherwise see if some other process holds it.
27592   */
27593  if( !reserved ){
27594    /* lock the RESERVED byte */
27595    int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27596    if( SQLITE_OK==lrc ){
27597      /* if we succeeded in taking the reserved lock, unlock it to restore
27598      ** the original state */
27599      lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27600    } else {
27601      /* if we failed to get the lock then someone else must have it */
27602      reserved = 1;
27603    }
27604    if( IS_LOCK_ERROR(lrc) ){
27605      rc=lrc;
27606    }
27607  }
27608
27609  unixLeaveMutex();
27610  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
27611
27612  *pResOut = reserved;
27613  return rc;
27614}
27615
27616/*
27617** Lock the file with the lock specified by parameter eFileLock - one
27618** of the following:
27619**
27620**     (1) SHARED_LOCK
27621**     (2) RESERVED_LOCK
27622**     (3) PENDING_LOCK
27623**     (4) EXCLUSIVE_LOCK
27624**
27625** Sometimes when requesting one lock state, additional lock states
27626** are inserted in between.  The locking might fail on one of the later
27627** transitions leaving the lock state different from what it started but
27628** still short of its goal.  The following chart shows the allowed
27629** transitions and the inserted intermediate states:
27630**
27631**    UNLOCKED -> SHARED
27632**    SHARED -> RESERVED
27633**    SHARED -> (PENDING) -> EXCLUSIVE
27634**    RESERVED -> (PENDING) -> EXCLUSIVE
27635**    PENDING -> EXCLUSIVE
27636**
27637** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27638** routine to lower a locking level.
27639*/
27640static int afpLock(sqlite3_file *id, int eFileLock){
27641  int rc = SQLITE_OK;
27642  unixFile *pFile = (unixFile*)id;
27643  unixInodeInfo *pInode = pFile->pInode;
27644  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27645
27646  assert( pFile );
27647  OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
27648           azFileLock(eFileLock), azFileLock(pFile->eFileLock),
27649           azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
27650
27651  /* If there is already a lock of this type or more restrictive on the
27652  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
27653  ** unixEnterMutex() hasn't been called yet.
27654  */
27655  if( pFile->eFileLock>=eFileLock ){
27656    OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
27657           azFileLock(eFileLock)));
27658    return SQLITE_OK;
27659  }
27660
27661  /* Make sure the locking sequence is correct
27662  **  (1) We never move from unlocked to anything higher than shared lock.
27663  **  (2) SQLite never explicitly requests a pendig lock.
27664  **  (3) A shared lock is always held when a reserve lock is requested.
27665  */
27666  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
27667  assert( eFileLock!=PENDING_LOCK );
27668  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
27669
27670  /* This mutex is needed because pFile->pInode is shared across threads
27671  */
27672  unixEnterMutex();
27673  pInode = pFile->pInode;
27674
27675  /* If some thread using this PID has a lock via a different unixFile*
27676  ** handle that precludes the requested lock, return BUSY.
27677  */
27678  if( (pFile->eFileLock!=pInode->eFileLock &&
27679       (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
27680     ){
27681    rc = SQLITE_BUSY;
27682    goto afp_end_lock;
27683  }
27684
27685  /* If a SHARED lock is requested, and some thread using this PID already
27686  ** has a SHARED or RESERVED lock, then increment reference counts and
27687  ** return SQLITE_OK.
27688  */
27689  if( eFileLock==SHARED_LOCK &&
27690     (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
27691    assert( eFileLock==SHARED_LOCK );
27692    assert( pFile->eFileLock==0 );
27693    assert( pInode->nShared>0 );
27694    pFile->eFileLock = SHARED_LOCK;
27695    pInode->nShared++;
27696    pInode->nLock++;
27697    goto afp_end_lock;
27698  }
27699
27700  /* A PENDING lock is needed before acquiring a SHARED lock and before
27701  ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
27702  ** be released.
27703  */
27704  if( eFileLock==SHARED_LOCK
27705      || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
27706  ){
27707    int failed;
27708    failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
27709    if (failed) {
27710      rc = failed;
27711      goto afp_end_lock;
27712    }
27713  }
27714
27715  /* If control gets to this point, then actually go ahead and make
27716  ** operating system calls for the specified lock.
27717  */
27718  if( eFileLock==SHARED_LOCK ){
27719    int lrc1, lrc2, lrc1Errno = 0;
27720    long lk, mask;
27721
27722    assert( pInode->nShared==0 );
27723    assert( pInode->eFileLock==0 );
27724
27725    mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
27726    /* Now get the read-lock SHARED_LOCK */
27727    /* note that the quality of the randomness doesn't matter that much */
27728    lk = random();
27729    pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
27730    lrc1 = afpSetLock(context->dbPath, pFile,
27731          SHARED_FIRST+pInode->sharedByte, 1, 1);
27732    if( IS_LOCK_ERROR(lrc1) ){
27733      lrc1Errno = pFile->lastErrno;
27734    }
27735    /* Drop the temporary PENDING lock */
27736    lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27737
27738    if( IS_LOCK_ERROR(lrc1) ) {
27739      pFile->lastErrno = lrc1Errno;
27740      rc = lrc1;
27741      goto afp_end_lock;
27742    } else if( IS_LOCK_ERROR(lrc2) ){
27743      rc = lrc2;
27744      goto afp_end_lock;
27745    } else if( lrc1 != SQLITE_OK ) {
27746      rc = lrc1;
27747    } else {
27748      pFile->eFileLock = SHARED_LOCK;
27749      pInode->nLock++;
27750      pInode->nShared = 1;
27751    }
27752  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27753    /* We are trying for an exclusive lock but another thread in this
27754     ** same process is still holding a shared lock. */
27755    rc = SQLITE_BUSY;
27756  }else{
27757    /* The request was for a RESERVED or EXCLUSIVE lock.  It is
27758    ** assumed that there is a SHARED or greater lock on the file
27759    ** already.
27760    */
27761    int failed = 0;
27762    assert( 0!=pFile->eFileLock );
27763    if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
27764        /* Acquire a RESERVED lock */
27765        failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
27766      if( !failed ){
27767        context->reserved = 1;
27768      }
27769    }
27770    if (!failed && eFileLock == EXCLUSIVE_LOCK) {
27771      /* Acquire an EXCLUSIVE lock */
27772
27773      /* Remove the shared lock before trying the range.  we'll need to
27774      ** reestablish the shared lock if we can't get the  afpUnlock
27775      */
27776      if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
27777                         pInode->sharedByte, 1, 0)) ){
27778        int failed2 = SQLITE_OK;
27779        /* now attemmpt to get the exclusive lock range */
27780        failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
27781                               SHARED_SIZE, 1);
27782        if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
27783                       SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
27784          /* Can't reestablish the shared lock.  Sqlite can't deal, this is
27785          ** a critical I/O error
27786          */
27787          rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
27788               SQLITE_IOERR_LOCK;
27789          goto afp_end_lock;
27790        }
27791      }else{
27792        rc = failed;
27793      }
27794    }
27795    if( failed ){
27796      rc = failed;
27797    }
27798  }
27799
27800  if( rc==SQLITE_OK ){
27801    pFile->eFileLock = eFileLock;
27802    pInode->eFileLock = eFileLock;
27803  }else if( eFileLock==EXCLUSIVE_LOCK ){
27804    pFile->eFileLock = PENDING_LOCK;
27805    pInode->eFileLock = PENDING_LOCK;
27806  }
27807
27808afp_end_lock:
27809  unixLeaveMutex();
27810  OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
27811         rc==SQLITE_OK ? "ok" : "failed"));
27812  return rc;
27813}
27814
27815/*
27816** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27817** must be either NO_LOCK or SHARED_LOCK.
27818**
27819** If the locking level of the file descriptor is already at or below
27820** the requested locking level, this routine is a no-op.
27821*/
27822static int afpUnlock(sqlite3_file *id, int eFileLock) {
27823  int rc = SQLITE_OK;
27824  unixFile *pFile = (unixFile*)id;
27825  unixInodeInfo *pInode;
27826  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
27827  int skipShared = 0;
27828#ifdef SQLITE_TEST
27829  int h = pFile->h;
27830#endif
27831
27832  assert( pFile );
27833  OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
27834           pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27835           getpid()));
27836
27837  assert( eFileLock<=SHARED_LOCK );
27838  if( pFile->eFileLock<=eFileLock ){
27839    return SQLITE_OK;
27840  }
27841  unixEnterMutex();
27842  pInode = pFile->pInode;
27843  assert( pInode->nShared!=0 );
27844  if( pFile->eFileLock>SHARED_LOCK ){
27845    assert( pInode->eFileLock==pFile->eFileLock );
27846    SimulateIOErrorBenign(1);
27847    SimulateIOError( h=(-1) )
27848    SimulateIOErrorBenign(0);
27849
27850#ifndef NDEBUG
27851    /* When reducing a lock such that other processes can start
27852    ** reading the database file again, make sure that the
27853    ** transaction counter was updated if any part of the database
27854    ** file changed.  If the transaction counter is not updated,
27855    ** other connections to the same file might not realize that
27856    ** the file has changed and hence might not know to flush their
27857    ** cache.  The use of a stale cache can lead to database corruption.
27858    */
27859    assert( pFile->inNormalWrite==0
27860           || pFile->dbUpdate==0
27861           || pFile->transCntrChng==1 );
27862    pFile->inNormalWrite = 0;
27863#endif
27864
27865    if( pFile->eFileLock==EXCLUSIVE_LOCK ){
27866      rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
27867      if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
27868        /* only re-establish the shared lock if necessary */
27869        int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27870        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
27871      } else {
27872        skipShared = 1;
27873      }
27874    }
27875    if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
27876      rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
27877    }
27878    if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
27879      rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
27880      if( !rc ){
27881        context->reserved = 0;
27882      }
27883    }
27884    if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
27885      pInode->eFileLock = SHARED_LOCK;
27886    }
27887  }
27888  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
27889
27890    /* Decrement the shared lock counter.  Release the lock using an
27891    ** OS call only when all threads in this same process have released
27892    ** the lock.
27893    */
27894    unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
27895    pInode->nShared--;
27896    if( pInode->nShared==0 ){
27897      SimulateIOErrorBenign(1);
27898      SimulateIOError( h=(-1) )
27899      SimulateIOErrorBenign(0);
27900      if( !skipShared ){
27901        rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
27902      }
27903      if( !rc ){
27904        pInode->eFileLock = NO_LOCK;
27905        pFile->eFileLock = NO_LOCK;
27906      }
27907    }
27908    if( rc==SQLITE_OK ){
27909      pInode->nLock--;
27910      assert( pInode->nLock>=0 );
27911      if( pInode->nLock==0 ){
27912        closePendingFds(pFile);
27913      }
27914    }
27915  }
27916
27917  unixLeaveMutex();
27918  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27919  return rc;
27920}
27921
27922/*
27923** Close a file & cleanup AFP specific locking context
27924*/
27925static int afpClose(sqlite3_file *id) {
27926  int rc = SQLITE_OK;
27927  if( id ){
27928    unixFile *pFile = (unixFile*)id;
27929    afpUnlock(id, NO_LOCK);
27930    unixEnterMutex();
27931    if( pFile->pInode && pFile->pInode->nLock ){
27932      /* If there are outstanding locks, do not actually close the file just
27933      ** yet because that would clear those locks.  Instead, add the file
27934      ** descriptor to pInode->aPending.  It will be automatically closed when
27935      ** the last lock is cleared.
27936      */
27937      setPendingFd(pFile);
27938    }
27939    releaseInodeInfo(pFile);
27940    sqlite3_free(pFile->lockingContext);
27941    rc = closeUnixFile(id);
27942    unixLeaveMutex();
27943  }
27944  return rc;
27945}
27946
27947#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27948/*
27949** The code above is the AFP lock implementation.  The code is specific
27950** to MacOSX and does not work on other unix platforms.  No alternative
27951** is available.  If you don't compile for a mac, then the "unix-afp"
27952** VFS is not available.
27953**
27954********************* End of the AFP lock implementation **********************
27955******************************************************************************/
27956
27957/******************************************************************************
27958*************************** Begin NFS Locking ********************************/
27959
27960#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27961/*
27962 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27963 ** must be either NO_LOCK or SHARED_LOCK.
27964 **
27965 ** If the locking level of the file descriptor is already at or below
27966 ** the requested locking level, this routine is a no-op.
27967 */
27968static int nfsUnlock(sqlite3_file *id, int eFileLock){
27969  return posixUnlock(id, eFileLock, 1);
27970}
27971
27972#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27973/*
27974** The code above is the NFS lock implementation.  The code is specific
27975** to MacOSX and does not work on other unix platforms.  No alternative
27976** is available.
27977**
27978********************* End of the NFS lock implementation **********************
27979******************************************************************************/
27980
27981/******************************************************************************
27982**************** Non-locking sqlite3_file methods *****************************
27983**
27984** The next division contains implementations for all methods of the
27985** sqlite3_file object other than the locking methods.  The locking
27986** methods were defined in divisions above (one locking method per
27987** division).  Those methods that are common to all locking modes
27988** are gather together into this division.
27989*/
27990
27991/*
27992** Seek to the offset passed as the second argument, then read cnt
27993** bytes into pBuf. Return the number of bytes actually read.
27994**
27995** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
27996** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
27997** one system to another.  Since SQLite does not define USE_PREAD
27998** any any form by default, we will not attempt to define _XOPEN_SOURCE.
27999** See tickets #2741 and #2681.
28000**
28001** To avoid stomping the errno value on a failed read the lastErrno value
28002** is set before returning.
28003*/
28004static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
28005  int got;
28006  int prior = 0;
28007#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28008  i64 newOffset;
28009#endif
28010  TIMER_START;
28011  do{
28012#if defined(USE_PREAD)
28013    got = osPread(id->h, pBuf, cnt, offset);
28014    SimulateIOError( got = -1 );
28015#elif defined(USE_PREAD64)
28016    got = osPread64(id->h, pBuf, cnt, offset);
28017    SimulateIOError( got = -1 );
28018#else
28019    newOffset = lseek(id->h, offset, SEEK_SET);
28020    SimulateIOError( newOffset-- );
28021    if( newOffset!=offset ){
28022      if( newOffset == -1 ){
28023        ((unixFile*)id)->lastErrno = errno;
28024      }else{
28025        ((unixFile*)id)->lastErrno = 0;
28026      }
28027      return -1;
28028    }
28029    got = osRead(id->h, pBuf, cnt);
28030#endif
28031    if( got==cnt ) break;
28032    if( got<0 ){
28033      if( errno==EINTR ){ got = 1; continue; }
28034      prior = 0;
28035      ((unixFile*)id)->lastErrno = errno;
28036      break;
28037    }else if( got>0 ){
28038      cnt -= got;
28039      offset += got;
28040      prior += got;
28041      pBuf = (void*)(got + (char*)pBuf);
28042    }
28043  }while( got>0 );
28044  TIMER_END;
28045  OSTRACE(("READ    %-3d %5d %7lld %llu\n",
28046            id->h, got+prior, offset-prior, TIMER_ELAPSED));
28047  return got+prior;
28048}
28049
28050/*
28051** Read data from a file into a buffer.  Return SQLITE_OK if all
28052** bytes were read successfully and SQLITE_IOERR if anything goes
28053** wrong.
28054*/
28055static int unixRead(
28056  sqlite3_file *id,
28057  void *pBuf,
28058  int amt,
28059  sqlite3_int64 offset
28060){
28061  unixFile *pFile = (unixFile *)id;
28062  int got;
28063  assert( id );
28064
28065  /* If this is a database file (not a journal, master-journal or temp
28066  ** file), the bytes in the locking range should never be read or written. */
28067#if 0
28068  assert( pFile->pUnused==0
28069       || offset>=PENDING_BYTE+512
28070       || offset+amt<=PENDING_BYTE
28071  );
28072#endif
28073
28074  got = seekAndRead(pFile, offset, pBuf, amt);
28075  if( got==amt ){
28076    return SQLITE_OK;
28077  }else if( got<0 ){
28078    /* lastErrno set by seekAndRead */
28079    return SQLITE_IOERR_READ;
28080  }else{
28081    pFile->lastErrno = 0; /* not a system error */
28082    /* Unread parts of the buffer must be zero-filled */
28083    memset(&((char*)pBuf)[got], 0, amt-got);
28084    return SQLITE_IOERR_SHORT_READ;
28085  }
28086}
28087
28088/*
28089** Seek to the offset in id->offset then read cnt bytes into pBuf.
28090** Return the number of bytes actually read.  Update the offset.
28091**
28092** To avoid stomping the errno value on a failed write the lastErrno value
28093** is set before returning.
28094*/
28095static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
28096  int got;
28097#if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28098  i64 newOffset;
28099#endif
28100  TIMER_START;
28101#if defined(USE_PREAD)
28102  do{ got = osPwrite(id->h, pBuf, cnt, offset); }while( got<0 && errno==EINTR );
28103#elif defined(USE_PREAD64)
28104  do{ got = osPwrite64(id->h, pBuf, cnt, offset);}while( got<0 && errno==EINTR);
28105#else
28106  do{
28107    newOffset = lseek(id->h, offset, SEEK_SET);
28108    SimulateIOError( newOffset-- );
28109    if( newOffset!=offset ){
28110      if( newOffset == -1 ){
28111        ((unixFile*)id)->lastErrno = errno;
28112      }else{
28113        ((unixFile*)id)->lastErrno = 0;
28114      }
28115      return -1;
28116    }
28117    got = osWrite(id->h, pBuf, cnt);
28118  }while( got<0 && errno==EINTR );
28119#endif
28120  TIMER_END;
28121  if( got<0 ){
28122    ((unixFile*)id)->lastErrno = errno;
28123  }
28124
28125  OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED));
28126  return got;
28127}
28128
28129
28130/*
28131** Write data from a buffer into a file.  Return SQLITE_OK on success
28132** or some other error code on failure.
28133*/
28134static int unixWrite(
28135  sqlite3_file *id,
28136  const void *pBuf,
28137  int amt,
28138  sqlite3_int64 offset
28139){
28140  unixFile *pFile = (unixFile*)id;
28141  int wrote = 0;
28142  assert( id );
28143  assert( amt>0 );
28144
28145  /* If this is a database file (not a journal, master-journal or temp
28146  ** file), the bytes in the locking range should never be read or written. */
28147#if 0
28148  assert( pFile->pUnused==0
28149       || offset>=PENDING_BYTE+512
28150       || offset+amt<=PENDING_BYTE
28151  );
28152#endif
28153
28154#ifndef NDEBUG
28155  /* If we are doing a normal write to a database file (as opposed to
28156  ** doing a hot-journal rollback or a write to some file other than a
28157  ** normal database file) then record the fact that the database
28158  ** has changed.  If the transaction counter is modified, record that
28159  ** fact too.
28160  */
28161  if( pFile->inNormalWrite ){
28162    pFile->dbUpdate = 1;  /* The database has been modified */
28163    if( offset<=24 && offset+amt>=27 ){
28164      int rc;
28165      char oldCntr[4];
28166      SimulateIOErrorBenign(1);
28167      rc = seekAndRead(pFile, 24, oldCntr, 4);
28168      SimulateIOErrorBenign(0);
28169      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
28170        pFile->transCntrChng = 1;  /* The transaction counter has changed */
28171      }
28172    }
28173  }
28174#endif
28175
28176  while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
28177    amt -= wrote;
28178    offset += wrote;
28179    pBuf = &((char*)pBuf)[wrote];
28180  }
28181  SimulateIOError(( wrote=(-1), amt=1 ));
28182  SimulateDiskfullError(( wrote=0, amt=1 ));
28183
28184  if( amt>0 ){
28185    if( wrote<0 && pFile->lastErrno!=ENOSPC ){
28186      /* lastErrno set by seekAndWrite */
28187      return SQLITE_IOERR_WRITE;
28188    }else{
28189      pFile->lastErrno = 0; /* not a system error */
28190      return SQLITE_FULL;
28191    }
28192  }
28193
28194  return SQLITE_OK;
28195}
28196
28197#ifdef SQLITE_TEST
28198/*
28199** Count the number of fullsyncs and normal syncs.  This is used to test
28200** that syncs and fullsyncs are occurring at the right times.
28201*/
28202SQLITE_API int sqlite3_sync_count = 0;
28203SQLITE_API int sqlite3_fullsync_count = 0;
28204#endif
28205
28206/*
28207** We do not trust systems to provide a working fdatasync().  Some do.
28208** Others do no.  To be safe, we will stick with the (slightly slower)
28209** fsync(). If you know that your system does support fdatasync() correctly,
28210** then simply compile with -Dfdatasync=fdatasync
28211*/
28212#if !defined(fdatasync)
28213# define fdatasync fsync
28214#endif
28215
28216/*
28217** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
28218** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
28219** only available on Mac OS X.  But that could change.
28220*/
28221#ifdef F_FULLFSYNC
28222# define HAVE_FULLFSYNC 1
28223#else
28224# define HAVE_FULLFSYNC 0
28225#endif
28226
28227
28228/*
28229** The fsync() system call does not work as advertised on many
28230** unix systems.  The following procedure is an attempt to make
28231** it work better.
28232**
28233** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
28234** for testing when we want to run through the test suite quickly.
28235** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
28236** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
28237** or power failure will likely corrupt the database file.
28238**
28239** SQLite sets the dataOnly flag if the size of the file is unchanged.
28240** The idea behind dataOnly is that it should only write the file content
28241** to disk, not the inode.  We only set dataOnly if the file size is
28242** unchanged since the file size is part of the inode.  However,
28243** Ted Ts'o tells us that fdatasync() will also write the inode if the
28244** file size has changed.  The only real difference between fdatasync()
28245** and fsync(), Ted tells us, is that fdatasync() will not flush the
28246** inode if the mtime or owner or other inode attributes have changed.
28247** We only care about the file size, not the other file attributes, so
28248** as far as SQLite is concerned, an fdatasync() is always adequate.
28249** So, we always use fdatasync() if it is available, regardless of
28250** the value of the dataOnly flag.
28251*/
28252static int full_fsync(int fd, int fullSync, int dataOnly){
28253  int rc;
28254
28255  /* The following "ifdef/elif/else/" block has the same structure as
28256  ** the one below. It is replicated here solely to avoid cluttering
28257  ** up the real code with the UNUSED_PARAMETER() macros.
28258  */
28259#ifdef SQLITE_NO_SYNC
28260  UNUSED_PARAMETER(fd);
28261  UNUSED_PARAMETER(fullSync);
28262  UNUSED_PARAMETER(dataOnly);
28263#elif HAVE_FULLFSYNC
28264  UNUSED_PARAMETER(dataOnly);
28265#else
28266  UNUSED_PARAMETER(fullSync);
28267  UNUSED_PARAMETER(dataOnly);
28268#endif
28269
28270  /* Record the number of times that we do a normal fsync() and
28271  ** FULLSYNC.  This is used during testing to verify that this procedure
28272  ** gets called with the correct arguments.
28273  */
28274#ifdef SQLITE_TEST
28275  if( fullSync ) sqlite3_fullsync_count++;
28276  sqlite3_sync_count++;
28277#endif
28278
28279  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28280  ** no-op
28281  */
28282#ifdef SQLITE_NO_SYNC
28283  rc = SQLITE_OK;
28284#elif HAVE_FULLFSYNC
28285  if( fullSync ){
28286    rc = osFcntl(fd, F_FULLFSYNC, 0);
28287  }else{
28288    rc = 1;
28289  }
28290  /* If the FULLFSYNC failed, fall back to attempting an fsync().
28291  ** It shouldn't be possible for fullfsync to fail on the local
28292  ** file system (on OSX), so failure indicates that FULLFSYNC
28293  ** isn't supported for this file system. So, attempt an fsync
28294  ** and (for now) ignore the overhead of a superfluous fcntl call.
28295  ** It'd be better to detect fullfsync support once and avoid
28296  ** the fcntl call every time sync is called.
28297  */
28298  if( rc ) rc = fsync(fd);
28299
28300#elif defined(__APPLE__)
28301  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
28302  ** so currently we default to the macro that redefines fdatasync to fsync
28303  */
28304  rc = fsync(fd);
28305#else
28306  rc = fdatasync(fd);
28307#if OS_VXWORKS
28308  if( rc==-1 && errno==ENOTSUP ){
28309    rc = fsync(fd);
28310  }
28311#endif /* OS_VXWORKS */
28312#endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
28313
28314  if( OS_VXWORKS && rc!= -1 ){
28315    rc = 0;
28316  }
28317  return rc;
28318}
28319
28320/*
28321** Open a file descriptor to the directory containing file zFilename.
28322** If successful, *pFd is set to the opened file descriptor and
28323** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28324** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28325** value.
28326**
28327** The directory file descriptor is used for only one thing - to
28328** fsync() a directory to make sure file creation and deletion events
28329** are flushed to disk.  Such fsyncs are not needed on newer
28330** journaling filesystems, but are required on older filesystems.
28331**
28332** This routine can be overridden using the xSetSysCall interface.
28333** The ability to override this routine was added in support of the
28334** chromium sandbox.  Opening a directory is a security risk (we are
28335** told) so making it overrideable allows the chromium sandbox to
28336** replace this routine with a harmless no-op.  To make this routine
28337** a no-op, replace it with a stub that returns SQLITE_OK but leaves
28338** *pFd set to a negative number.
28339**
28340** If SQLITE_OK is returned, the caller is responsible for closing
28341** the file descriptor *pFd using close().
28342*/
28343static int openDirectory(const char *zFilename, int *pFd){
28344  int ii;
28345  int fd = -1;
28346  char zDirname[MAX_PATHNAME+1];
28347
28348  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28349  for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28350  if( ii>0 ){
28351    zDirname[ii] = '\0';
28352    fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28353    if( fd>=0 ){
28354#ifdef FD_CLOEXEC
28355      osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
28356#endif
28357      OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28358    }
28359  }
28360  *pFd = fd;
28361  return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28362}
28363
28364/*
28365** Make sure all writes to a particular file are committed to disk.
28366**
28367** If dataOnly==0 then both the file itself and its metadata (file
28368** size, access time, etc) are synced.  If dataOnly!=0 then only the
28369** file data is synced.
28370**
28371** Under Unix, also make sure that the directory entry for the file
28372** has been created by fsync-ing the directory that contains the file.
28373** If we do not do this and we encounter a power failure, the directory
28374** entry for the journal might not exist after we reboot.  The next
28375** SQLite to access the file will not know that the journal exists (because
28376** the directory entry for the journal was never created) and the transaction
28377** will not roll back - possibly leading to database corruption.
28378*/
28379static int unixSync(sqlite3_file *id, int flags){
28380  int rc;
28381  unixFile *pFile = (unixFile*)id;
28382
28383  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
28384  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
28385
28386  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
28387  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
28388      || (flags&0x0F)==SQLITE_SYNC_FULL
28389  );
28390
28391  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
28392  ** line is to test that doing so does not cause any problems.
28393  */
28394  SimulateDiskfullError( return SQLITE_FULL );
28395
28396  assert( pFile );
28397  OSTRACE(("SYNC    %-3d\n", pFile->h));
28398  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
28399  SimulateIOError( rc=1 );
28400  if( rc ){
28401    pFile->lastErrno = errno;
28402    return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
28403  }
28404
28405  /* Also fsync the directory containing the file if the DIRSYNC flag
28406  ** is set.  This is a one-time occurrance.  Many systems (examples: AIX)
28407  ** are unable to fsync a directory, so ignore errors on the fsync.
28408  */
28409  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
28410    int dirfd;
28411    OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
28412            HAVE_FULLFSYNC, isFullsync));
28413    rc = osOpenDirectory(pFile->zPath, &dirfd);
28414    if( rc==SQLITE_OK && dirfd>=0 ){
28415      full_fsync(dirfd, 0, 0);
28416      robust_close(pFile, dirfd, __LINE__);
28417    }else if( rc==SQLITE_CANTOPEN ){
28418      rc = SQLITE_OK;
28419    }
28420    pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
28421  }
28422  return rc;
28423}
28424
28425/*
28426** Truncate an open file to a specified size
28427*/
28428static int unixTruncate(sqlite3_file *id, i64 nByte){
28429  unixFile *pFile = (unixFile *)id;
28430  int rc;
28431  assert( pFile );
28432  SimulateIOError( return SQLITE_IOERR_TRUNCATE );
28433
28434  /* If the user has configured a chunk-size for this file, truncate the
28435  ** file so that it consists of an integer number of chunks (i.e. the
28436  ** actual file size after the operation may be larger than the requested
28437  ** size).
28438  */
28439  if( pFile->szChunk ){
28440    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
28441  }
28442
28443  rc = robust_ftruncate(pFile->h, (off_t)nByte);
28444  if( rc ){
28445    pFile->lastErrno = errno;
28446    return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28447  }else{
28448#ifndef NDEBUG
28449    /* If we are doing a normal write to a database file (as opposed to
28450    ** doing a hot-journal rollback or a write to some file other than a
28451    ** normal database file) and we truncate the file to zero length,
28452    ** that effectively updates the change counter.  This might happen
28453    ** when restoring a database using the backup API from a zero-length
28454    ** source.
28455    */
28456    if( pFile->inNormalWrite && nByte==0 ){
28457      pFile->transCntrChng = 1;
28458    }
28459#endif
28460
28461    return SQLITE_OK;
28462  }
28463}
28464
28465/*
28466** Determine the current size of a file in bytes
28467*/
28468static int unixFileSize(sqlite3_file *id, i64 *pSize){
28469  int rc;
28470  struct stat buf;
28471  assert( id );
28472  rc = osFstat(((unixFile*)id)->h, &buf);
28473  SimulateIOError( rc=1 );
28474  if( rc!=0 ){
28475    ((unixFile*)id)->lastErrno = errno;
28476    return SQLITE_IOERR_FSTAT;
28477  }
28478  *pSize = buf.st_size;
28479
28480  /* When opening a zero-size database, the findInodeInfo() procedure
28481  ** writes a single byte into that file in order to work around a bug
28482  ** in the OS-X msdos filesystem.  In order to avoid problems with upper
28483  ** layers, we need to report this file size as zero even though it is
28484  ** really 1.   Ticket #3260.
28485  */
28486  if( *pSize==1 ) *pSize = 0;
28487
28488
28489  return SQLITE_OK;
28490}
28491
28492#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28493/*
28494** Handler for proxy-locking file-control verbs.  Defined below in the
28495** proxying locking division.
28496*/
28497static int proxyFileControl(sqlite3_file*,int,void*);
28498#endif
28499
28500/*
28501** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
28502** file-control operation.  Enlarge the database to nBytes in size
28503** (rounded up to the next chunk-size).  If the database is already
28504** nBytes or larger, this routine is a no-op.
28505*/
28506static int fcntlSizeHint(unixFile *pFile, i64 nByte){
28507  if( pFile->szChunk>0 ){
28508    i64 nSize;                    /* Required file size */
28509    struct stat buf;              /* Used to hold return values of fstat() */
28510
28511    if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
28512
28513    nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
28514    if( nSize>(i64)buf.st_size ){
28515
28516#if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
28517      /* The code below is handling the return value of osFallocate()
28518      ** correctly. posix_fallocate() is defined to "returns zero on success,
28519      ** or an error number on  failure". See the manpage for details. */
28520      int err;
28521      do{
28522        err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
28523      }while( err==EINTR );
28524      if( err ) return SQLITE_IOERR_WRITE;
28525#else
28526      /* If the OS does not have posix_fallocate(), fake it. First use
28527      ** ftruncate() to set the file size, then write a single byte to
28528      ** the last byte in each block within the extended region. This
28529      ** is the same technique used by glibc to implement posix_fallocate()
28530      ** on systems that do not have a real fallocate() system call.
28531      */
28532      int nBlk = buf.st_blksize;  /* File-system block size */
28533      i64 iWrite;                 /* Next offset to write to */
28534
28535      if( robust_ftruncate(pFile->h, nSize) ){
28536        pFile->lastErrno = errno;
28537        return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
28538      }
28539      iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
28540      while( iWrite<nSize ){
28541        int nWrite = seekAndWrite(pFile, iWrite, "", 1);
28542        if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
28543        iWrite += nBlk;
28544      }
28545#endif
28546    }
28547  }
28548
28549  return SQLITE_OK;
28550}
28551
28552/*
28553** If *pArg is inititially negative then this is a query.  Set *pArg to
28554** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
28555**
28556** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
28557*/
28558static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
28559  if( *pArg<0 ){
28560    *pArg = (pFile->ctrlFlags & mask)!=0;
28561  }else if( (*pArg)==0 ){
28562    pFile->ctrlFlags &= ~mask;
28563  }else{
28564    pFile->ctrlFlags |= mask;
28565  }
28566}
28567
28568/*
28569** Information and control of an open file handle.
28570*/
28571static int unixFileControl(sqlite3_file *id, int op, void *pArg){
28572  unixFile *pFile = (unixFile*)id;
28573  switch( op ){
28574    case SQLITE_FCNTL_LOCKSTATE: {
28575      *(int*)pArg = pFile->eFileLock;
28576      return SQLITE_OK;
28577    }
28578    case SQLITE_LAST_ERRNO: {
28579      *(int*)pArg = pFile->lastErrno;
28580      return SQLITE_OK;
28581    }
28582    case SQLITE_FCNTL_CHUNK_SIZE: {
28583      pFile->szChunk = *(int *)pArg;
28584      return SQLITE_OK;
28585    }
28586    case SQLITE_FCNTL_SIZE_HINT: {
28587      int rc;
28588      SimulateIOErrorBenign(1);
28589      rc = fcntlSizeHint(pFile, *(i64 *)pArg);
28590      SimulateIOErrorBenign(0);
28591      return rc;
28592    }
28593    case SQLITE_FCNTL_PERSIST_WAL: {
28594      unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
28595      return SQLITE_OK;
28596    }
28597    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
28598      unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
28599      return SQLITE_OK;
28600    }
28601    case SQLITE_FCNTL_VFSNAME: {
28602      *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
28603      return SQLITE_OK;
28604    }
28605#ifndef NDEBUG
28606    /* The pager calls this method to signal that it has done
28607    ** a rollback and that the database is therefore unchanged and
28608    ** it hence it is OK for the transaction change counter to be
28609    ** unchanged.
28610    */
28611    case SQLITE_FCNTL_DB_UNCHANGED: {
28612      ((unixFile*)id)->dbUpdate = 0;
28613      return SQLITE_OK;
28614    }
28615#endif
28616#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28617    case SQLITE_SET_LOCKPROXYFILE:
28618    case SQLITE_GET_LOCKPROXYFILE: {
28619      return proxyFileControl(id,op,pArg);
28620    }
28621#endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
28622  }
28623  return SQLITE_NOTFOUND;
28624}
28625
28626/*
28627** Return the sector size in bytes of the underlying block device for
28628** the specified file. This is almost always 512 bytes, but may be
28629** larger for some devices.
28630**
28631** SQLite code assumes this function cannot fail. It also assumes that
28632** if two files are created in the same file-system directory (i.e.
28633** a database and its journal file) that the sector size will be the
28634** same for both.
28635*/
28636static int unixSectorSize(sqlite3_file *pFile){
28637  (void)pFile;
28638  return SQLITE_DEFAULT_SECTOR_SIZE;
28639}
28640
28641/*
28642** Return the device characteristics for the file.
28643**
28644** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
28645** However, that choice is contraversial since technically the underlying
28646** file system does not always provide powersafe overwrites.  (In other
28647** words, after a power-loss event, parts of the file that were never
28648** written might end up being altered.)  However, non-PSOW behavior is very,
28649** very rare.  And asserting PSOW makes a large reduction in the amount
28650** of required I/O for journaling, since a lot of padding is eliminated.
28651**  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
28652** available to turn it off and URI query parameter available to turn it off.
28653*/
28654static int unixDeviceCharacteristics(sqlite3_file *id){
28655  unixFile *p = (unixFile*)id;
28656  if( p->ctrlFlags & UNIXFILE_PSOW ){
28657    return SQLITE_IOCAP_POWERSAFE_OVERWRITE;
28658  }else{
28659    return 0;
28660  }
28661}
28662
28663#ifndef SQLITE_OMIT_WAL
28664
28665
28666/*
28667** Object used to represent an shared memory buffer.
28668**
28669** When multiple threads all reference the same wal-index, each thread
28670** has its own unixShm object, but they all point to a single instance
28671** of this unixShmNode object.  In other words, each wal-index is opened
28672** only once per process.
28673**
28674** Each unixShmNode object is connected to a single unixInodeInfo object.
28675** We could coalesce this object into unixInodeInfo, but that would mean
28676** every open file that does not use shared memory (in other words, most
28677** open files) would have to carry around this extra information.  So
28678** the unixInodeInfo object contains a pointer to this unixShmNode object
28679** and the unixShmNode object is created only when needed.
28680**
28681** unixMutexHeld() must be true when creating or destroying
28682** this object or while reading or writing the following fields:
28683**
28684**      nRef
28685**
28686** The following fields are read-only after the object is created:
28687**
28688**      fid
28689**      zFilename
28690**
28691** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
28692** unixMutexHeld() is true when reading or writing any other field
28693** in this structure.
28694*/
28695struct unixShmNode {
28696  unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
28697  sqlite3_mutex *mutex;      /* Mutex to access this object */
28698  char *zFilename;           /* Name of the mmapped file */
28699  int h;                     /* Open file descriptor */
28700  int szRegion;              /* Size of shared-memory regions */
28701  u16 nRegion;               /* Size of array apRegion */
28702  u8 isReadonly;             /* True if read-only */
28703  char **apRegion;           /* Array of mapped shared-memory regions */
28704  int nRef;                  /* Number of unixShm objects pointing to this */
28705  unixShm *pFirst;           /* All unixShm objects pointing to this */
28706#ifdef SQLITE_DEBUG
28707  u8 exclMask;               /* Mask of exclusive locks held */
28708  u8 sharedMask;             /* Mask of shared locks held */
28709  u8 nextShmId;              /* Next available unixShm.id value */
28710#endif
28711};
28712
28713/*
28714** Structure used internally by this VFS to record the state of an
28715** open shared memory connection.
28716**
28717** The following fields are initialized when this object is created and
28718** are read-only thereafter:
28719**
28720**    unixShm.pFile
28721**    unixShm.id
28722**
28723** All other fields are read/write.  The unixShm.pFile->mutex must be held
28724** while accessing any read/write fields.
28725*/
28726struct unixShm {
28727  unixShmNode *pShmNode;     /* The underlying unixShmNode object */
28728  unixShm *pNext;            /* Next unixShm with the same unixShmNode */
28729  u8 hasMutex;               /* True if holding the unixShmNode mutex */
28730  u8 id;                     /* Id of this connection within its unixShmNode */
28731  u16 sharedMask;            /* Mask of shared locks held */
28732  u16 exclMask;              /* Mask of exclusive locks held */
28733};
28734
28735/*
28736** Constants used for locking
28737*/
28738#define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
28739#define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
28740
28741/*
28742** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
28743**
28744** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
28745** otherwise.
28746*/
28747static int unixShmSystemLock(
28748  unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
28749  int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
28750  int ofst,              /* First byte of the locking range */
28751  int n                  /* Number of bytes to lock */
28752){
28753  struct flock f;       /* The posix advisory locking structure */
28754  int rc = SQLITE_OK;   /* Result code form fcntl() */
28755
28756  /* Access to the unixShmNode object is serialized by the caller */
28757  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
28758
28759  /* Shared locks never span more than one byte */
28760  assert( n==1 || lockType!=F_RDLCK );
28761
28762  /* Locks are within range */
28763  assert( n>=1 && n<SQLITE_SHM_NLOCK );
28764
28765  if( pShmNode->h>=0 ){
28766    /* Initialize the locking parameters */
28767    memset(&f, 0, sizeof(f));
28768    f.l_type = lockType;
28769    f.l_whence = SEEK_SET;
28770    f.l_start = ofst;
28771    f.l_len = n;
28772
28773    rc = osFcntl(pShmNode->h, F_SETLK, &f);
28774    rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
28775  }
28776
28777  /* Update the global lock state and do debug tracing */
28778#ifdef SQLITE_DEBUG
28779  { u16 mask;
28780  OSTRACE(("SHM-LOCK "));
28781  mask = (1<<(ofst+n)) - (1<<ofst);
28782  if( rc==SQLITE_OK ){
28783    if( lockType==F_UNLCK ){
28784      OSTRACE(("unlock %d ok", ofst));
28785      pShmNode->exclMask &= ~mask;
28786      pShmNode->sharedMask &= ~mask;
28787    }else if( lockType==F_RDLCK ){
28788      OSTRACE(("read-lock %d ok", ofst));
28789      pShmNode->exclMask &= ~mask;
28790      pShmNode->sharedMask |= mask;
28791    }else{
28792      assert( lockType==F_WRLCK );
28793      OSTRACE(("write-lock %d ok", ofst));
28794      pShmNode->exclMask |= mask;
28795      pShmNode->sharedMask &= ~mask;
28796    }
28797  }else{
28798    if( lockType==F_UNLCK ){
28799      OSTRACE(("unlock %d failed", ofst));
28800    }else if( lockType==F_RDLCK ){
28801      OSTRACE(("read-lock failed"));
28802    }else{
28803      assert( lockType==F_WRLCK );
28804      OSTRACE(("write-lock %d failed", ofst));
28805    }
28806  }
28807  OSTRACE((" - afterwards %03x,%03x\n",
28808           pShmNode->sharedMask, pShmNode->exclMask));
28809  }
28810#endif
28811
28812  return rc;
28813}
28814
28815
28816/*
28817** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
28818**
28819** This is not a VFS shared-memory method; it is a utility function called
28820** by VFS shared-memory methods.
28821*/
28822static void unixShmPurge(unixFile *pFd){
28823  unixShmNode *p = pFd->pInode->pShmNode;
28824  assert( unixMutexHeld() );
28825  if( p && p->nRef==0 ){
28826    int i;
28827    assert( p->pInode==pFd->pInode );
28828    sqlite3_mutex_free(p->mutex);
28829    for(i=0; i<p->nRegion; i++){
28830      if( p->h>=0 ){
28831        munmap(p->apRegion[i], p->szRegion);
28832      }else{
28833        sqlite3_free(p->apRegion[i]);
28834      }
28835    }
28836    sqlite3_free(p->apRegion);
28837    if( p->h>=0 ){
28838      robust_close(pFd, p->h, __LINE__);
28839      p->h = -1;
28840    }
28841    p->pInode->pShmNode = 0;
28842    sqlite3_free(p);
28843  }
28844}
28845
28846/*
28847** Open a shared-memory area associated with open database file pDbFd.
28848** This particular implementation uses mmapped files.
28849**
28850** The file used to implement shared-memory is in the same directory
28851** as the open database file and has the same name as the open database
28852** file with the "-shm" suffix added.  For example, if the database file
28853** is "/home/user1/config.db" then the file that is created and mmapped
28854** for shared memory will be called "/home/user1/config.db-shm".
28855**
28856** Another approach to is to use files in /dev/shm or /dev/tmp or an
28857** some other tmpfs mount. But if a file in a different directory
28858** from the database file is used, then differing access permissions
28859** or a chroot() might cause two different processes on the same
28860** database to end up using different files for shared memory -
28861** meaning that their memory would not really be shared - resulting
28862** in database corruption.  Nevertheless, this tmpfs file usage
28863** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
28864** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
28865** option results in an incompatible build of SQLite;  builds of SQLite
28866** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
28867** same database file at the same time, database corruption will likely
28868** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
28869** "unsupported" and may go away in a future SQLite release.
28870**
28871** When opening a new shared-memory file, if no other instances of that
28872** file are currently open, in this process or in other processes, then
28873** the file must be truncated to zero length or have its header cleared.
28874**
28875** If the original database file (pDbFd) is using the "unix-excl" VFS
28876** that means that an exclusive lock is held on the database file and
28877** that no other processes are able to read or write the database.  In
28878** that case, we do not really need shared memory.  No shared memory
28879** file is created.  The shared memory will be simulated with heap memory.
28880*/
28881static int unixOpenSharedMemory(unixFile *pDbFd){
28882  struct unixShm *p = 0;          /* The connection to be opened */
28883  struct unixShmNode *pShmNode;   /* The underlying mmapped file */
28884  int rc;                         /* Result code */
28885  unixInodeInfo *pInode;          /* The inode of fd */
28886  char *zShmFilename;             /* Name of the file used for SHM */
28887  int nShmFilename;               /* Size of the SHM filename in bytes */
28888
28889  /* Allocate space for the new unixShm object. */
28890  p = sqlite3_malloc( sizeof(*p) );
28891  if( p==0 ) return SQLITE_NOMEM;
28892  memset(p, 0, sizeof(*p));
28893  assert( pDbFd->pShm==0 );
28894
28895  /* Check to see if a unixShmNode object already exists. Reuse an existing
28896  ** one if present. Create a new one if necessary.
28897  */
28898  unixEnterMutex();
28899  pInode = pDbFd->pInode;
28900  pShmNode = pInode->pShmNode;
28901  if( pShmNode==0 ){
28902    struct stat sStat;                 /* fstat() info for database file */
28903
28904    /* Call fstat() to figure out the permissions on the database file. If
28905    ** a new *-shm file is created, an attempt will be made to create it
28906    ** with the same permissions.
28907    */
28908    if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
28909      rc = SQLITE_IOERR_FSTAT;
28910      goto shm_open_err;
28911    }
28912
28913#ifdef SQLITE_SHM_DIRECTORY
28914    nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
28915#else
28916    nShmFilename = 6 + (int)strlen(pDbFd->zPath);
28917#endif
28918    pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
28919    if( pShmNode==0 ){
28920      rc = SQLITE_NOMEM;
28921      goto shm_open_err;
28922    }
28923    memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
28924    zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
28925#ifdef SQLITE_SHM_DIRECTORY
28926    sqlite3_snprintf(nShmFilename, zShmFilename,
28927                     SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
28928                     (u32)sStat.st_ino, (u32)sStat.st_dev);
28929#else
28930    sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
28931    sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
28932#endif
28933    pShmNode->h = -1;
28934    pDbFd->pInode->pShmNode = pShmNode;
28935    pShmNode->pInode = pDbFd->pInode;
28936    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
28937    if( pShmNode->mutex==0 ){
28938      rc = SQLITE_NOMEM;
28939      goto shm_open_err;
28940    }
28941
28942    if( pInode->bProcessLock==0 ){
28943      int openFlags = O_RDWR | O_CREAT;
28944      if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
28945        openFlags = O_RDONLY;
28946        pShmNode->isReadonly = 1;
28947      }
28948      pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
28949      if( pShmNode->h<0 ){
28950        rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
28951        goto shm_open_err;
28952      }
28953
28954      /* If this process is running as root, make sure that the SHM file
28955      ** is owned by the same user that owns the original database.  Otherwise,
28956      ** the original owner will not be able to connect. If this process is
28957      ** not root, the following fchown() will fail, but we don't care.  The
28958      ** if(){..} and the UNIXFILE_CHOWN flag are purely to silence compiler
28959      ** warnings.
28960      */
28961      if( osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid)==0 ){
28962        pDbFd->ctrlFlags |= UNIXFILE_CHOWN;
28963      }
28964
28965      /* Check to see if another process is holding the dead-man switch.
28966      ** If not, truncate the file to zero length.
28967      */
28968      rc = SQLITE_OK;
28969      if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
28970        if( robust_ftruncate(pShmNode->h, 0) ){
28971          rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
28972        }
28973      }
28974      if( rc==SQLITE_OK ){
28975        rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
28976      }
28977      if( rc ) goto shm_open_err;
28978    }
28979  }
28980
28981  /* Make the new connection a child of the unixShmNode */
28982  p->pShmNode = pShmNode;
28983#ifdef SQLITE_DEBUG
28984  p->id = pShmNode->nextShmId++;
28985#endif
28986  pShmNode->nRef++;
28987  pDbFd->pShm = p;
28988  unixLeaveMutex();
28989
28990  /* The reference count on pShmNode has already been incremented under
28991  ** the cover of the unixEnterMutex() mutex and the pointer from the
28992  ** new (struct unixShm) object to the pShmNode has been set. All that is
28993  ** left to do is to link the new object into the linked list starting
28994  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
28995  ** mutex.
28996  */
28997  sqlite3_mutex_enter(pShmNode->mutex);
28998  p->pNext = pShmNode->pFirst;
28999  pShmNode->pFirst = p;
29000  sqlite3_mutex_leave(pShmNode->mutex);
29001  return SQLITE_OK;
29002
29003  /* Jump here on any error */
29004shm_open_err:
29005  unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
29006  sqlite3_free(p);
29007  unixLeaveMutex();
29008  return rc;
29009}
29010
29011/*
29012** This function is called to obtain a pointer to region iRegion of the
29013** shared-memory associated with the database file fd. Shared-memory regions
29014** are numbered starting from zero. Each shared-memory region is szRegion
29015** bytes in size.
29016**
29017** If an error occurs, an error code is returned and *pp is set to NULL.
29018**
29019** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
29020** region has not been allocated (by any client, including one running in a
29021** separate process), then *pp is set to NULL and SQLITE_OK returned. If
29022** bExtend is non-zero and the requested shared-memory region has not yet
29023** been allocated, it is allocated by this function.
29024**
29025** If the shared-memory region has already been allocated or is allocated by
29026** this call as described above, then it is mapped into this processes
29027** address space (if it is not already), *pp is set to point to the mapped
29028** memory and SQLITE_OK returned.
29029*/
29030static int unixShmMap(
29031  sqlite3_file *fd,               /* Handle open on database file */
29032  int iRegion,                    /* Region to retrieve */
29033  int szRegion,                   /* Size of regions */
29034  int bExtend,                    /* True to extend file if necessary */
29035  void volatile **pp              /* OUT: Mapped memory */
29036){
29037  unixFile *pDbFd = (unixFile*)fd;
29038  unixShm *p;
29039  unixShmNode *pShmNode;
29040  int rc = SQLITE_OK;
29041
29042  /* If the shared-memory file has not yet been opened, open it now. */
29043  if( pDbFd->pShm==0 ){
29044    rc = unixOpenSharedMemory(pDbFd);
29045    if( rc!=SQLITE_OK ) return rc;
29046  }
29047
29048  p = pDbFd->pShm;
29049  pShmNode = p->pShmNode;
29050  sqlite3_mutex_enter(pShmNode->mutex);
29051  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
29052  assert( pShmNode->pInode==pDbFd->pInode );
29053  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29054  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29055
29056  if( pShmNode->nRegion<=iRegion ){
29057    char **apNew;                      /* New apRegion[] array */
29058    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
29059    struct stat sStat;                 /* Used by fstat() */
29060
29061    pShmNode->szRegion = szRegion;
29062
29063    if( pShmNode->h>=0 ){
29064      /* The requested region is not mapped into this processes address space.
29065      ** Check to see if it has been allocated (i.e. if the wal-index file is
29066      ** large enough to contain the requested region).
29067      */
29068      if( osFstat(pShmNode->h, &sStat) ){
29069        rc = SQLITE_IOERR_SHMSIZE;
29070        goto shmpage_out;
29071      }
29072
29073      if( sStat.st_size<nByte ){
29074        /* The requested memory region does not exist. If bExtend is set to
29075        ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
29076        **
29077        ** Alternatively, if bExtend is true, use ftruncate() to allocate
29078        ** the requested memory region.
29079        */
29080        if( !bExtend ) goto shmpage_out;
29081        if( robust_ftruncate(pShmNode->h, nByte) ){
29082          rc = unixLogError(SQLITE_IOERR_SHMSIZE, "ftruncate",
29083                            pShmNode->zFilename);
29084          goto shmpage_out;
29085        }
29086      }
29087    }
29088
29089    /* Map the requested memory region into this processes address space. */
29090    apNew = (char **)sqlite3_realloc(
29091        pShmNode->apRegion, (iRegion+1)*sizeof(char *)
29092    );
29093    if( !apNew ){
29094      rc = SQLITE_IOERR_NOMEM;
29095      goto shmpage_out;
29096    }
29097    pShmNode->apRegion = apNew;
29098    while(pShmNode->nRegion<=iRegion){
29099      void *pMem;
29100      if( pShmNode->h>=0 ){
29101        pMem = mmap(0, szRegion,
29102            pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
29103            MAP_SHARED, pShmNode->h, pShmNode->nRegion*szRegion
29104        );
29105        if( pMem==MAP_FAILED ){
29106          rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
29107          goto shmpage_out;
29108        }
29109      }else{
29110        pMem = sqlite3_malloc(szRegion);
29111        if( pMem==0 ){
29112          rc = SQLITE_NOMEM;
29113          goto shmpage_out;
29114        }
29115        memset(pMem, 0, szRegion);
29116      }
29117      pShmNode->apRegion[pShmNode->nRegion] = pMem;
29118      pShmNode->nRegion++;
29119    }
29120  }
29121
29122shmpage_out:
29123  if( pShmNode->nRegion>iRegion ){
29124    *pp = pShmNode->apRegion[iRegion];
29125  }else{
29126    *pp = 0;
29127  }
29128  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
29129  sqlite3_mutex_leave(pShmNode->mutex);
29130  return rc;
29131}
29132
29133/*
29134** Change the lock state for a shared-memory segment.
29135**
29136** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
29137** different here than in posix.  In xShmLock(), one can go from unlocked
29138** to shared and back or from unlocked to exclusive and back.  But one may
29139** not go from shared to exclusive or from exclusive to shared.
29140*/
29141static int unixShmLock(
29142  sqlite3_file *fd,          /* Database file holding the shared memory */
29143  int ofst,                  /* First lock to acquire or release */
29144  int n,                     /* Number of locks to acquire or release */
29145  int flags                  /* What to do with the lock */
29146){
29147  unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
29148  unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
29149  unixShm *pX;                          /* For looping over all siblings */
29150  unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
29151  int rc = SQLITE_OK;                   /* Result code */
29152  u16 mask;                             /* Mask of locks to take or release */
29153
29154  assert( pShmNode==pDbFd->pInode->pShmNode );
29155  assert( pShmNode->pInode==pDbFd->pInode );
29156  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
29157  assert( n>=1 );
29158  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
29159       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
29160       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
29161       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
29162  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
29163  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29164  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29165
29166  mask = (1<<(ofst+n)) - (1<<ofst);
29167  assert( n>1 || mask==(1<<ofst) );
29168  sqlite3_mutex_enter(pShmNode->mutex);
29169  if( flags & SQLITE_SHM_UNLOCK ){
29170    u16 allMask = 0; /* Mask of locks held by siblings */
29171
29172    /* See if any siblings hold this same lock */
29173    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29174      if( pX==p ) continue;
29175      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
29176      allMask |= pX->sharedMask;
29177    }
29178
29179    /* Unlock the system-level locks */
29180    if( (mask & allMask)==0 ){
29181      rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
29182    }else{
29183      rc = SQLITE_OK;
29184    }
29185
29186    /* Undo the local locks */
29187    if( rc==SQLITE_OK ){
29188      p->exclMask &= ~mask;
29189      p->sharedMask &= ~mask;
29190    }
29191  }else if( flags & SQLITE_SHM_SHARED ){
29192    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
29193
29194    /* Find out which shared locks are already held by sibling connections.
29195    ** If any sibling already holds an exclusive lock, go ahead and return
29196    ** SQLITE_BUSY.
29197    */
29198    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29199      if( (pX->exclMask & mask)!=0 ){
29200        rc = SQLITE_BUSY;
29201        break;
29202      }
29203      allShared |= pX->sharedMask;
29204    }
29205
29206    /* Get shared locks at the system level, if necessary */
29207    if( rc==SQLITE_OK ){
29208      if( (allShared & mask)==0 ){
29209        rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
29210      }else{
29211        rc = SQLITE_OK;
29212      }
29213    }
29214
29215    /* Get the local shared locks */
29216    if( rc==SQLITE_OK ){
29217      p->sharedMask |= mask;
29218    }
29219  }else{
29220    /* Make sure no sibling connections hold locks that will block this
29221    ** lock.  If any do, return SQLITE_BUSY right away.
29222    */
29223    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29224      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
29225        rc = SQLITE_BUSY;
29226        break;
29227      }
29228    }
29229
29230    /* Get the exclusive locks at the system level.  Then if successful
29231    ** also mark the local connection as being locked.
29232    */
29233    if( rc==SQLITE_OK ){
29234      rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
29235      if( rc==SQLITE_OK ){
29236        assert( (p->sharedMask & mask)==0 );
29237        p->exclMask |= mask;
29238      }
29239    }
29240  }
29241  sqlite3_mutex_leave(pShmNode->mutex);
29242  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
29243           p->id, getpid(), p->sharedMask, p->exclMask));
29244  return rc;
29245}
29246
29247/*
29248** Implement a memory barrier or memory fence on shared memory.
29249**
29250** All loads and stores begun before the barrier must complete before
29251** any load or store begun after the barrier.
29252*/
29253static void unixShmBarrier(
29254  sqlite3_file *fd                /* Database file holding the shared memory */
29255){
29256  UNUSED_PARAMETER(fd);
29257  unixEnterMutex();
29258  unixLeaveMutex();
29259}
29260
29261/*
29262** Close a connection to shared-memory.  Delete the underlying
29263** storage if deleteFlag is true.
29264**
29265** If there is no shared memory associated with the connection then this
29266** routine is a harmless no-op.
29267*/
29268static int unixShmUnmap(
29269  sqlite3_file *fd,               /* The underlying database file */
29270  int deleteFlag                  /* Delete shared-memory if true */
29271){
29272  unixShm *p;                     /* The connection to be closed */
29273  unixShmNode *pShmNode;          /* The underlying shared-memory file */
29274  unixShm **pp;                   /* For looping over sibling connections */
29275  unixFile *pDbFd;                /* The underlying database file */
29276
29277  pDbFd = (unixFile*)fd;
29278  p = pDbFd->pShm;
29279  if( p==0 ) return SQLITE_OK;
29280  pShmNode = p->pShmNode;
29281
29282  assert( pShmNode==pDbFd->pInode->pShmNode );
29283  assert( pShmNode->pInode==pDbFd->pInode );
29284
29285  /* Remove connection p from the set of connections associated
29286  ** with pShmNode */
29287  sqlite3_mutex_enter(pShmNode->mutex);
29288  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
29289  *pp = p->pNext;
29290
29291  /* Free the connection p */
29292  sqlite3_free(p);
29293  pDbFd->pShm = 0;
29294  sqlite3_mutex_leave(pShmNode->mutex);
29295
29296  /* If pShmNode->nRef has reached 0, then close the underlying
29297  ** shared-memory file, too */
29298  unixEnterMutex();
29299  assert( pShmNode->nRef>0 );
29300  pShmNode->nRef--;
29301  if( pShmNode->nRef==0 ){
29302    if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
29303    unixShmPurge(pDbFd);
29304  }
29305  unixLeaveMutex();
29306
29307  return SQLITE_OK;
29308}
29309
29310
29311#else
29312# define unixShmMap     0
29313# define unixShmLock    0
29314# define unixShmBarrier 0
29315# define unixShmUnmap   0
29316#endif /* #ifndef SQLITE_OMIT_WAL */
29317
29318/*
29319** Here ends the implementation of all sqlite3_file methods.
29320**
29321********************** End sqlite3_file Methods *******************************
29322******************************************************************************/
29323
29324/*
29325** This division contains definitions of sqlite3_io_methods objects that
29326** implement various file locking strategies.  It also contains definitions
29327** of "finder" functions.  A finder-function is used to locate the appropriate
29328** sqlite3_io_methods object for a particular database file.  The pAppData
29329** field of the sqlite3_vfs VFS objects are initialized to be pointers to
29330** the correct finder-function for that VFS.
29331**
29332** Most finder functions return a pointer to a fixed sqlite3_io_methods
29333** object.  The only interesting finder-function is autolockIoFinder, which
29334** looks at the filesystem type and tries to guess the best locking
29335** strategy from that.
29336**
29337** For finder-funtion F, two objects are created:
29338**
29339**    (1) The real finder-function named "FImpt()".
29340**
29341**    (2) A constant pointer to this function named just "F".
29342**
29343**
29344** A pointer to the F pointer is used as the pAppData value for VFS
29345** objects.  We have to do this instead of letting pAppData point
29346** directly at the finder-function since C90 rules prevent a void*
29347** from be cast into a function pointer.
29348**
29349**
29350** Each instance of this macro generates two objects:
29351**
29352**   *  A constant sqlite3_io_methods object call METHOD that has locking
29353**      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
29354**
29355**   *  An I/O method finder function called FINDER that returns a pointer
29356**      to the METHOD object in the previous bullet.
29357*/
29358#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
29359static const sqlite3_io_methods METHOD = {                                   \
29360   VERSION,                    /* iVersion */                                \
29361   CLOSE,                      /* xClose */                                  \
29362   unixRead,                   /* xRead */                                   \
29363   unixWrite,                  /* xWrite */                                  \
29364   unixTruncate,               /* xTruncate */                               \
29365   unixSync,                   /* xSync */                                   \
29366   unixFileSize,               /* xFileSize */                               \
29367   LOCK,                       /* xLock */                                   \
29368   UNLOCK,                     /* xUnlock */                                 \
29369   CKLOCK,                     /* xCheckReservedLock */                      \
29370   unixFileControl,            /* xFileControl */                            \
29371   unixSectorSize,             /* xSectorSize */                             \
29372   unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
29373   unixShmMap,                 /* xShmMap */                                 \
29374   unixShmLock,                /* xShmLock */                                \
29375   unixShmBarrier,             /* xShmBarrier */                             \
29376   unixShmUnmap                /* xShmUnmap */                               \
29377};                                                                           \
29378static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
29379  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
29380  return &METHOD;                                                            \
29381}                                                                            \
29382static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
29383    = FINDER##Impl;
29384
29385/*
29386** Here are all of the sqlite3_io_methods objects for each of the
29387** locking strategies.  Functions that return pointers to these methods
29388** are also created.
29389*/
29390IOMETHODS(
29391  posixIoFinder,            /* Finder function name */
29392  posixIoMethods,           /* sqlite3_io_methods object name */
29393  2,                        /* shared memory is enabled */
29394  unixClose,                /* xClose method */
29395  unixLock,                 /* xLock method */
29396  unixUnlock,               /* xUnlock method */
29397  unixCheckReservedLock     /* xCheckReservedLock method */
29398)
29399IOMETHODS(
29400  nolockIoFinder,           /* Finder function name */
29401  nolockIoMethods,          /* sqlite3_io_methods object name */
29402  1,                        /* shared memory is disabled */
29403  nolockClose,              /* xClose method */
29404  nolockLock,               /* xLock method */
29405  nolockUnlock,             /* xUnlock method */
29406  nolockCheckReservedLock   /* xCheckReservedLock method */
29407)
29408IOMETHODS(
29409  dotlockIoFinder,          /* Finder function name */
29410  dotlockIoMethods,         /* sqlite3_io_methods object name */
29411  1,                        /* shared memory is disabled */
29412  dotlockClose,             /* xClose method */
29413  dotlockLock,              /* xLock method */
29414  dotlockUnlock,            /* xUnlock method */
29415  dotlockCheckReservedLock  /* xCheckReservedLock method */
29416)
29417
29418#if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
29419IOMETHODS(
29420  flockIoFinder,            /* Finder function name */
29421  flockIoMethods,           /* sqlite3_io_methods object name */
29422  1,                        /* shared memory is disabled */
29423  flockClose,               /* xClose method */
29424  flockLock,                /* xLock method */
29425  flockUnlock,              /* xUnlock method */
29426  flockCheckReservedLock    /* xCheckReservedLock method */
29427)
29428#endif
29429
29430#if OS_VXWORKS
29431IOMETHODS(
29432  semIoFinder,              /* Finder function name */
29433  semIoMethods,             /* sqlite3_io_methods object name */
29434  1,                        /* shared memory is disabled */
29435  semClose,                 /* xClose method */
29436  semLock,                  /* xLock method */
29437  semUnlock,                /* xUnlock method */
29438  semCheckReservedLock      /* xCheckReservedLock method */
29439)
29440#endif
29441
29442#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29443IOMETHODS(
29444  afpIoFinder,              /* Finder function name */
29445  afpIoMethods,             /* sqlite3_io_methods object name */
29446  1,                        /* shared memory is disabled */
29447  afpClose,                 /* xClose method */
29448  afpLock,                  /* xLock method */
29449  afpUnlock,                /* xUnlock method */
29450  afpCheckReservedLock      /* xCheckReservedLock method */
29451)
29452#endif
29453
29454/*
29455** The proxy locking method is a "super-method" in the sense that it
29456** opens secondary file descriptors for the conch and lock files and
29457** it uses proxy, dot-file, AFP, and flock() locking methods on those
29458** secondary files.  For this reason, the division that implements
29459** proxy locking is located much further down in the file.  But we need
29460** to go ahead and define the sqlite3_io_methods and finder function
29461** for proxy locking here.  So we forward declare the I/O methods.
29462*/
29463#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29464static int proxyClose(sqlite3_file*);
29465static int proxyLock(sqlite3_file*, int);
29466static int proxyUnlock(sqlite3_file*, int);
29467static int proxyCheckReservedLock(sqlite3_file*, int*);
29468IOMETHODS(
29469  proxyIoFinder,            /* Finder function name */
29470  proxyIoMethods,           /* sqlite3_io_methods object name */
29471  1,                        /* shared memory is disabled */
29472  proxyClose,               /* xClose method */
29473  proxyLock,                /* xLock method */
29474  proxyUnlock,              /* xUnlock method */
29475  proxyCheckReservedLock    /* xCheckReservedLock method */
29476)
29477#endif
29478
29479/* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
29480#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29481IOMETHODS(
29482  nfsIoFinder,               /* Finder function name */
29483  nfsIoMethods,              /* sqlite3_io_methods object name */
29484  1,                         /* shared memory is disabled */
29485  unixClose,                 /* xClose method */
29486  unixLock,                  /* xLock method */
29487  nfsUnlock,                 /* xUnlock method */
29488  unixCheckReservedLock      /* xCheckReservedLock method */
29489)
29490#endif
29491
29492#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29493/*
29494** This "finder" function attempts to determine the best locking strategy
29495** for the database file "filePath".  It then returns the sqlite3_io_methods
29496** object that implements that strategy.
29497**
29498** This is for MacOSX only.
29499*/
29500static const sqlite3_io_methods *autolockIoFinderImpl(
29501  const char *filePath,    /* name of the database file */
29502  unixFile *pNew           /* open file object for the database file */
29503){
29504  static const struct Mapping {
29505    const char *zFilesystem;              /* Filesystem type name */
29506    const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
29507  } aMap[] = {
29508    { "hfs",    &posixIoMethods },
29509    { "ufs",    &posixIoMethods },
29510    { "afpfs",  &afpIoMethods },
29511    { "smbfs",  &afpIoMethods },
29512    { "webdav", &nolockIoMethods },
29513    { 0, 0 }
29514  };
29515  int i;
29516  struct statfs fsInfo;
29517  struct flock lockInfo;
29518
29519  if( !filePath ){
29520    /* If filePath==NULL that means we are dealing with a transient file
29521    ** that does not need to be locked. */
29522    return &nolockIoMethods;
29523  }
29524  if( statfs(filePath, &fsInfo) != -1 ){
29525    if( fsInfo.f_flags & MNT_RDONLY ){
29526      return &nolockIoMethods;
29527    }
29528    for(i=0; aMap[i].zFilesystem; i++){
29529      if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
29530        return aMap[i].pMethods;
29531      }
29532    }
29533  }
29534
29535  /* Default case. Handles, amongst others, "nfs".
29536  ** Test byte-range lock using fcntl(). If the call succeeds,
29537  ** assume that the file-system supports POSIX style locks.
29538  */
29539  lockInfo.l_len = 1;
29540  lockInfo.l_start = 0;
29541  lockInfo.l_whence = SEEK_SET;
29542  lockInfo.l_type = F_RDLCK;
29543  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29544    if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
29545      return &nfsIoMethods;
29546    } else {
29547      return &posixIoMethods;
29548    }
29549  }else{
29550    return &dotlockIoMethods;
29551  }
29552}
29553static const sqlite3_io_methods
29554  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29555
29556#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
29557
29558#if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
29559/*
29560** This "finder" function attempts to determine the best locking strategy
29561** for the database file "filePath".  It then returns the sqlite3_io_methods
29562** object that implements that strategy.
29563**
29564** This is for VXWorks only.
29565*/
29566static const sqlite3_io_methods *autolockIoFinderImpl(
29567  const char *filePath,    /* name of the database file */
29568  unixFile *pNew           /* the open file object */
29569){
29570  struct flock lockInfo;
29571
29572  if( !filePath ){
29573    /* If filePath==NULL that means we are dealing with a transient file
29574    ** that does not need to be locked. */
29575    return &nolockIoMethods;
29576  }
29577
29578  /* Test if fcntl() is supported and use POSIX style locks.
29579  ** Otherwise fall back to the named semaphore method.
29580  */
29581  lockInfo.l_len = 1;
29582  lockInfo.l_start = 0;
29583  lockInfo.l_whence = SEEK_SET;
29584  lockInfo.l_type = F_RDLCK;
29585  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
29586    return &posixIoMethods;
29587  }else{
29588    return &semIoMethods;
29589  }
29590}
29591static const sqlite3_io_methods
29592  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
29593
29594#endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
29595
29596/*
29597** An abstract type for a pointer to a IO method finder function:
29598*/
29599typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
29600
29601
29602/****************************************************************************
29603**************************** sqlite3_vfs methods ****************************
29604**
29605** This division contains the implementation of methods on the
29606** sqlite3_vfs object.
29607*/
29608
29609/*
29610** Initialize the contents of the unixFile structure pointed to by pId.
29611*/
29612static int fillInUnixFile(
29613  sqlite3_vfs *pVfs,      /* Pointer to vfs object */
29614  int h,                  /* Open file descriptor of file being opened */
29615  sqlite3_file *pId,      /* Write to the unixFile structure here */
29616  const char *zFilename,  /* Name of the file being opened */
29617  int ctrlFlags           /* Zero or more UNIXFILE_* values */
29618){
29619  const sqlite3_io_methods *pLockingStyle;
29620  unixFile *pNew = (unixFile *)pId;
29621  int rc = SQLITE_OK;
29622
29623  assert( pNew->pInode==NULL );
29624
29625  /* Usually the path zFilename should not be a relative pathname. The
29626  ** exception is when opening the proxy "conch" file in builds that
29627  ** include the special Apple locking styles.
29628  */
29629#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29630  assert( zFilename==0 || zFilename[0]=='/'
29631    || pVfs->pAppData==(void*)&autolockIoFinder );
29632#else
29633  assert( zFilename==0 || zFilename[0]=='/' );
29634#endif
29635
29636  /* No locking occurs in temporary files */
29637  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
29638
29639  OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
29640  pNew->h = h;
29641  pNew->pVfs = pVfs;
29642  pNew->zPath = zFilename;
29643  pNew->ctrlFlags = (u8)ctrlFlags;
29644  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
29645                           "psow", SQLITE_POWERSAFE_OVERWRITE) ){
29646    pNew->ctrlFlags |= UNIXFILE_PSOW;
29647  }
29648  if( memcmp(pVfs->zName,"unix-excl",10)==0 ){
29649    pNew->ctrlFlags |= UNIXFILE_EXCL;
29650  }
29651
29652#if OS_VXWORKS
29653  pNew->pId = vxworksFindFileId(zFilename);
29654  if( pNew->pId==0 ){
29655    ctrlFlags |= UNIXFILE_NOLOCK;
29656    rc = SQLITE_NOMEM;
29657  }
29658#endif
29659
29660  if( ctrlFlags & UNIXFILE_NOLOCK ){
29661    pLockingStyle = &nolockIoMethods;
29662  }else{
29663    pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
29664#if SQLITE_ENABLE_LOCKING_STYLE
29665    /* Cache zFilename in the locking context (AFP and dotlock override) for
29666    ** proxyLock activation is possible (remote proxy is based on db name)
29667    ** zFilename remains valid until file is closed, to support */
29668    pNew->lockingContext = (void*)zFilename;
29669#endif
29670  }
29671
29672  if( pLockingStyle == &posixIoMethods
29673#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29674    || pLockingStyle == &nfsIoMethods
29675#endif
29676  ){
29677    unixEnterMutex();
29678    rc = findInodeInfo(pNew, &pNew->pInode);
29679    if( rc!=SQLITE_OK ){
29680      /* If an error occured in findInodeInfo(), close the file descriptor
29681      ** immediately, before releasing the mutex. findInodeInfo() may fail
29682      ** in two scenarios:
29683      **
29684      **   (a) A call to fstat() failed.
29685      **   (b) A malloc failed.
29686      **
29687      ** Scenario (b) may only occur if the process is holding no other
29688      ** file descriptors open on the same file. If there were other file
29689      ** descriptors on this file, then no malloc would be required by
29690      ** findInodeInfo(). If this is the case, it is quite safe to close
29691      ** handle h - as it is guaranteed that no posix locks will be released
29692      ** by doing so.
29693      **
29694      ** If scenario (a) caused the error then things are not so safe. The
29695      ** implicit assumption here is that if fstat() fails, things are in
29696      ** such bad shape that dropping a lock or two doesn't matter much.
29697      */
29698      robust_close(pNew, h, __LINE__);
29699      h = -1;
29700    }
29701    unixLeaveMutex();
29702  }
29703
29704#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29705  else if( pLockingStyle == &afpIoMethods ){
29706    /* AFP locking uses the file path so it needs to be included in
29707    ** the afpLockingContext.
29708    */
29709    afpLockingContext *pCtx;
29710    pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
29711    if( pCtx==0 ){
29712      rc = SQLITE_NOMEM;
29713    }else{
29714      /* NB: zFilename exists and remains valid until the file is closed
29715      ** according to requirement F11141.  So we do not need to make a
29716      ** copy of the filename. */
29717      pCtx->dbPath = zFilename;
29718      pCtx->reserved = 0;
29719      srandomdev();
29720      unixEnterMutex();
29721      rc = findInodeInfo(pNew, &pNew->pInode);
29722      if( rc!=SQLITE_OK ){
29723        sqlite3_free(pNew->lockingContext);
29724        robust_close(pNew, h, __LINE__);
29725        h = -1;
29726      }
29727      unixLeaveMutex();
29728    }
29729  }
29730#endif
29731
29732  else if( pLockingStyle == &dotlockIoMethods ){
29733    /* Dotfile locking uses the file path so it needs to be included in
29734    ** the dotlockLockingContext
29735    */
29736    char *zLockFile;
29737    int nFilename;
29738    assert( zFilename!=0 );
29739    nFilename = (int)strlen(zFilename) + 6;
29740    zLockFile = (char *)sqlite3_malloc(nFilename);
29741    if( zLockFile==0 ){
29742      rc = SQLITE_NOMEM;
29743    }else{
29744      sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
29745    }
29746    pNew->lockingContext = zLockFile;
29747  }
29748
29749#if OS_VXWORKS
29750  else if( pLockingStyle == &semIoMethods ){
29751    /* Named semaphore locking uses the file path so it needs to be
29752    ** included in the semLockingContext
29753    */
29754    unixEnterMutex();
29755    rc = findInodeInfo(pNew, &pNew->pInode);
29756    if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
29757      char *zSemName = pNew->pInode->aSemName;
29758      int n;
29759      sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
29760                       pNew->pId->zCanonicalName);
29761      for( n=1; zSemName[n]; n++ )
29762        if( zSemName[n]=='/' ) zSemName[n] = '_';
29763      pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
29764      if( pNew->pInode->pSem == SEM_FAILED ){
29765        rc = SQLITE_NOMEM;
29766        pNew->pInode->aSemName[0] = '\0';
29767      }
29768    }
29769    unixLeaveMutex();
29770  }
29771#endif
29772
29773  pNew->lastErrno = 0;
29774#if OS_VXWORKS
29775  if( rc!=SQLITE_OK ){
29776    if( h>=0 ) robust_close(pNew, h, __LINE__);
29777    h = -1;
29778    osUnlink(zFilename);
29779    isDelete = 0;
29780  }
29781  if( isDelete ) pNew->ctrlFlags |= UNIXFILE_DELETE;
29782#endif
29783  if( rc!=SQLITE_OK ){
29784    if( h>=0 ) robust_close(pNew, h, __LINE__);
29785  }else{
29786    pNew->pMethod = pLockingStyle;
29787    OpenCounter(+1);
29788  }
29789  return rc;
29790}
29791
29792/*
29793** Return the name of a directory in which to put temporary files.
29794** If no suitable temporary file directory can be found, return NULL.
29795*/
29796static const char *unixTempFileDir(void){
29797  static const char *azDirs[] = {
29798     0,
29799     0,
29800     "/var/tmp",
29801     "/usr/tmp",
29802     "/tmp",
29803     0        /* List terminator */
29804  };
29805  unsigned int i;
29806  struct stat buf;
29807  const char *zDir = 0;
29808
29809  azDirs[0] = sqlite3_temp_directory;
29810  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
29811  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
29812    if( zDir==0 ) continue;
29813    if( osStat(zDir, &buf) ) continue;
29814    if( !S_ISDIR(buf.st_mode) ) continue;
29815    if( osAccess(zDir, 07) ) continue;
29816    break;
29817  }
29818  return zDir;
29819}
29820
29821/*
29822** Create a temporary file name in zBuf.  zBuf must be allocated
29823** by the calling process and must be big enough to hold at least
29824** pVfs->mxPathname bytes.
29825*/
29826static int unixGetTempname(int nBuf, char *zBuf){
29827  static const unsigned char zChars[] =
29828    "abcdefghijklmnopqrstuvwxyz"
29829    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
29830    "0123456789";
29831  unsigned int i, j;
29832  const char *zDir;
29833
29834  /* It's odd to simulate an io-error here, but really this is just
29835  ** using the io-error infrastructure to test that SQLite handles this
29836  ** function failing.
29837  */
29838  SimulateIOError( return SQLITE_IOERR );
29839
29840  zDir = unixTempFileDir();
29841  if( zDir==0 ) zDir = ".";
29842
29843  /* Check that the output buffer is large enough for the temporary file
29844  ** name. If it is not, return SQLITE_ERROR.
29845  */
29846  if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
29847    return SQLITE_ERROR;
29848  }
29849
29850  do{
29851    sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
29852    j = (int)strlen(zBuf);
29853    sqlite3_randomness(15, &zBuf[j]);
29854    for(i=0; i<15; i++, j++){
29855      zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29856    }
29857    zBuf[j] = 0;
29858    zBuf[j+1] = 0;
29859  }while( osAccess(zBuf,0)==0 );
29860  return SQLITE_OK;
29861}
29862
29863#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29864/*
29865** Routine to transform a unixFile into a proxy-locking unixFile.
29866** Implementation in the proxy-lock division, but used by unixOpen()
29867** if SQLITE_PREFER_PROXY_LOCKING is defined.
29868*/
29869static int proxyTransformUnixFile(unixFile*, const char*);
29870#endif
29871
29872/*
29873** Search for an unused file descriptor that was opened on the database
29874** file (not a journal or master-journal file) identified by pathname
29875** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
29876** argument to this function.
29877**
29878** Such a file descriptor may exist if a database connection was closed
29879** but the associated file descriptor could not be closed because some
29880** other file descriptor open on the same file is holding a file-lock.
29881** Refer to comments in the unixClose() function and the lengthy comment
29882** describing "Posix Advisory Locking" at the start of this file for
29883** further details. Also, ticket #4018.
29884**
29885** If a suitable file descriptor is found, then it is returned. If no
29886** such file descriptor is located, -1 is returned.
29887*/
29888static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
29889  UnixUnusedFd *pUnused = 0;
29890
29891  /* Do not search for an unused file descriptor on vxworks. Not because
29892  ** vxworks would not benefit from the change (it might, we're not sure),
29893  ** but because no way to test it is currently available. It is better
29894  ** not to risk breaking vxworks support for the sake of such an obscure
29895  ** feature.  */
29896#if !OS_VXWORKS
29897  struct stat sStat;                   /* Results of stat() call */
29898
29899  /* A stat() call may fail for various reasons. If this happens, it is
29900  ** almost certain that an open() call on the same path will also fail.
29901  ** For this reason, if an error occurs in the stat() call here, it is
29902  ** ignored and -1 is returned. The caller will try to open a new file
29903  ** descriptor on the same path, fail, and return an error to SQLite.
29904  **
29905  ** Even if a subsequent open() call does succeed, the consequences of
29906  ** not searching for a resusable file descriptor are not dire.  */
29907  if( 0==osStat(zPath, &sStat) ){
29908    unixInodeInfo *pInode;
29909
29910    unixEnterMutex();
29911    pInode = inodeList;
29912    while( pInode && (pInode->fileId.dev!=sStat.st_dev
29913                     || pInode->fileId.ino!=sStat.st_ino) ){
29914       pInode = pInode->pNext;
29915    }
29916    if( pInode ){
29917      UnixUnusedFd **pp;
29918      for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
29919      pUnused = *pp;
29920      if( pUnused ){
29921        *pp = pUnused->pNext;
29922      }
29923    }
29924    unixLeaveMutex();
29925  }
29926#endif    /* if !OS_VXWORKS */
29927  return pUnused;
29928}
29929
29930/*
29931** This function is called by unixOpen() to determine the unix permissions
29932** to create new files with. If no error occurs, then SQLITE_OK is returned
29933** and a value suitable for passing as the third argument to open(2) is
29934** written to *pMode. If an IO error occurs, an SQLite error code is
29935** returned and the value of *pMode is not modified.
29936**
29937** In most cases cases, this routine sets *pMode to 0, which will become
29938** an indication to robust_open() to create the file using
29939** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
29940** But if the file being opened is a WAL or regular journal file, then
29941** this function queries the file-system for the permissions on the
29942** corresponding database file and sets *pMode to this value. Whenever
29943** possible, WAL and journal files are created using the same permissions
29944** as the associated database file.
29945**
29946** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
29947** original filename is unavailable.  But 8_3_NAMES is only used for
29948** FAT filesystems and permissions do not matter there, so just use
29949** the default permissions.
29950*/
29951static int findCreateFileMode(
29952  const char *zPath,              /* Path of file (possibly) being created */
29953  int flags,                      /* Flags passed as 4th argument to xOpen() */
29954  mode_t *pMode,                  /* OUT: Permissions to open file with */
29955  uid_t *pUid,                    /* OUT: uid to set on the file */
29956  gid_t *pGid                     /* OUT: gid to set on the file */
29957){
29958  int rc = SQLITE_OK;             /* Return Code */
29959  *pMode = 0;
29960  *pUid = 0;
29961  *pGid = 0;
29962  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
29963    char zDb[MAX_PATHNAME+1];     /* Database file path */
29964    int nDb;                      /* Number of valid bytes in zDb */
29965    struct stat sStat;            /* Output of stat() on database file */
29966
29967    /* zPath is a path to a WAL or journal file. The following block derives
29968    ** the path to the associated database file from zPath. This block handles
29969    ** the following naming conventions:
29970    **
29971    **   "<path to db>-journal"
29972    **   "<path to db>-wal"
29973    **   "<path to db>-journalNN"
29974    **   "<path to db>-walNN"
29975    **
29976    ** where NN is a decimal number. The NN naming schemes are
29977    ** used by the test_multiplex.c module.
29978    */
29979    nDb = sqlite3Strlen30(zPath) - 1;
29980#ifdef SQLITE_ENABLE_8_3_NAMES
29981    while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
29982    if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
29983#else
29984    while( zPath[nDb]!='-' ){
29985      assert( nDb>0 );
29986      assert( zPath[nDb]!='\n' );
29987      nDb--;
29988    }
29989#endif
29990    memcpy(zDb, zPath, nDb);
29991    zDb[nDb] = '\0';
29992
29993    if( 0==osStat(zDb, &sStat) ){
29994      *pMode = sStat.st_mode & 0777;
29995      *pUid = sStat.st_uid;
29996      *pGid = sStat.st_gid;
29997    }else{
29998      rc = SQLITE_IOERR_FSTAT;
29999    }
30000  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
30001    *pMode = 0600;
30002  }
30003  return rc;
30004}
30005
30006/*
30007** Open the file zPath.
30008**
30009** Previously, the SQLite OS layer used three functions in place of this
30010** one:
30011**
30012**     sqlite3OsOpenReadWrite();
30013**     sqlite3OsOpenReadOnly();
30014**     sqlite3OsOpenExclusive();
30015**
30016** These calls correspond to the following combinations of flags:
30017**
30018**     ReadWrite() ->     (READWRITE | CREATE)
30019**     ReadOnly()  ->     (READONLY)
30020**     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
30021**
30022** The old OpenExclusive() accepted a boolean argument - "delFlag". If
30023** true, the file was configured to be automatically deleted when the
30024** file handle closed. To achieve the same effect using this new
30025** interface, add the DELETEONCLOSE flag to those specified above for
30026** OpenExclusive().
30027*/
30028static int unixOpen(
30029  sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
30030  const char *zPath,           /* Pathname of file to be opened */
30031  sqlite3_file *pFile,         /* The file descriptor to be filled in */
30032  int flags,                   /* Input flags to control the opening */
30033  int *pOutFlags               /* Output flags returned to SQLite core */
30034){
30035  unixFile *p = (unixFile *)pFile;
30036  int fd = -1;                   /* File descriptor returned by open() */
30037  int openFlags = 0;             /* Flags to pass to open() */
30038  int eType = flags&0xFFFFFF00;  /* Type of file to open */
30039  int noLock;                    /* True to omit locking primitives */
30040  int rc = SQLITE_OK;            /* Function Return Code */
30041  int ctrlFlags = 0;             /* UNIXFILE_* flags */
30042
30043  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
30044  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
30045  int isCreate     = (flags & SQLITE_OPEN_CREATE);
30046  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
30047  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
30048#if SQLITE_ENABLE_LOCKING_STYLE
30049  int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
30050#endif
30051#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30052  struct statfs fsInfo;
30053#endif
30054
30055  /* If creating a master or main-file journal, this function will open
30056  ** a file-descriptor on the directory too. The first time unixSync()
30057  ** is called the directory file descriptor will be fsync()ed and close()d.
30058  */
30059  int syncDir = (isCreate && (
30060        eType==SQLITE_OPEN_MASTER_JOURNAL
30061     || eType==SQLITE_OPEN_MAIN_JOURNAL
30062     || eType==SQLITE_OPEN_WAL
30063  ));
30064
30065  /* If argument zPath is a NULL pointer, this function is required to open
30066  ** a temporary file. Use this buffer to store the file name in.
30067  */
30068  char zTmpname[MAX_PATHNAME+2];
30069  const char *zName = zPath;
30070
30071  /* Check the following statements are true:
30072  **
30073  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
30074  **   (b) if CREATE is set, then READWRITE must also be set, and
30075  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
30076  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
30077  */
30078  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
30079  assert(isCreate==0 || isReadWrite);
30080  assert(isExclusive==0 || isCreate);
30081  assert(isDelete==0 || isCreate);
30082
30083  /* The main DB, main journal, WAL file and master journal are never
30084  ** automatically deleted. Nor are they ever temporary files.  */
30085  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
30086  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
30087  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
30088  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
30089
30090  /* Assert that the upper layer has set one of the "file-type" flags. */
30091  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
30092       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
30093       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
30094       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
30095  );
30096
30097  memset(p, 0, sizeof(unixFile));
30098
30099  if( eType==SQLITE_OPEN_MAIN_DB ){
30100    UnixUnusedFd *pUnused;
30101    pUnused = findReusableFd(zName, flags);
30102    if( pUnused ){
30103      fd = pUnused->fd;
30104    }else{
30105      pUnused = sqlite3_malloc(sizeof(*pUnused));
30106      if( !pUnused ){
30107        return SQLITE_NOMEM;
30108      }
30109    }
30110    p->pUnused = pUnused;
30111
30112    /* Database filenames are double-zero terminated if they are not
30113    ** URIs with parameters.  Hence, they can always be passed into
30114    ** sqlite3_uri_parameter(). */
30115    assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
30116
30117  }else if( !zName ){
30118    /* If zName is NULL, the upper layer is requesting a temp file. */
30119    assert(isDelete && !syncDir);
30120    rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
30121    if( rc!=SQLITE_OK ){
30122      return rc;
30123    }
30124    zName = zTmpname;
30125
30126    /* Generated temporary filenames are always double-zero terminated
30127    ** for use by sqlite3_uri_parameter(). */
30128    assert( zName[strlen(zName)+1]==0 );
30129  }
30130
30131  /* Determine the value of the flags parameter passed to POSIX function
30132  ** open(). These must be calculated even if open() is not called, as
30133  ** they may be stored as part of the file handle and used by the
30134  ** 'conch file' locking functions later on.  */
30135  if( isReadonly )  openFlags |= O_RDONLY;
30136  if( isReadWrite ) openFlags |= O_RDWR;
30137  if( isCreate )    openFlags |= O_CREAT;
30138  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
30139  openFlags |= (O_LARGEFILE|O_BINARY);
30140
30141  if( fd<0 ){
30142    mode_t openMode;              /* Permissions to create file with */
30143    uid_t uid;                    /* Userid for the file */
30144    gid_t gid;                    /* Groupid for the file */
30145    rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
30146    if( rc!=SQLITE_OK ){
30147      assert( !p->pUnused );
30148      assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
30149      return rc;
30150    }
30151    fd = robust_open(zName, openFlags, openMode);
30152    OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
30153    if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
30154      /* Failed to open the file for read/write access. Try read-only. */
30155      flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
30156      openFlags &= ~(O_RDWR|O_CREAT);
30157      flags |= SQLITE_OPEN_READONLY;
30158      openFlags |= O_RDONLY;
30159      isReadonly = 1;
30160      fd = robust_open(zName, openFlags, openMode);
30161    }
30162    if( fd<0 ){
30163      rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
30164      goto open_finished;
30165    }
30166
30167    /* If this process is running as root and if creating a new rollback
30168    ** journal or WAL file, set the ownership of the journal or WAL to be
30169    ** the same as the original database.  If we are not running as root,
30170    ** then the fchown() call will fail, but that's ok.  The "if(){}" and
30171    ** the setting of the UNIXFILE_CHOWN flag are purely to silence compiler
30172    ** warnings from gcc.
30173    */
30174    if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30175      if( osFchown(fd, uid, gid)==0 ){ p->ctrlFlags |= UNIXFILE_CHOWN; }
30176    }
30177  }
30178  assert( fd>=0 );
30179  if( pOutFlags ){
30180    *pOutFlags = flags;
30181  }
30182
30183  if( p->pUnused ){
30184    p->pUnused->fd = fd;
30185    p->pUnused->flags = flags;
30186  }
30187
30188  if( isDelete ){
30189#if OS_VXWORKS
30190    zPath = zName;
30191#else
30192    osUnlink(zName);
30193#endif
30194  }
30195#if SQLITE_ENABLE_LOCKING_STYLE
30196  else{
30197    p->openFlags = openFlags;
30198  }
30199#endif
30200
30201#ifdef FD_CLOEXEC
30202  osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
30203#endif
30204
30205  noLock = eType!=SQLITE_OPEN_MAIN_DB;
30206
30207
30208#if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
30209  if( fstatfs(fd, &fsInfo) == -1 ){
30210    ((unixFile*)pFile)->lastErrno = errno;
30211    robust_close(p, fd, __LINE__);
30212    return SQLITE_IOERR_ACCESS;
30213  }
30214  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
30215    ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
30216  }
30217#endif
30218
30219  /* Set up appropriate ctrlFlags */
30220  if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
30221  if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
30222  if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
30223  if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
30224  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
30225
30226#if SQLITE_ENABLE_LOCKING_STYLE
30227#if SQLITE_PREFER_PROXY_LOCKING
30228  isAutoProxy = 1;
30229#endif
30230  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
30231    char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
30232    int useProxy = 0;
30233
30234    /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
30235    ** never use proxy, NULL means use proxy for non-local files only.  */
30236    if( envforce!=NULL ){
30237      useProxy = atoi(envforce)>0;
30238    }else{
30239      if( statfs(zPath, &fsInfo) == -1 ){
30240        /* In theory, the close(fd) call is sub-optimal. If the file opened
30241        ** with fd is a database file, and there are other connections open
30242        ** on that file that are currently holding advisory locks on it,
30243        ** then the call to close() will cancel those locks. In practice,
30244        ** we're assuming that statfs() doesn't fail very often. At least
30245        ** not while other file descriptors opened by the same process on
30246        ** the same file are working.  */
30247        p->lastErrno = errno;
30248        robust_close(p, fd, __LINE__);
30249        rc = SQLITE_IOERR_ACCESS;
30250        goto open_finished;
30251      }
30252      useProxy = !(fsInfo.f_flags&MNT_LOCAL);
30253    }
30254    if( useProxy ){
30255      rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30256      if( rc==SQLITE_OK ){
30257        rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
30258        if( rc!=SQLITE_OK ){
30259          /* Use unixClose to clean up the resources added in fillInUnixFile
30260          ** and clear all the structure's references.  Specifically,
30261          ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
30262          */
30263          unixClose(pFile);
30264          return rc;
30265        }
30266      }
30267      goto open_finished;
30268    }
30269  }
30270#endif
30271
30272  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
30273
30274open_finished:
30275  if( rc!=SQLITE_OK ){
30276    sqlite3_free(p->pUnused);
30277  }
30278  return rc;
30279}
30280
30281
30282/*
30283** Delete the file at zPath. If the dirSync argument is true, fsync()
30284** the directory after deleting the file.
30285*/
30286static int unixDelete(
30287  sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
30288  const char *zPath,        /* Name of file to be deleted */
30289  int dirSync               /* If true, fsync() directory after deleting file */
30290){
30291  int rc = SQLITE_OK;
30292  UNUSED_PARAMETER(NotUsed);
30293  SimulateIOError(return SQLITE_IOERR_DELETE);
30294  if( osUnlink(zPath)==(-1) && errno!=ENOENT ){
30295    return unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
30296  }
30297#ifndef SQLITE_DISABLE_DIRSYNC
30298  if( (dirSync & 1)!=0 ){
30299    int fd;
30300    rc = osOpenDirectory(zPath, &fd);
30301    if( rc==SQLITE_OK ){
30302#if OS_VXWORKS
30303      if( fsync(fd)==-1 )
30304#else
30305      if( fsync(fd) )
30306#endif
30307      {
30308        rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
30309      }
30310      robust_close(0, fd, __LINE__);
30311    }else if( rc==SQLITE_CANTOPEN ){
30312      rc = SQLITE_OK;
30313    }
30314  }
30315#endif
30316  return rc;
30317}
30318
30319/*
30320** Test the existance of or access permissions of file zPath. The
30321** test performed depends on the value of flags:
30322**
30323**     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
30324**     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
30325**     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
30326**
30327** Otherwise return 0.
30328*/
30329static int unixAccess(
30330  sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
30331  const char *zPath,      /* Path of the file to examine */
30332  int flags,              /* What do we want to learn about the zPath file? */
30333  int *pResOut            /* Write result boolean here */
30334){
30335  int amode = 0;
30336  UNUSED_PARAMETER(NotUsed);
30337  SimulateIOError( return SQLITE_IOERR_ACCESS; );
30338  switch( flags ){
30339    case SQLITE_ACCESS_EXISTS:
30340      amode = F_OK;
30341      break;
30342    case SQLITE_ACCESS_READWRITE:
30343      amode = W_OK|R_OK;
30344      break;
30345    case SQLITE_ACCESS_READ:
30346      amode = R_OK;
30347      break;
30348
30349    default:
30350      assert(!"Invalid flags argument");
30351  }
30352  *pResOut = (osAccess(zPath, amode)==0);
30353  if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
30354    struct stat buf;
30355    if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
30356      *pResOut = 0;
30357    }
30358  }
30359  return SQLITE_OK;
30360}
30361
30362
30363/*
30364** Turn a relative pathname into a full pathname. The relative path
30365** is stored as a nul-terminated string in the buffer pointed to by
30366** zPath.
30367**
30368** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
30369** (in this case, MAX_PATHNAME bytes). The full-path is written to
30370** this buffer before returning.
30371*/
30372static int unixFullPathname(
30373  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
30374  const char *zPath,            /* Possibly relative input path */
30375  int nOut,                     /* Size of output buffer in bytes */
30376  char *zOut                    /* Output buffer */
30377){
30378
30379  /* It's odd to simulate an io-error here, but really this is just
30380  ** using the io-error infrastructure to test that SQLite handles this
30381  ** function failing. This function could fail if, for example, the
30382  ** current working directory has been unlinked.
30383  */
30384  SimulateIOError( return SQLITE_ERROR );
30385
30386  assert( pVfs->mxPathname==MAX_PATHNAME );
30387  UNUSED_PARAMETER(pVfs);
30388
30389  zOut[nOut-1] = '\0';
30390  if( zPath[0]=='/' ){
30391    sqlite3_snprintf(nOut, zOut, "%s", zPath);
30392  }else{
30393    int nCwd;
30394    if( osGetcwd(zOut, nOut-1)==0 ){
30395      return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
30396    }
30397    nCwd = (int)strlen(zOut);
30398    sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
30399  }
30400  return SQLITE_OK;
30401}
30402
30403
30404#ifndef SQLITE_OMIT_LOAD_EXTENSION
30405/*
30406** Interfaces for opening a shared library, finding entry points
30407** within the shared library, and closing the shared library.
30408*/
30409#include <dlfcn.h>
30410static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
30411  UNUSED_PARAMETER(NotUsed);
30412  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
30413}
30414
30415/*
30416** SQLite calls this function immediately after a call to unixDlSym() or
30417** unixDlOpen() fails (returns a null pointer). If a more detailed error
30418** message is available, it is written to zBufOut. If no error message
30419** is available, zBufOut is left unmodified and SQLite uses a default
30420** error message.
30421*/
30422static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
30423  const char *zErr;
30424  UNUSED_PARAMETER(NotUsed);
30425  unixEnterMutex();
30426  zErr = dlerror();
30427  if( zErr ){
30428    sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
30429  }
30430  unixLeaveMutex();
30431}
30432static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
30433  /*
30434  ** GCC with -pedantic-errors says that C90 does not allow a void* to be
30435  ** cast into a pointer to a function.  And yet the library dlsym() routine
30436  ** returns a void* which is really a pointer to a function.  So how do we
30437  ** use dlsym() with -pedantic-errors?
30438  **
30439  ** Variable x below is defined to be a pointer to a function taking
30440  ** parameters void* and const char* and returning a pointer to a function.
30441  ** We initialize x by assigning it a pointer to the dlsym() function.
30442  ** (That assignment requires a cast.)  Then we call the function that
30443  ** x points to.
30444  **
30445  ** This work-around is unlikely to work correctly on any system where
30446  ** you really cannot cast a function pointer into void*.  But then, on the
30447  ** other hand, dlsym() will not work on such a system either, so we have
30448  ** not really lost anything.
30449  */
30450  void (*(*x)(void*,const char*))(void);
30451  UNUSED_PARAMETER(NotUsed);
30452  x = (void(*(*)(void*,const char*))(void))dlsym;
30453  return (*x)(p, zSym);
30454}
30455static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
30456  UNUSED_PARAMETER(NotUsed);
30457  dlclose(pHandle);
30458}
30459#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
30460  #define unixDlOpen  0
30461  #define unixDlError 0
30462  #define unixDlSym   0
30463  #define unixDlClose 0
30464#endif
30465
30466/*
30467** Write nBuf bytes of random data to the supplied buffer zBuf.
30468*/
30469static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
30470  UNUSED_PARAMETER(NotUsed);
30471  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
30472
30473  /* We have to initialize zBuf to prevent valgrind from reporting
30474  ** errors.  The reports issued by valgrind are incorrect - we would
30475  ** prefer that the randomness be increased by making use of the
30476  ** uninitialized space in zBuf - but valgrind errors tend to worry
30477  ** some users.  Rather than argue, it seems easier just to initialize
30478  ** the whole array and silence valgrind, even if that means less randomness
30479  ** in the random seed.
30480  **
30481  ** When testing, initializing zBuf[] to zero is all we do.  That means
30482  ** that we always use the same random number sequence.  This makes the
30483  ** tests repeatable.
30484  */
30485  memset(zBuf, 0, nBuf);
30486#if !defined(SQLITE_TEST)
30487  {
30488    int pid, fd, got;
30489    fd = robust_open("/dev/urandom", O_RDONLY, 0);
30490    if( fd<0 ){
30491      time_t t;
30492      time(&t);
30493      memcpy(zBuf, &t, sizeof(t));
30494      pid = getpid();
30495      memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
30496      assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
30497      nBuf = sizeof(t) + sizeof(pid);
30498    }else{
30499      do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
30500      robust_close(0, fd, __LINE__);
30501    }
30502  }
30503#endif
30504  return nBuf;
30505}
30506
30507
30508/*
30509** Sleep for a little while.  Return the amount of time slept.
30510** The argument is the number of microseconds we want to sleep.
30511** The return value is the number of microseconds of sleep actually
30512** requested from the underlying operating system, a number which
30513** might be greater than or equal to the argument, but not less
30514** than the argument.
30515*/
30516static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
30517#if OS_VXWORKS
30518  struct timespec sp;
30519
30520  sp.tv_sec = microseconds / 1000000;
30521  sp.tv_nsec = (microseconds % 1000000) * 1000;
30522  nanosleep(&sp, NULL);
30523  UNUSED_PARAMETER(NotUsed);
30524  return microseconds;
30525#elif defined(HAVE_USLEEP) && HAVE_USLEEP
30526  usleep(microseconds);
30527  UNUSED_PARAMETER(NotUsed);
30528  return microseconds;
30529#else
30530  int seconds = (microseconds+999999)/1000000;
30531  sleep(seconds);
30532  UNUSED_PARAMETER(NotUsed);
30533  return seconds*1000000;
30534#endif
30535}
30536
30537/*
30538** The following variable, if set to a non-zero value, is interpreted as
30539** the number of seconds since 1970 and is used to set the result of
30540** sqlite3OsCurrentTime() during testing.
30541*/
30542#ifdef SQLITE_TEST
30543SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
30544#endif
30545
30546/*
30547** Find the current time (in Universal Coordinated Time).  Write into *piNow
30548** the current time and date as a Julian Day number times 86_400_000.  In
30549** other words, write into *piNow the number of milliseconds since the Julian
30550** epoch of noon in Greenwich on November 24, 4714 B.C according to the
30551** proleptic Gregorian calendar.
30552**
30553** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
30554** cannot be found.
30555*/
30556static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
30557  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
30558  int rc = SQLITE_OK;
30559#if defined(NO_GETTOD)
30560  time_t t;
30561  time(&t);
30562  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
30563#elif OS_VXWORKS
30564  struct timespec sNow;
30565  clock_gettime(CLOCK_REALTIME, &sNow);
30566  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
30567#else
30568  struct timeval sNow;
30569  if( gettimeofday(&sNow, 0)==0 ){
30570    *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
30571  }else{
30572    rc = SQLITE_ERROR;
30573  }
30574#endif
30575
30576#ifdef SQLITE_TEST
30577  if( sqlite3_current_time ){
30578    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
30579  }
30580#endif
30581  UNUSED_PARAMETER(NotUsed);
30582  return rc;
30583}
30584
30585/*
30586** Find the current time (in Universal Coordinated Time).  Write the
30587** current time and date as a Julian Day number into *prNow and
30588** return 0.  Return 1 if the time and date cannot be found.
30589*/
30590static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
30591  sqlite3_int64 i = 0;
30592  int rc;
30593  UNUSED_PARAMETER(NotUsed);
30594  rc = unixCurrentTimeInt64(0, &i);
30595  *prNow = i/86400000.0;
30596  return rc;
30597}
30598
30599/*
30600** We added the xGetLastError() method with the intention of providing
30601** better low-level error messages when operating-system problems come up
30602** during SQLite operation.  But so far, none of that has been implemented
30603** in the core.  So this routine is never called.  For now, it is merely
30604** a place-holder.
30605*/
30606static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
30607  UNUSED_PARAMETER(NotUsed);
30608  UNUSED_PARAMETER(NotUsed2);
30609  UNUSED_PARAMETER(NotUsed3);
30610  return 0;
30611}
30612
30613
30614/*
30615************************ End of sqlite3_vfs methods ***************************
30616******************************************************************************/
30617
30618/******************************************************************************
30619************************** Begin Proxy Locking ********************************
30620**
30621** Proxy locking is a "uber-locking-method" in this sense:  It uses the
30622** other locking methods on secondary lock files.  Proxy locking is a
30623** meta-layer over top of the primitive locking implemented above.  For
30624** this reason, the division that implements of proxy locking is deferred
30625** until late in the file (here) after all of the other I/O methods have
30626** been defined - so that the primitive locking methods are available
30627** as services to help with the implementation of proxy locking.
30628**
30629****
30630**
30631** The default locking schemes in SQLite use byte-range locks on the
30632** database file to coordinate safe, concurrent access by multiple readers
30633** and writers [http://sqlite.org/lockingv3.html].  The five file locking
30634** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
30635** as POSIX read & write locks over fixed set of locations (via fsctl),
30636** on AFP and SMB only exclusive byte-range locks are available via fsctl
30637** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
30638** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
30639** address in the shared range is taken for a SHARED lock, the entire
30640** shared range is taken for an EXCLUSIVE lock):
30641**
30642**      PENDING_BYTE        0x40000000
30643**      RESERVED_BYTE       0x40000001
30644**      SHARED_RANGE        0x40000002 -> 0x40000200
30645**
30646** This works well on the local file system, but shows a nearly 100x
30647** slowdown in read performance on AFP because the AFP client disables
30648** the read cache when byte-range locks are present.  Enabling the read
30649** cache exposes a cache coherency problem that is present on all OS X
30650** supported network file systems.  NFS and AFP both observe the
30651** close-to-open semantics for ensuring cache coherency
30652** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
30653** address the requirements for concurrent database access by multiple
30654** readers and writers
30655** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
30656**
30657** To address the performance and cache coherency issues, proxy file locking
30658** changes the way database access is controlled by limiting access to a
30659** single host at a time and moving file locks off of the database file
30660** and onto a proxy file on the local file system.
30661**
30662**
30663** Using proxy locks
30664** -----------------
30665**
30666** C APIs
30667**
30668**  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
30669**                       <proxy_path> | ":auto:");
30670**  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
30671**
30672**
30673** SQL pragmas
30674**
30675**  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
30676**  PRAGMA [database.]lock_proxy_file
30677**
30678** Specifying ":auto:" means that if there is a conch file with a matching
30679** host ID in it, the proxy path in the conch file will be used, otherwise
30680** a proxy path based on the user's temp dir
30681** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
30682** actual proxy file name is generated from the name and path of the
30683** database file.  For example:
30684**
30685**       For database path "/Users/me/foo.db"
30686**       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
30687**
30688** Once a lock proxy is configured for a database connection, it can not
30689** be removed, however it may be switched to a different proxy path via
30690** the above APIs (assuming the conch file is not being held by another
30691** connection or process).
30692**
30693**
30694** How proxy locking works
30695** -----------------------
30696**
30697** Proxy file locking relies primarily on two new supporting files:
30698**
30699**   *  conch file to limit access to the database file to a single host
30700**      at a time
30701**
30702**   *  proxy file to act as a proxy for the advisory locks normally
30703**      taken on the database
30704**
30705** The conch file - to use a proxy file, sqlite must first "hold the conch"
30706** by taking an sqlite-style shared lock on the conch file, reading the
30707** contents and comparing the host's unique host ID (see below) and lock
30708** proxy path against the values stored in the conch.  The conch file is
30709** stored in the same directory as the database file and the file name
30710** is patterned after the database file name as ".<databasename>-conch".
30711** If the conch file does not exist, or it's contents do not match the
30712** host ID and/or proxy path, then the lock is escalated to an exclusive
30713** lock and the conch file contents is updated with the host ID and proxy
30714** path and the lock is downgraded to a shared lock again.  If the conch
30715** is held by another process (with a shared lock), the exclusive lock
30716** will fail and SQLITE_BUSY is returned.
30717**
30718** The proxy file - a single-byte file used for all advisory file locks
30719** normally taken on the database file.   This allows for safe sharing
30720** of the database file for multiple readers and writers on the same
30721** host (the conch ensures that they all use the same local lock file).
30722**
30723** Requesting the lock proxy does not immediately take the conch, it is
30724** only taken when the first request to lock database file is made.
30725** This matches the semantics of the traditional locking behavior, where
30726** opening a connection to a database file does not take a lock on it.
30727** The shared lock and an open file descriptor are maintained until
30728** the connection to the database is closed.
30729**
30730** The proxy file and the lock file are never deleted so they only need
30731** to be created the first time they are used.
30732**
30733** Configuration options
30734** ---------------------
30735**
30736**  SQLITE_PREFER_PROXY_LOCKING
30737**
30738**       Database files accessed on non-local file systems are
30739**       automatically configured for proxy locking, lock files are
30740**       named automatically using the same logic as
30741**       PRAGMA lock_proxy_file=":auto:"
30742**
30743**  SQLITE_PROXY_DEBUG
30744**
30745**       Enables the logging of error messages during host id file
30746**       retrieval and creation
30747**
30748**  LOCKPROXYDIR
30749**
30750**       Overrides the default directory used for lock proxy files that
30751**       are named automatically via the ":auto:" setting
30752**
30753**  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
30754**
30755**       Permissions to use when creating a directory for storing the
30756**       lock proxy files, only used when LOCKPROXYDIR is not set.
30757**
30758**
30759** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
30760** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
30761** force proxy locking to be used for every database file opened, and 0
30762** will force automatic proxy locking to be disabled for all database
30763** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
30764** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
30765*/
30766
30767/*
30768** Proxy locking is only available on MacOSX
30769*/
30770#if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30771
30772/*
30773** The proxyLockingContext has the path and file structures for the remote
30774** and local proxy files in it
30775*/
30776typedef struct proxyLockingContext proxyLockingContext;
30777struct proxyLockingContext {
30778  unixFile *conchFile;         /* Open conch file */
30779  char *conchFilePath;         /* Name of the conch file */
30780  unixFile *lockProxy;         /* Open proxy lock file */
30781  char *lockProxyPath;         /* Name of the proxy lock file */
30782  char *dbPath;                /* Name of the open file */
30783  int conchHeld;               /* 1 if the conch is held, -1 if lockless */
30784  void *oldLockingContext;     /* Original lockingcontext to restore on close */
30785  sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
30786};
30787
30788/*
30789** The proxy lock file path for the database at dbPath is written into lPath,
30790** which must point to valid, writable memory large enough for a maxLen length
30791** file path.
30792*/
30793static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
30794  int len;
30795  int dbLen;
30796  int i;
30797
30798#ifdef LOCKPROXYDIR
30799  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
30800#else
30801# ifdef _CS_DARWIN_USER_TEMP_DIR
30802  {
30803    if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
30804      OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
30805               lPath, errno, getpid()));
30806      return SQLITE_IOERR_LOCK;
30807    }
30808    len = strlcat(lPath, "sqliteplocks", maxLen);
30809  }
30810# else
30811  len = strlcpy(lPath, "/tmp/", maxLen);
30812# endif
30813#endif
30814
30815  if( lPath[len-1]!='/' ){
30816    len = strlcat(lPath, "/", maxLen);
30817  }
30818
30819  /* transform the db path to a unique cache name */
30820  dbLen = (int)strlen(dbPath);
30821  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
30822    char c = dbPath[i];
30823    lPath[i+len] = (c=='/')?'_':c;
30824  }
30825  lPath[i+len]='\0';
30826  strlcat(lPath, ":auto:", maxLen);
30827  OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
30828  return SQLITE_OK;
30829}
30830
30831/*
30832 ** Creates the lock file and any missing directories in lockPath
30833 */
30834static int proxyCreateLockPath(const char *lockPath){
30835  int i, len;
30836  char buf[MAXPATHLEN];
30837  int start = 0;
30838
30839  assert(lockPath!=NULL);
30840  /* try to create all the intermediate directories */
30841  len = (int)strlen(lockPath);
30842  buf[0] = lockPath[0];
30843  for( i=1; i<len; i++ ){
30844    if( lockPath[i] == '/' && (i - start > 0) ){
30845      /* only mkdir if leaf dir != "." or "/" or ".." */
30846      if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
30847         || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
30848        buf[i]='\0';
30849        if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
30850          int err=errno;
30851          if( err!=EEXIST ) {
30852            OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
30853                     "'%s' proxy lock path=%s pid=%d\n",
30854                     buf, strerror(err), lockPath, getpid()));
30855            return err;
30856          }
30857        }
30858      }
30859      start=i+1;
30860    }
30861    buf[i] = lockPath[i];
30862  }
30863  OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
30864  return 0;
30865}
30866
30867/*
30868** Create a new VFS file descriptor (stored in memory obtained from
30869** sqlite3_malloc) and open the file named "path" in the file descriptor.
30870**
30871** The caller is responsible not only for closing the file descriptor
30872** but also for freeing the memory associated with the file descriptor.
30873*/
30874static int proxyCreateUnixFile(
30875    const char *path,        /* path for the new unixFile */
30876    unixFile **ppFile,       /* unixFile created and returned by ref */
30877    int islockfile           /* if non zero missing dirs will be created */
30878) {
30879  int fd = -1;
30880  unixFile *pNew;
30881  int rc = SQLITE_OK;
30882  int openFlags = O_RDWR | O_CREAT;
30883  sqlite3_vfs dummyVfs;
30884  int terrno = 0;
30885  UnixUnusedFd *pUnused = NULL;
30886
30887  /* 1. first try to open/create the file
30888  ** 2. if that fails, and this is a lock file (not-conch), try creating
30889  ** the parent directories and then try again.
30890  ** 3. if that fails, try to open the file read-only
30891  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
30892  */
30893  pUnused = findReusableFd(path, openFlags);
30894  if( pUnused ){
30895    fd = pUnused->fd;
30896  }else{
30897    pUnused = sqlite3_malloc(sizeof(*pUnused));
30898    if( !pUnused ){
30899      return SQLITE_NOMEM;
30900    }
30901  }
30902  if( fd<0 ){
30903    fd = robust_open(path, openFlags, 0);
30904    terrno = errno;
30905    if( fd<0 && errno==ENOENT && islockfile ){
30906      if( proxyCreateLockPath(path) == SQLITE_OK ){
30907        fd = robust_open(path, openFlags, 0);
30908      }
30909    }
30910  }
30911  if( fd<0 ){
30912    openFlags = O_RDONLY;
30913    fd = robust_open(path, openFlags, 0);
30914    terrno = errno;
30915  }
30916  if( fd<0 ){
30917    if( islockfile ){
30918      return SQLITE_BUSY;
30919    }
30920    switch (terrno) {
30921      case EACCES:
30922        return SQLITE_PERM;
30923      case EIO:
30924        return SQLITE_IOERR_LOCK; /* even though it is the conch */
30925      default:
30926        return SQLITE_CANTOPEN_BKPT;
30927    }
30928  }
30929
30930  pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
30931  if( pNew==NULL ){
30932    rc = SQLITE_NOMEM;
30933    goto end_create_proxy;
30934  }
30935  memset(pNew, 0, sizeof(unixFile));
30936  pNew->openFlags = openFlags;
30937  memset(&dummyVfs, 0, sizeof(dummyVfs));
30938  dummyVfs.pAppData = (void*)&autolockIoFinder;
30939  dummyVfs.zName = "dummy";
30940  pUnused->fd = fd;
30941  pUnused->flags = openFlags;
30942  pNew->pUnused = pUnused;
30943
30944  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
30945  if( rc==SQLITE_OK ){
30946    *ppFile = pNew;
30947    return SQLITE_OK;
30948  }
30949end_create_proxy:
30950  robust_close(pNew, fd, __LINE__);
30951  sqlite3_free(pNew);
30952  sqlite3_free(pUnused);
30953  return rc;
30954}
30955
30956#ifdef SQLITE_TEST
30957/* simulate multiple hosts by creating unique hostid file paths */
30958SQLITE_API int sqlite3_hostid_num = 0;
30959#endif
30960
30961#define PROXY_HOSTIDLEN    16  /* conch file host id length */
30962
30963/* Not always defined in the headers as it ought to be */
30964extern int gethostuuid(uuid_t id, const struct timespec *wait);
30965
30966/* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
30967** bytes of writable memory.
30968*/
30969static int proxyGetHostID(unsigned char *pHostID, int *pError){
30970  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
30971  memset(pHostID, 0, PROXY_HOSTIDLEN);
30972#if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
30973               && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
30974  {
30975    static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
30976    if( gethostuuid(pHostID, &timeout) ){
30977      int err = errno;
30978      if( pError ){
30979        *pError = err;
30980      }
30981      return SQLITE_IOERR;
30982    }
30983  }
30984#else
30985  UNUSED_PARAMETER(pError);
30986#endif
30987#ifdef SQLITE_TEST
30988  /* simulate multiple hosts by creating unique hostid file paths */
30989  if( sqlite3_hostid_num != 0){
30990    pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
30991  }
30992#endif
30993
30994  return SQLITE_OK;
30995}
30996
30997/* The conch file contains the header, host id and lock file path
30998 */
30999#define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
31000#define PROXY_HEADERLEN    1   /* conch file header length */
31001#define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
31002#define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
31003
31004/*
31005** Takes an open conch file, copies the contents to a new path and then moves
31006** it back.  The newly created file's file descriptor is assigned to the
31007** conch file structure and finally the original conch file descriptor is
31008** closed.  Returns zero if successful.
31009*/
31010static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
31011  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31012  unixFile *conchFile = pCtx->conchFile;
31013  char tPath[MAXPATHLEN];
31014  char buf[PROXY_MAXCONCHLEN];
31015  char *cPath = pCtx->conchFilePath;
31016  size_t readLen = 0;
31017  size_t pathLen = 0;
31018  char errmsg[64] = "";
31019  int fd = -1;
31020  int rc = -1;
31021  UNUSED_PARAMETER(myHostID);
31022
31023  /* create a new path by replace the trailing '-conch' with '-break' */
31024  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
31025  if( pathLen>MAXPATHLEN || pathLen<6 ||
31026     (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
31027    sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
31028    goto end_breaklock;
31029  }
31030  /* read the conch content */
31031  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
31032  if( readLen<PROXY_PATHINDEX ){
31033    sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
31034    goto end_breaklock;
31035  }
31036  /* write it out to the temporary break file */
31037  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
31038  if( fd<0 ){
31039    sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
31040    goto end_breaklock;
31041  }
31042  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
31043    sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
31044    goto end_breaklock;
31045  }
31046  if( rename(tPath, cPath) ){
31047    sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
31048    goto end_breaklock;
31049  }
31050  rc = 0;
31051  fprintf(stderr, "broke stale lock on %s\n", cPath);
31052  robust_close(pFile, conchFile->h, __LINE__);
31053  conchFile->h = fd;
31054  conchFile->openFlags = O_RDWR | O_CREAT;
31055
31056end_breaklock:
31057  if( rc ){
31058    if( fd>=0 ){
31059      osUnlink(tPath);
31060      robust_close(pFile, fd, __LINE__);
31061    }
31062    fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
31063  }
31064  return rc;
31065}
31066
31067/* Take the requested lock on the conch file and break a stale lock if the
31068** host id matches.
31069*/
31070static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
31071  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31072  unixFile *conchFile = pCtx->conchFile;
31073  int rc = SQLITE_OK;
31074  int nTries = 0;
31075  struct timespec conchModTime;
31076
31077  memset(&conchModTime, 0, sizeof(conchModTime));
31078  do {
31079    rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31080    nTries ++;
31081    if( rc==SQLITE_BUSY ){
31082      /* If the lock failed (busy):
31083       * 1st try: get the mod time of the conch, wait 0.5s and try again.
31084       * 2nd try: fail if the mod time changed or host id is different, wait
31085       *           10 sec and try again
31086       * 3rd try: break the lock unless the mod time has changed.
31087       */
31088      struct stat buf;
31089      if( osFstat(conchFile->h, &buf) ){
31090        pFile->lastErrno = errno;
31091        return SQLITE_IOERR_LOCK;
31092      }
31093
31094      if( nTries==1 ){
31095        conchModTime = buf.st_mtimespec;
31096        usleep(500000); /* wait 0.5 sec and try the lock again*/
31097        continue;
31098      }
31099
31100      assert( nTries>1 );
31101      if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
31102         conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
31103        return SQLITE_BUSY;
31104      }
31105
31106      if( nTries==2 ){
31107        char tBuf[PROXY_MAXCONCHLEN];
31108        int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
31109        if( len<0 ){
31110          pFile->lastErrno = errno;
31111          return SQLITE_IOERR_LOCK;
31112        }
31113        if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
31114          /* don't break the lock if the host id doesn't match */
31115          if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
31116            return SQLITE_BUSY;
31117          }
31118        }else{
31119          /* don't break the lock on short read or a version mismatch */
31120          return SQLITE_BUSY;
31121        }
31122        usleep(10000000); /* wait 10 sec and try the lock again */
31123        continue;
31124      }
31125
31126      assert( nTries==3 );
31127      if( 0==proxyBreakConchLock(pFile, myHostID) ){
31128        rc = SQLITE_OK;
31129        if( lockType==EXCLUSIVE_LOCK ){
31130          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
31131        }
31132        if( !rc ){
31133          rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
31134        }
31135      }
31136    }
31137  } while( rc==SQLITE_BUSY && nTries<3 );
31138
31139  return rc;
31140}
31141
31142/* Takes the conch by taking a shared lock and read the contents conch, if
31143** lockPath is non-NULL, the host ID and lock file path must match.  A NULL
31144** lockPath means that the lockPath in the conch file will be used if the
31145** host IDs match, or a new lock path will be generated automatically
31146** and written to the conch file.
31147*/
31148static int proxyTakeConch(unixFile *pFile){
31149  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31150
31151  if( pCtx->conchHeld!=0 ){
31152    return SQLITE_OK;
31153  }else{
31154    unixFile *conchFile = pCtx->conchFile;
31155    uuid_t myHostID;
31156    int pError = 0;
31157    char readBuf[PROXY_MAXCONCHLEN];
31158    char lockPath[MAXPATHLEN];
31159    char *tempLockPath = NULL;
31160    int rc = SQLITE_OK;
31161    int createConch = 0;
31162    int hostIdMatch = 0;
31163    int readLen = 0;
31164    int tryOldLockPath = 0;
31165    int forceNewLockPath = 0;
31166
31167    OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
31168             (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
31169
31170    rc = proxyGetHostID(myHostID, &pError);
31171    if( (rc&0xff)==SQLITE_IOERR ){
31172      pFile->lastErrno = pError;
31173      goto end_takeconch;
31174    }
31175    rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
31176    if( rc!=SQLITE_OK ){
31177      goto end_takeconch;
31178    }
31179    /* read the existing conch file */
31180    readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
31181    if( readLen<0 ){
31182      /* I/O error: lastErrno set by seekAndRead */
31183      pFile->lastErrno = conchFile->lastErrno;
31184      rc = SQLITE_IOERR_READ;
31185      goto end_takeconch;
31186    }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
31187             readBuf[0]!=(char)PROXY_CONCHVERSION ){
31188      /* a short read or version format mismatch means we need to create a new
31189      ** conch file.
31190      */
31191      createConch = 1;
31192    }
31193    /* if the host id matches and the lock path already exists in the conch
31194    ** we'll try to use the path there, if we can't open that path, we'll
31195    ** retry with a new auto-generated path
31196    */
31197    do { /* in case we need to try again for an :auto: named lock file */
31198
31199      if( !createConch && !forceNewLockPath ){
31200        hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
31201                                  PROXY_HOSTIDLEN);
31202        /* if the conch has data compare the contents */
31203        if( !pCtx->lockProxyPath ){
31204          /* for auto-named local lock file, just check the host ID and we'll
31205           ** use the local lock file path that's already in there
31206           */
31207          if( hostIdMatch ){
31208            size_t pathLen = (readLen - PROXY_PATHINDEX);
31209
31210            if( pathLen>=MAXPATHLEN ){
31211              pathLen=MAXPATHLEN-1;
31212            }
31213            memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
31214            lockPath[pathLen] = 0;
31215            tempLockPath = lockPath;
31216            tryOldLockPath = 1;
31217            /* create a copy of the lock path if the conch is taken */
31218            goto end_takeconch;
31219          }
31220        }else if( hostIdMatch
31221               && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
31222                           readLen-PROXY_PATHINDEX)
31223        ){
31224          /* conch host and lock path match */
31225          goto end_takeconch;
31226        }
31227      }
31228
31229      /* if the conch isn't writable and doesn't match, we can't take it */
31230      if( (conchFile->openFlags&O_RDWR) == 0 ){
31231        rc = SQLITE_BUSY;
31232        goto end_takeconch;
31233      }
31234
31235      /* either the conch didn't match or we need to create a new one */
31236      if( !pCtx->lockProxyPath ){
31237        proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
31238        tempLockPath = lockPath;
31239        /* create a copy of the lock path _only_ if the conch is taken */
31240      }
31241
31242      /* update conch with host and path (this will fail if other process
31243      ** has a shared lock already), if the host id matches, use the big
31244      ** stick.
31245      */
31246      futimes(conchFile->h, NULL);
31247      if( hostIdMatch && !createConch ){
31248        if( conchFile->pInode && conchFile->pInode->nShared>1 ){
31249          /* We are trying for an exclusive lock but another thread in this
31250           ** same process is still holding a shared lock. */
31251          rc = SQLITE_BUSY;
31252        } else {
31253          rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
31254        }
31255      }else{
31256        rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
31257      }
31258      if( rc==SQLITE_OK ){
31259        char writeBuffer[PROXY_MAXCONCHLEN];
31260        int writeSize = 0;
31261
31262        writeBuffer[0] = (char)PROXY_CONCHVERSION;
31263        memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
31264        if( pCtx->lockProxyPath!=NULL ){
31265          strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
31266        }else{
31267          strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
31268        }
31269        writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
31270        robust_ftruncate(conchFile->h, writeSize);
31271        rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
31272        fsync(conchFile->h);
31273        /* If we created a new conch file (not just updated the contents of a
31274         ** valid conch file), try to match the permissions of the database
31275         */
31276        if( rc==SQLITE_OK && createConch ){
31277          struct stat buf;
31278          int err = osFstat(pFile->h, &buf);
31279          if( err==0 ){
31280            mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
31281                                        S_IROTH|S_IWOTH);
31282            /* try to match the database file R/W permissions, ignore failure */
31283#ifndef SQLITE_PROXY_DEBUG
31284            osFchmod(conchFile->h, cmode);
31285#else
31286            do{
31287              rc = osFchmod(conchFile->h, cmode);
31288            }while( rc==(-1) && errno==EINTR );
31289            if( rc!=0 ){
31290              int code = errno;
31291              fprintf(stderr, "fchmod %o FAILED with %d %s\n",
31292                      cmode, code, strerror(code));
31293            } else {
31294              fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
31295            }
31296          }else{
31297            int code = errno;
31298            fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
31299                    err, code, strerror(code));
31300#endif
31301          }
31302        }
31303      }
31304      conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
31305
31306    end_takeconch:
31307      OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
31308      if( rc==SQLITE_OK && pFile->openFlags ){
31309        int fd;
31310        if( pFile->h>=0 ){
31311          robust_close(pFile, pFile->h, __LINE__);
31312        }
31313        pFile->h = -1;
31314        fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
31315        OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
31316        if( fd>=0 ){
31317          pFile->h = fd;
31318        }else{
31319          rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
31320           during locking */
31321        }
31322      }
31323      if( rc==SQLITE_OK && !pCtx->lockProxy ){
31324        char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
31325        rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
31326        if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
31327          /* we couldn't create the proxy lock file with the old lock file path
31328           ** so try again via auto-naming
31329           */
31330          forceNewLockPath = 1;
31331          tryOldLockPath = 0;
31332          continue; /* go back to the do {} while start point, try again */
31333        }
31334      }
31335      if( rc==SQLITE_OK ){
31336        /* Need to make a copy of path if we extracted the value
31337         ** from the conch file or the path was allocated on the stack
31338         */
31339        if( tempLockPath ){
31340          pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
31341          if( !pCtx->lockProxyPath ){
31342            rc = SQLITE_NOMEM;
31343          }
31344        }
31345      }
31346      if( rc==SQLITE_OK ){
31347        pCtx->conchHeld = 1;
31348
31349        if( pCtx->lockProxy->pMethod == &afpIoMethods ){
31350          afpLockingContext *afpCtx;
31351          afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
31352          afpCtx->dbPath = pCtx->lockProxyPath;
31353        }
31354      } else {
31355        conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31356      }
31357      OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
31358               rc==SQLITE_OK?"ok":"failed"));
31359      return rc;
31360    } while (1); /* in case we need to retry the :auto: lock file -
31361                 ** we should never get here except via the 'continue' call. */
31362  }
31363}
31364
31365/*
31366** If pFile holds a lock on a conch file, then release that lock.
31367*/
31368static int proxyReleaseConch(unixFile *pFile){
31369  int rc = SQLITE_OK;         /* Subroutine return code */
31370  proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
31371  unixFile *conchFile;        /* Name of the conch file */
31372
31373  pCtx = (proxyLockingContext *)pFile->lockingContext;
31374  conchFile = pCtx->conchFile;
31375  OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
31376           (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
31377           getpid()));
31378  if( pCtx->conchHeld>0 ){
31379    rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
31380  }
31381  pCtx->conchHeld = 0;
31382  OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
31383           (rc==SQLITE_OK ? "ok" : "failed")));
31384  return rc;
31385}
31386
31387/*
31388** Given the name of a database file, compute the name of its conch file.
31389** Store the conch filename in memory obtained from sqlite3_malloc().
31390** Make *pConchPath point to the new name.  Return SQLITE_OK on success
31391** or SQLITE_NOMEM if unable to obtain memory.
31392**
31393** The caller is responsible for ensuring that the allocated memory
31394** space is eventually freed.
31395**
31396** *pConchPath is set to NULL if a memory allocation error occurs.
31397*/
31398static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
31399  int i;                        /* Loop counter */
31400  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
31401  char *conchPath;              /* buffer in which to construct conch name */
31402
31403  /* Allocate space for the conch filename and initialize the name to
31404  ** the name of the original database file. */
31405  *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
31406  if( conchPath==0 ){
31407    return SQLITE_NOMEM;
31408  }
31409  memcpy(conchPath, dbPath, len+1);
31410
31411  /* now insert a "." before the last / character */
31412  for( i=(len-1); i>=0; i-- ){
31413    if( conchPath[i]=='/' ){
31414      i++;
31415      break;
31416    }
31417  }
31418  conchPath[i]='.';
31419  while ( i<len ){
31420    conchPath[i+1]=dbPath[i];
31421    i++;
31422  }
31423
31424  /* append the "-conch" suffix to the file */
31425  memcpy(&conchPath[i+1], "-conch", 7);
31426  assert( (int)strlen(conchPath) == len+7 );
31427
31428  return SQLITE_OK;
31429}
31430
31431
31432/* Takes a fully configured proxy locking-style unix file and switches
31433** the local lock file path
31434*/
31435static int switchLockProxyPath(unixFile *pFile, const char *path) {
31436  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31437  char *oldPath = pCtx->lockProxyPath;
31438  int rc = SQLITE_OK;
31439
31440  if( pFile->eFileLock!=NO_LOCK ){
31441    return SQLITE_BUSY;
31442  }
31443
31444  /* nothing to do if the path is NULL, :auto: or matches the existing path */
31445  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
31446    (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
31447    return SQLITE_OK;
31448  }else{
31449    unixFile *lockProxy = pCtx->lockProxy;
31450    pCtx->lockProxy=NULL;
31451    pCtx->conchHeld = 0;
31452    if( lockProxy!=NULL ){
31453      rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
31454      if( rc ) return rc;
31455      sqlite3_free(lockProxy);
31456    }
31457    sqlite3_free(oldPath);
31458    pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
31459  }
31460
31461  return rc;
31462}
31463
31464/*
31465** pFile is a file that has been opened by a prior xOpen call.  dbPath
31466** is a string buffer at least MAXPATHLEN+1 characters in size.
31467**
31468** This routine find the filename associated with pFile and writes it
31469** int dbPath.
31470*/
31471static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
31472#if defined(__APPLE__)
31473  if( pFile->pMethod == &afpIoMethods ){
31474    /* afp style keeps a reference to the db path in the filePath field
31475    ** of the struct */
31476    assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31477    strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
31478  } else
31479#endif
31480  if( pFile->pMethod == &dotlockIoMethods ){
31481    /* dot lock style uses the locking context to store the dot lock
31482    ** file path */
31483    int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
31484    memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
31485  }else{
31486    /* all other styles use the locking context to store the db file path */
31487    assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
31488    strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
31489  }
31490  return SQLITE_OK;
31491}
31492
31493/*
31494** Takes an already filled in unix file and alters it so all file locking
31495** will be performed on the local proxy lock file.  The following fields
31496** are preserved in the locking context so that they can be restored and
31497** the unix structure properly cleaned up at close time:
31498**  ->lockingContext
31499**  ->pMethod
31500*/
31501static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
31502  proxyLockingContext *pCtx;
31503  char dbPath[MAXPATHLEN+1];       /* Name of the database file */
31504  char *lockPath=NULL;
31505  int rc = SQLITE_OK;
31506
31507  if( pFile->eFileLock!=NO_LOCK ){
31508    return SQLITE_BUSY;
31509  }
31510  proxyGetDbPathForUnixFile(pFile, dbPath);
31511  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
31512    lockPath=NULL;
31513  }else{
31514    lockPath=(char *)path;
31515  }
31516
31517  OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
31518           (lockPath ? lockPath : ":auto:"), getpid()));
31519
31520  pCtx = sqlite3_malloc( sizeof(*pCtx) );
31521  if( pCtx==0 ){
31522    return SQLITE_NOMEM;
31523  }
31524  memset(pCtx, 0, sizeof(*pCtx));
31525
31526  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
31527  if( rc==SQLITE_OK ){
31528    rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
31529    if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
31530      /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
31531      ** (c) the file system is read-only, then enable no-locking access.
31532      ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
31533      ** that openFlags will have only one of O_RDONLY or O_RDWR.
31534      */
31535      struct statfs fsInfo;
31536      struct stat conchInfo;
31537      int goLockless = 0;
31538
31539      if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
31540        int err = errno;
31541        if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
31542          goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
31543        }
31544      }
31545      if( goLockless ){
31546        pCtx->conchHeld = -1; /* read only FS/ lockless */
31547        rc = SQLITE_OK;
31548      }
31549    }
31550  }
31551  if( rc==SQLITE_OK && lockPath ){
31552    pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
31553  }
31554
31555  if( rc==SQLITE_OK ){
31556    pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
31557    if( pCtx->dbPath==NULL ){
31558      rc = SQLITE_NOMEM;
31559    }
31560  }
31561  if( rc==SQLITE_OK ){
31562    /* all memory is allocated, proxys are created and assigned,
31563    ** switch the locking context and pMethod then return.
31564    */
31565    pCtx->oldLockingContext = pFile->lockingContext;
31566    pFile->lockingContext = pCtx;
31567    pCtx->pOldMethod = pFile->pMethod;
31568    pFile->pMethod = &proxyIoMethods;
31569  }else{
31570    if( pCtx->conchFile ){
31571      pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
31572      sqlite3_free(pCtx->conchFile);
31573    }
31574    sqlite3DbFree(0, pCtx->lockProxyPath);
31575    sqlite3_free(pCtx->conchFilePath);
31576    sqlite3_free(pCtx);
31577  }
31578  OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
31579           (rc==SQLITE_OK ? "ok" : "failed")));
31580  return rc;
31581}
31582
31583
31584/*
31585** This routine handles sqlite3_file_control() calls that are specific
31586** to proxy locking.
31587*/
31588static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
31589  switch( op ){
31590    case SQLITE_GET_LOCKPROXYFILE: {
31591      unixFile *pFile = (unixFile*)id;
31592      if( pFile->pMethod == &proxyIoMethods ){
31593        proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
31594        proxyTakeConch(pFile);
31595        if( pCtx->lockProxyPath ){
31596          *(const char **)pArg = pCtx->lockProxyPath;
31597        }else{
31598          *(const char **)pArg = ":auto: (not held)";
31599        }
31600      } else {
31601        *(const char **)pArg = NULL;
31602      }
31603      return SQLITE_OK;
31604    }
31605    case SQLITE_SET_LOCKPROXYFILE: {
31606      unixFile *pFile = (unixFile*)id;
31607      int rc = SQLITE_OK;
31608      int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
31609      if( pArg==NULL || (const char *)pArg==0 ){
31610        if( isProxyStyle ){
31611          /* turn off proxy locking - not supported */
31612          rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
31613        }else{
31614          /* turn off proxy locking - already off - NOOP */
31615          rc = SQLITE_OK;
31616        }
31617      }else{
31618        const char *proxyPath = (const char *)pArg;
31619        if( isProxyStyle ){
31620          proxyLockingContext *pCtx =
31621            (proxyLockingContext*)pFile->lockingContext;
31622          if( !strcmp(pArg, ":auto:")
31623           || (pCtx->lockProxyPath &&
31624               !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
31625          ){
31626            rc = SQLITE_OK;
31627          }else{
31628            rc = switchLockProxyPath(pFile, proxyPath);
31629          }
31630        }else{
31631          /* turn on proxy file locking */
31632          rc = proxyTransformUnixFile(pFile, proxyPath);
31633        }
31634      }
31635      return rc;
31636    }
31637    default: {
31638      assert( 0 );  /* The call assures that only valid opcodes are sent */
31639    }
31640  }
31641  /*NOTREACHED*/
31642  return SQLITE_ERROR;
31643}
31644
31645/*
31646** Within this division (the proxying locking implementation) the procedures
31647** above this point are all utilities.  The lock-related methods of the
31648** proxy-locking sqlite3_io_method object follow.
31649*/
31650
31651
31652/*
31653** This routine checks if there is a RESERVED lock held on the specified
31654** file by this or any other process. If such a lock is held, set *pResOut
31655** to a non-zero value otherwise *pResOut is set to zero.  The return value
31656** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31657*/
31658static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
31659  unixFile *pFile = (unixFile*)id;
31660  int rc = proxyTakeConch(pFile);
31661  if( rc==SQLITE_OK ){
31662    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31663    if( pCtx->conchHeld>0 ){
31664      unixFile *proxy = pCtx->lockProxy;
31665      return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
31666    }else{ /* conchHeld < 0 is lockless */
31667      pResOut=0;
31668    }
31669  }
31670  return rc;
31671}
31672
31673/*
31674** Lock the file with the lock specified by parameter eFileLock - one
31675** of the following:
31676**
31677**     (1) SHARED_LOCK
31678**     (2) RESERVED_LOCK
31679**     (3) PENDING_LOCK
31680**     (4) EXCLUSIVE_LOCK
31681**
31682** Sometimes when requesting one lock state, additional lock states
31683** are inserted in between.  The locking might fail on one of the later
31684** transitions leaving the lock state different from what it started but
31685** still short of its goal.  The following chart shows the allowed
31686** transitions and the inserted intermediate states:
31687**
31688**    UNLOCKED -> SHARED
31689**    SHARED -> RESERVED
31690**    SHARED -> (PENDING) -> EXCLUSIVE
31691**    RESERVED -> (PENDING) -> EXCLUSIVE
31692**    PENDING -> EXCLUSIVE
31693**
31694** This routine will only increase a lock.  Use the sqlite3OsUnlock()
31695** routine to lower a locking level.
31696*/
31697static int proxyLock(sqlite3_file *id, int eFileLock) {
31698  unixFile *pFile = (unixFile*)id;
31699  int rc = proxyTakeConch(pFile);
31700  if( rc==SQLITE_OK ){
31701    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31702    if( pCtx->conchHeld>0 ){
31703      unixFile *proxy = pCtx->lockProxy;
31704      rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
31705      pFile->eFileLock = proxy->eFileLock;
31706    }else{
31707      /* conchHeld < 0 is lockless */
31708    }
31709  }
31710  return rc;
31711}
31712
31713
31714/*
31715** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
31716** must be either NO_LOCK or SHARED_LOCK.
31717**
31718** If the locking level of the file descriptor is already at or below
31719** the requested locking level, this routine is a no-op.
31720*/
31721static int proxyUnlock(sqlite3_file *id, int eFileLock) {
31722  unixFile *pFile = (unixFile*)id;
31723  int rc = proxyTakeConch(pFile);
31724  if( rc==SQLITE_OK ){
31725    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31726    if( pCtx->conchHeld>0 ){
31727      unixFile *proxy = pCtx->lockProxy;
31728      rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
31729      pFile->eFileLock = proxy->eFileLock;
31730    }else{
31731      /* conchHeld < 0 is lockless */
31732    }
31733  }
31734  return rc;
31735}
31736
31737/*
31738** Close a file that uses proxy locks.
31739*/
31740static int proxyClose(sqlite3_file *id) {
31741  if( id ){
31742    unixFile *pFile = (unixFile*)id;
31743    proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
31744    unixFile *lockProxy = pCtx->lockProxy;
31745    unixFile *conchFile = pCtx->conchFile;
31746    int rc = SQLITE_OK;
31747
31748    if( lockProxy ){
31749      rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
31750      if( rc ) return rc;
31751      rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
31752      if( rc ) return rc;
31753      sqlite3_free(lockProxy);
31754      pCtx->lockProxy = 0;
31755    }
31756    if( conchFile ){
31757      if( pCtx->conchHeld ){
31758        rc = proxyReleaseConch(pFile);
31759        if( rc ) return rc;
31760      }
31761      rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
31762      if( rc ) return rc;
31763      sqlite3_free(conchFile);
31764    }
31765    sqlite3DbFree(0, pCtx->lockProxyPath);
31766    sqlite3_free(pCtx->conchFilePath);
31767    sqlite3DbFree(0, pCtx->dbPath);
31768    /* restore the original locking context and pMethod then close it */
31769    pFile->lockingContext = pCtx->oldLockingContext;
31770    pFile->pMethod = pCtx->pOldMethod;
31771    sqlite3_free(pCtx);
31772    return pFile->pMethod->xClose(id);
31773  }
31774  return SQLITE_OK;
31775}
31776
31777
31778
31779#endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
31780/*
31781** The proxy locking style is intended for use with AFP filesystems.
31782** And since AFP is only supported on MacOSX, the proxy locking is also
31783** restricted to MacOSX.
31784**
31785**
31786******************* End of the proxy lock implementation **********************
31787******************************************************************************/
31788
31789/*
31790** Initialize the operating system interface.
31791**
31792** This routine registers all VFS implementations for unix-like operating
31793** systems.  This routine, and the sqlite3_os_end() routine that follows,
31794** should be the only routines in this file that are visible from other
31795** files.
31796**
31797** This routine is called once during SQLite initialization and by a
31798** single thread.  The memory allocation and mutex subsystems have not
31799** necessarily been initialized when this routine is called, and so they
31800** should not be used.
31801*/
31802SQLITE_API int sqlite3_os_init(void){
31803  /*
31804  ** The following macro defines an initializer for an sqlite3_vfs object.
31805  ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
31806  ** to the "finder" function.  (pAppData is a pointer to a pointer because
31807  ** silly C90 rules prohibit a void* from being cast to a function pointer
31808  ** and so we have to go through the intermediate pointer to avoid problems
31809  ** when compiling with -pedantic-errors on GCC.)
31810  **
31811  ** The FINDER parameter to this macro is the name of the pointer to the
31812  ** finder-function.  The finder-function returns a pointer to the
31813  ** sqlite_io_methods object that implements the desired locking
31814  ** behaviors.  See the division above that contains the IOMETHODS
31815  ** macro for addition information on finder-functions.
31816  **
31817  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
31818  ** object.  But the "autolockIoFinder" available on MacOSX does a little
31819  ** more than that; it looks at the filesystem type that hosts the
31820  ** database file and tries to choose an locking method appropriate for
31821  ** that filesystem time.
31822  */
31823  #define UNIXVFS(VFSNAME, FINDER) {                        \
31824    3,                    /* iVersion */                    \
31825    sizeof(unixFile),     /* szOsFile */                    \
31826    MAX_PATHNAME,         /* mxPathname */                  \
31827    0,                    /* pNext */                       \
31828    VFSNAME,              /* zName */                       \
31829    (void*)&FINDER,       /* pAppData */                    \
31830    unixOpen,             /* xOpen */                       \
31831    unixDelete,           /* xDelete */                     \
31832    unixAccess,           /* xAccess */                     \
31833    unixFullPathname,     /* xFullPathname */               \
31834    unixDlOpen,           /* xDlOpen */                     \
31835    unixDlError,          /* xDlError */                    \
31836    unixDlSym,            /* xDlSym */                      \
31837    unixDlClose,          /* xDlClose */                    \
31838    unixRandomness,       /* xRandomness */                 \
31839    unixSleep,            /* xSleep */                      \
31840    unixCurrentTime,      /* xCurrentTime */                \
31841    unixGetLastError,     /* xGetLastError */               \
31842    unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
31843    unixSetSystemCall,    /* xSetSystemCall */              \
31844    unixGetSystemCall,    /* xGetSystemCall */              \
31845    unixNextSystemCall,   /* xNextSystemCall */             \
31846  }
31847
31848  /*
31849  ** All default VFSes for unix are contained in the following array.
31850  **
31851  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
31852  ** by the SQLite core when the VFS is registered.  So the following
31853  ** array cannot be const.
31854  */
31855  static sqlite3_vfs aVfs[] = {
31856#if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
31857    UNIXVFS("unix",          autolockIoFinder ),
31858#else
31859    UNIXVFS("unix",          posixIoFinder ),
31860#endif
31861    UNIXVFS("unix-none",     nolockIoFinder ),
31862    UNIXVFS("unix-dotfile",  dotlockIoFinder ),
31863    UNIXVFS("unix-excl",     posixIoFinder ),
31864#if OS_VXWORKS
31865    UNIXVFS("unix-namedsem", semIoFinder ),
31866#endif
31867#if SQLITE_ENABLE_LOCKING_STYLE
31868    UNIXVFS("unix-posix",    posixIoFinder ),
31869#if !OS_VXWORKS
31870    UNIXVFS("unix-flock",    flockIoFinder ),
31871#endif
31872#endif
31873#if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
31874    UNIXVFS("unix-afp",      afpIoFinder ),
31875    UNIXVFS("unix-nfs",      nfsIoFinder ),
31876    UNIXVFS("unix-proxy",    proxyIoFinder ),
31877#endif
31878  };
31879  unsigned int i;          /* Loop counter */
31880
31881  /* Double-check that the aSyscall[] array has been constructed
31882  ** correctly.  See ticket [bb3a86e890c8e96ab] */
31883  assert( ArraySize(aSyscall)==22 );
31884
31885  /* Register all VFSes defined in the aVfs[] array */
31886  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
31887    sqlite3_vfs_register(&aVfs[i], i==0);
31888  }
31889  return SQLITE_OK;
31890}
31891
31892/*
31893** Shutdown the operating system interface.
31894**
31895** Some operating systems might need to do some cleanup in this routine,
31896** to release dynamically allocated objects.  But not on unix.
31897** This routine is a no-op for unix.
31898*/
31899SQLITE_API int sqlite3_os_end(void){
31900  return SQLITE_OK;
31901}
31902
31903#endif /* SQLITE_OS_UNIX */
31904
31905/************** End of os_unix.c *********************************************/
31906/************** Begin file os_win.c ******************************************/
31907/*
31908** 2004 May 22
31909**
31910** The author disclaims copyright to this source code.  In place of
31911** a legal notice, here is a blessing:
31912**
31913**    May you do good and not evil.
31914**    May you find forgiveness for yourself and forgive others.
31915**    May you share freely, never taking more than you give.
31916**
31917******************************************************************************
31918**
31919** This file contains code that is specific to Windows.
31920*/
31921#if SQLITE_OS_WIN               /* This file is used for Windows only */
31922
31923#ifdef __CYGWIN__
31924# include <sys/cygwin.h>
31925#endif
31926
31927/*
31928** Include code that is common to all os_*.c files
31929*/
31930/************** Include os_common.h in the middle of os_win.c ****************/
31931/************** Begin file os_common.h ***************************************/
31932/*
31933** 2004 May 22
31934**
31935** The author disclaims copyright to this source code.  In place of
31936** a legal notice, here is a blessing:
31937**
31938**    May you do good and not evil.
31939**    May you find forgiveness for yourself and forgive others.
31940**    May you share freely, never taking more than you give.
31941**
31942******************************************************************************
31943**
31944** This file contains macros and a little bit of code that is common to
31945** all of the platform-specific files (os_*.c) and is #included into those
31946** files.
31947**
31948** This file should be #included by the os_*.c files only.  It is not a
31949** general purpose header file.
31950*/
31951#ifndef _OS_COMMON_H_
31952#define _OS_COMMON_H_
31953
31954/*
31955** At least two bugs have slipped in because we changed the MEMORY_DEBUG
31956** macro to SQLITE_DEBUG and some older makefiles have not yet made the
31957** switch.  The following code should catch this problem at compile-time.
31958*/
31959#ifdef MEMORY_DEBUG
31960# error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
31961#endif
31962
31963#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
31964# ifndef SQLITE_DEBUG_OS_TRACE
31965#   define SQLITE_DEBUG_OS_TRACE 0
31966# endif
31967  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
31968# define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
31969#else
31970# define OSTRACE(X)
31971#endif
31972
31973/*
31974** Macros for performance tracing.  Normally turned off.  Only works
31975** on i486 hardware.
31976*/
31977#ifdef SQLITE_PERFORMANCE_TRACE
31978
31979/*
31980** hwtime.h contains inline assembler code for implementing
31981** high-performance timing routines.
31982*/
31983/************** Include hwtime.h in the middle of os_common.h ****************/
31984/************** Begin file hwtime.h ******************************************/
31985/*
31986** 2008 May 27
31987**
31988** The author disclaims copyright to this source code.  In place of
31989** a legal notice, here is a blessing:
31990**
31991**    May you do good and not evil.
31992**    May you find forgiveness for yourself and forgive others.
31993**    May you share freely, never taking more than you give.
31994**
31995******************************************************************************
31996**
31997** This file contains inline asm code for retrieving "high-performance"
31998** counters for x86 class CPUs.
31999*/
32000#ifndef _HWTIME_H_
32001#define _HWTIME_H_
32002
32003/*
32004** The following routine only works on pentium-class (or newer) processors.
32005** It uses the RDTSC opcode to read the cycle count value out of the
32006** processor and returns that value.  This can be used for high-res
32007** profiling.
32008*/
32009#if (defined(__GNUC__) || defined(_MSC_VER)) && \
32010      (defined(i386) || defined(__i386__) || defined(_M_IX86))
32011
32012  #if defined(__GNUC__)
32013
32014  __inline__ sqlite_uint64 sqlite3Hwtime(void){
32015     unsigned int lo, hi;
32016     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
32017     return (sqlite_uint64)hi << 32 | lo;
32018  }
32019
32020  #elif defined(_MSC_VER)
32021
32022  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
32023     __asm {
32024        rdtsc
32025        ret       ; return value at EDX:EAX
32026     }
32027  }
32028
32029  #endif
32030
32031#elif (defined(__GNUC__) && defined(__x86_64__))
32032
32033  __inline__ sqlite_uint64 sqlite3Hwtime(void){
32034      unsigned long val;
32035      __asm__ __volatile__ ("rdtsc" : "=A" (val));
32036      return val;
32037  }
32038
32039#elif (defined(__GNUC__) && defined(__ppc__))
32040
32041  __inline__ sqlite_uint64 sqlite3Hwtime(void){
32042      unsigned long long retval;
32043      unsigned long junk;
32044      __asm__ __volatile__ ("\n\
32045          1:      mftbu   %1\n\
32046                  mftb    %L0\n\
32047                  mftbu   %0\n\
32048                  cmpw    %0,%1\n\
32049                  bne     1b"
32050                  : "=r" (retval), "=r" (junk));
32051      return retval;
32052  }
32053
32054#else
32055
32056  #error Need implementation of sqlite3Hwtime() for your platform.
32057
32058  /*
32059  ** To compile without implementing sqlite3Hwtime() for your platform,
32060  ** you can remove the above #error and use the following
32061  ** stub function.  You will lose timing support for many
32062  ** of the debugging and testing utilities, but it should at
32063  ** least compile and run.
32064  */
32065SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
32066
32067#endif
32068
32069#endif /* !defined(_HWTIME_H_) */
32070
32071/************** End of hwtime.h **********************************************/
32072/************** Continuing where we left off in os_common.h ******************/
32073
32074static sqlite_uint64 g_start;
32075static sqlite_uint64 g_elapsed;
32076#define TIMER_START       g_start=sqlite3Hwtime()
32077#define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
32078#define TIMER_ELAPSED     g_elapsed
32079#else
32080#define TIMER_START
32081#define TIMER_END
32082#define TIMER_ELAPSED     ((sqlite_uint64)0)
32083#endif
32084
32085/*
32086** If we compile with the SQLITE_TEST macro set, then the following block
32087** of code will give us the ability to simulate a disk I/O error.  This
32088** is used for testing the I/O recovery logic.
32089*/
32090#ifdef SQLITE_TEST
32091SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
32092SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
32093SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
32094SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
32095SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
32096SQLITE_API int sqlite3_diskfull_pending = 0;
32097SQLITE_API int sqlite3_diskfull = 0;
32098#define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
32099#define SimulateIOError(CODE)  \
32100  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
32101       || sqlite3_io_error_pending-- == 1 )  \
32102              { local_ioerr(); CODE; }
32103static void local_ioerr(){
32104  IOTRACE(("IOERR\n"));
32105  sqlite3_io_error_hit++;
32106  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
32107}
32108#define SimulateDiskfullError(CODE) \
32109   if( sqlite3_diskfull_pending ){ \
32110     if( sqlite3_diskfull_pending == 1 ){ \
32111       local_ioerr(); \
32112       sqlite3_diskfull = 1; \
32113       sqlite3_io_error_hit = 1; \
32114       CODE; \
32115     }else{ \
32116       sqlite3_diskfull_pending--; \
32117     } \
32118   }
32119#else
32120#define SimulateIOErrorBenign(X)
32121#define SimulateIOError(A)
32122#define SimulateDiskfullError(A)
32123#endif
32124
32125/*
32126** When testing, keep a count of the number of open files.
32127*/
32128#ifdef SQLITE_TEST
32129SQLITE_API int sqlite3_open_file_count = 0;
32130#define OpenCounter(X)  sqlite3_open_file_count+=(X)
32131#else
32132#define OpenCounter(X)
32133#endif
32134
32135#endif /* !defined(_OS_COMMON_H_) */
32136
32137/************** End of os_common.h *******************************************/
32138/************** Continuing where we left off in os_win.c *********************/
32139
32140/*
32141** Some Microsoft compilers lack this definition.
32142*/
32143#ifndef INVALID_FILE_ATTRIBUTES
32144# define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
32145#endif
32146
32147/* Forward references */
32148typedef struct winShm winShm;           /* A connection to shared-memory */
32149typedef struct winShmNode winShmNode;   /* A region of shared-memory */
32150
32151/*
32152** WinCE lacks native support for file locking so we have to fake it
32153** with some code of our own.
32154*/
32155#if SQLITE_OS_WINCE
32156typedef struct winceLock {
32157  int nReaders;       /* Number of reader locks obtained */
32158  BOOL bPending;      /* Indicates a pending lock has been obtained */
32159  BOOL bReserved;     /* Indicates a reserved lock has been obtained */
32160  BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
32161} winceLock;
32162#endif
32163
32164/*
32165** The winFile structure is a subclass of sqlite3_file* specific to the win32
32166** portability layer.
32167*/
32168typedef struct winFile winFile;
32169struct winFile {
32170  const sqlite3_io_methods *pMethod; /*** Must be first ***/
32171  sqlite3_vfs *pVfs;      /* The VFS used to open this file */
32172  HANDLE h;               /* Handle for accessing the file */
32173  u8 locktype;            /* Type of lock currently held on this file */
32174  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
32175  u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
32176  DWORD lastErrno;        /* The Windows errno from the last I/O error */
32177  winShm *pShm;           /* Instance of shared memory on this file */
32178  const char *zPath;      /* Full pathname of this file */
32179  int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
32180#if SQLITE_OS_WINCE
32181  LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
32182  HANDLE hMutex;          /* Mutex used to control access to shared lock */
32183  HANDLE hShared;         /* Shared memory segment used for locking */
32184  winceLock local;        /* Locks obtained by this instance of winFile */
32185  winceLock *shared;      /* Global shared lock memory for the file  */
32186#endif
32187};
32188
32189/*
32190** Allowed values for winFile.ctrlFlags
32191*/
32192#define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
32193#define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
32194
32195/*
32196 * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
32197 * various Win32 API heap functions instead of our own.
32198 */
32199#ifdef SQLITE_WIN32_MALLOC
32200/*
32201 * The initial size of the Win32-specific heap.  This value may be zero.
32202 */
32203#ifndef SQLITE_WIN32_HEAP_INIT_SIZE
32204#  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
32205                                       (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
32206#endif
32207
32208/*
32209 * The maximum size of the Win32-specific heap.  This value may be zero.
32210 */
32211#ifndef SQLITE_WIN32_HEAP_MAX_SIZE
32212#  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
32213#endif
32214
32215/*
32216 * The extra flags to use in calls to the Win32 heap APIs.  This value may be
32217 * zero for the default behavior.
32218 */
32219#ifndef SQLITE_WIN32_HEAP_FLAGS
32220#  define SQLITE_WIN32_HEAP_FLAGS     (0)
32221#endif
32222
32223/*
32224** The winMemData structure stores information required by the Win32-specific
32225** sqlite3_mem_methods implementation.
32226*/
32227typedef struct winMemData winMemData;
32228struct winMemData {
32229#ifndef NDEBUG
32230  u32 magic;    /* Magic number to detect structure corruption. */
32231#endif
32232  HANDLE hHeap; /* The handle to our heap. */
32233  BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
32234};
32235
32236#ifndef NDEBUG
32237#define WINMEM_MAGIC     0x42b2830b
32238#endif
32239
32240static struct winMemData win_mem_data = {
32241#ifndef NDEBUG
32242  WINMEM_MAGIC,
32243#endif
32244  NULL, FALSE
32245};
32246
32247#ifndef NDEBUG
32248#define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
32249#else
32250#define winMemAssertMagic()
32251#endif
32252
32253#define winMemGetHeap() win_mem_data.hHeap
32254
32255static void *winMemMalloc(int nBytes);
32256static void winMemFree(void *pPrior);
32257static void *winMemRealloc(void *pPrior, int nBytes);
32258static int winMemSize(void *p);
32259static int winMemRoundup(int n);
32260static int winMemInit(void *pAppData);
32261static void winMemShutdown(void *pAppData);
32262
32263SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
32264#endif /* SQLITE_WIN32_MALLOC */
32265
32266/*
32267** The following variable is (normally) set once and never changes
32268** thereafter.  It records whether the operating system is Win9x
32269** or WinNT.
32270**
32271** 0:   Operating system unknown.
32272** 1:   Operating system is Win9x.
32273** 2:   Operating system is WinNT.
32274**
32275** In order to facilitate testing on a WinNT system, the test fixture
32276** can manually set this value to 1 to emulate Win98 behavior.
32277*/
32278#ifdef SQLITE_TEST
32279SQLITE_API int sqlite3_os_type = 0;
32280#else
32281static int sqlite3_os_type = 0;
32282#endif
32283
32284/*
32285** Many system calls are accessed through pointer-to-functions so that
32286** they may be overridden at runtime to facilitate fault injection during
32287** testing and sandboxing.  The following array holds the names and pointers
32288** to all overrideable system calls.
32289*/
32290#if !SQLITE_OS_WINCE
32291#  define SQLITE_WIN32_HAS_ANSI
32292#endif
32293
32294#if SQLITE_OS_WINCE || SQLITE_OS_WINNT
32295#  define SQLITE_WIN32_HAS_WIDE
32296#endif
32297
32298#ifndef SYSCALL
32299#  define SYSCALL sqlite3_syscall_ptr
32300#endif
32301
32302#if SQLITE_OS_WINCE
32303/*
32304** These macros are necessary because Windows CE does not natively support the
32305** Win32 APIs LockFile, UnlockFile, and LockFileEx.
32306 */
32307
32308#  define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
32309#  define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
32310#  define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
32311
32312/*
32313** These are the special syscall hacks for Windows CE.  The locking related
32314** defines here refer to the macros defined just above.
32315 */
32316
32317#  define osAreFileApisANSI()       1
32318#  define osLockFile                LockFile
32319#  define osUnlockFile              UnlockFile
32320#  define osLockFileEx              LockFileEx
32321#endif
32322
32323static struct win_syscall {
32324  const char *zName;            /* Name of the sytem call */
32325  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
32326  sqlite3_syscall_ptr pDefault; /* Default value */
32327} aSyscall[] = {
32328#if !SQLITE_OS_WINCE
32329  { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
32330
32331#define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
32332#else
32333  { "AreFileApisANSI",         (SYSCALL)0,                       0 },
32334#endif
32335
32336#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32337  { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
32338#else
32339  { "CharLowerW",              (SYSCALL)0,                       0 },
32340#endif
32341
32342#define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
32343
32344#if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32345  { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
32346#else
32347  { "CharUpperW",              (SYSCALL)0,                       0 },
32348#endif
32349
32350#define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
32351
32352  { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
32353
32354#define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
32355
32356#if defined(SQLITE_WIN32_HAS_ANSI)
32357  { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
32358#else
32359  { "CreateFileA",             (SYSCALL)0,                       0 },
32360#endif
32361
32362#define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
32363        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
32364
32365#if defined(SQLITE_WIN32_HAS_WIDE)
32366  { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
32367#else
32368  { "CreateFileW",             (SYSCALL)0,                       0 },
32369#endif
32370
32371#define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
32372        LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
32373
32374  { "CreateFileMapping",       (SYSCALL)CreateFileMapping,       0 },
32375
32376#define osCreateFileMapping ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
32377        DWORD,DWORD,DWORD,LPCTSTR))aSyscall[6].pCurrent)
32378
32379#if defined(SQLITE_WIN32_HAS_WIDE)
32380  { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
32381#else
32382  { "CreateFileMappingW",      (SYSCALL)0,                       0 },
32383#endif
32384
32385#define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
32386        DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
32387
32388#if defined(SQLITE_WIN32_HAS_WIDE)
32389  { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
32390#else
32391  { "CreateMutexW",            (SYSCALL)0,                       0 },
32392#endif
32393
32394#define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
32395        LPCWSTR))aSyscall[8].pCurrent)
32396
32397#if defined(SQLITE_WIN32_HAS_ANSI)
32398  { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
32399#else
32400  { "DeleteFileA",             (SYSCALL)0,                       0 },
32401#endif
32402
32403#define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
32404
32405#if defined(SQLITE_WIN32_HAS_WIDE)
32406  { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
32407#else
32408  { "DeleteFileW",             (SYSCALL)0,                       0 },
32409#endif
32410
32411#define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
32412
32413#if SQLITE_OS_WINCE
32414  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
32415#else
32416  { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
32417#endif
32418
32419#define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32420        LPFILETIME))aSyscall[11].pCurrent)
32421
32422#if SQLITE_OS_WINCE
32423  { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
32424#else
32425  { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
32426#endif
32427
32428#define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
32429        LPSYSTEMTIME))aSyscall[12].pCurrent)
32430
32431  { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
32432
32433#define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
32434
32435#if defined(SQLITE_WIN32_HAS_ANSI)
32436  { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
32437#else
32438  { "FormatMessageA",          (SYSCALL)0,                       0 },
32439#endif
32440
32441#define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
32442        DWORD,va_list*))aSyscall[14].pCurrent)
32443
32444#if defined(SQLITE_WIN32_HAS_WIDE)
32445  { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
32446#else
32447  { "FormatMessageW",          (SYSCALL)0,                       0 },
32448#endif
32449
32450#define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
32451        DWORD,va_list*))aSyscall[15].pCurrent)
32452
32453  { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
32454
32455#define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
32456
32457  { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
32458
32459#define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
32460
32461#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32462  { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
32463#else
32464  { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
32465#endif
32466
32467#define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
32468        LPDWORD))aSyscall[18].pCurrent)
32469
32470#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32471  { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
32472#else
32473  { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
32474#endif
32475
32476#define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
32477        LPDWORD))aSyscall[19].pCurrent)
32478
32479#if defined(SQLITE_WIN32_HAS_ANSI)
32480  { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
32481#else
32482  { "GetFileAttributesA",      (SYSCALL)0,                       0 },
32483#endif
32484
32485#define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
32486
32487#if defined(SQLITE_WIN32_HAS_WIDE)
32488  { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
32489#else
32490  { "GetFileAttributesW",      (SYSCALL)0,                       0 },
32491#endif
32492
32493#define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
32494
32495#if defined(SQLITE_WIN32_HAS_WIDE)
32496  { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
32497#else
32498  { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
32499#endif
32500
32501#define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
32502        LPVOID))aSyscall[22].pCurrent)
32503
32504  { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
32505
32506#define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
32507
32508#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
32509  { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
32510#else
32511  { "GetFullPathNameA",        (SYSCALL)0,                       0 },
32512#endif
32513
32514#define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
32515        LPSTR*))aSyscall[24].pCurrent)
32516
32517#if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
32518  { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
32519#else
32520  { "GetFullPathNameW",        (SYSCALL)0,                       0 },
32521#endif
32522
32523#define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
32524        LPWSTR*))aSyscall[25].pCurrent)
32525
32526  { "GetLastError",            (SYSCALL)GetLastError,            0 },
32527
32528#define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
32529
32530#if SQLITE_OS_WINCE
32531  /* The GetProcAddressA() routine is only available on Windows CE. */
32532  { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
32533#else
32534  /* All other Windows platforms expect GetProcAddress() to take
32535  ** an ANSI string regardless of the _UNICODE setting */
32536  { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
32537#endif
32538
32539#define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
32540        LPCSTR))aSyscall[27].pCurrent)
32541
32542  { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
32543
32544#define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
32545
32546  { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
32547
32548#define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
32549
32550#if !SQLITE_OS_WINCE
32551  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
32552#else
32553  { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
32554#endif
32555
32556#define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
32557        LPFILETIME))aSyscall[30].pCurrent)
32558
32559#if defined(SQLITE_WIN32_HAS_ANSI)
32560  { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
32561#else
32562  { "GetTempPathA",            (SYSCALL)0,                       0 },
32563#endif
32564
32565#define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
32566
32567#if defined(SQLITE_WIN32_HAS_WIDE)
32568  { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
32569#else
32570  { "GetTempPathW",            (SYSCALL)0,                       0 },
32571#endif
32572
32573#define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
32574
32575  { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
32576
32577#define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
32578
32579#if defined(SQLITE_WIN32_HAS_ANSI)
32580  { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
32581#else
32582  { "GetVersionExA",           (SYSCALL)0,                       0 },
32583#endif
32584
32585#define osGetVersionExA ((BOOL(WINAPI*)( \
32586        LPOSVERSIONINFOA))aSyscall[34].pCurrent)
32587
32588  { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
32589
32590#define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
32591        SIZE_T))aSyscall[35].pCurrent)
32592
32593  { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
32594
32595#define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
32596        SIZE_T))aSyscall[36].pCurrent)
32597
32598  { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
32599
32600#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
32601
32602  { "HeapFree",                (SYSCALL)HeapFree,                0 },
32603
32604#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
32605
32606  { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
32607
32608#define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
32609        SIZE_T))aSyscall[39].pCurrent)
32610
32611  { "HeapSize",                (SYSCALL)HeapSize,                0 },
32612
32613#define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
32614        LPCVOID))aSyscall[40].pCurrent)
32615
32616  { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
32617
32618#define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
32619        LPCVOID))aSyscall[41].pCurrent)
32620
32621#if defined(SQLITE_WIN32_HAS_ANSI)
32622  { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
32623#else
32624  { "LoadLibraryA",            (SYSCALL)0,                       0 },
32625#endif
32626
32627#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
32628
32629#if defined(SQLITE_WIN32_HAS_WIDE)
32630  { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
32631#else
32632  { "LoadLibraryW",            (SYSCALL)0,                       0 },
32633#endif
32634
32635#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
32636
32637  { "LocalFree",               (SYSCALL)LocalFree,               0 },
32638
32639#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
32640
32641#if !SQLITE_OS_WINCE
32642  { "LockFile",                (SYSCALL)LockFile,                0 },
32643
32644#define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32645        DWORD))aSyscall[45].pCurrent)
32646#else
32647  { "LockFile",                (SYSCALL)0,                       0 },
32648#endif
32649
32650#if !SQLITE_OS_WINCE
32651  { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
32652
32653#define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
32654        LPOVERLAPPED))aSyscall[46].pCurrent)
32655#else
32656  { "LockFileEx",              (SYSCALL)0,                       0 },
32657#endif
32658
32659  { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
32660
32661#define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32662        SIZE_T))aSyscall[47].pCurrent)
32663
32664  { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
32665
32666#define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
32667        int))aSyscall[48].pCurrent)
32668
32669  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
32670
32671#define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
32672        LARGE_INTEGER*))aSyscall[49].pCurrent)
32673
32674  { "ReadFile",                (SYSCALL)ReadFile,                0 },
32675
32676#define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
32677        LPOVERLAPPED))aSyscall[50].pCurrent)
32678
32679  { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
32680
32681#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
32682
32683  { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
32684
32685#define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
32686        DWORD))aSyscall[52].pCurrent)
32687
32688  { "Sleep",                   (SYSCALL)Sleep,                   0 },
32689
32690#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
32691
32692  { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
32693
32694#define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
32695        LPFILETIME))aSyscall[54].pCurrent)
32696
32697#if !SQLITE_OS_WINCE
32698  { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
32699
32700#define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32701        DWORD))aSyscall[55].pCurrent)
32702#else
32703  { "UnlockFile",              (SYSCALL)0,                       0 },
32704#endif
32705
32706#if !SQLITE_OS_WINCE
32707  { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
32708
32709#define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
32710        LPOVERLAPPED))aSyscall[56].pCurrent)
32711#else
32712  { "UnlockFileEx",            (SYSCALL)0,                       0 },
32713#endif
32714
32715  { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
32716
32717#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
32718
32719  { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
32720
32721#define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
32722        LPCSTR,LPBOOL))aSyscall[58].pCurrent)
32723
32724  { "WriteFile",               (SYSCALL)WriteFile,               0 },
32725
32726#define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
32727        LPOVERLAPPED))aSyscall[59].pCurrent)
32728
32729}; /* End of the overrideable system calls */
32730
32731/*
32732** This is the xSetSystemCall() method of sqlite3_vfs for all of the
32733** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
32734** system call pointer, or SQLITE_NOTFOUND if there is no configurable
32735** system call named zName.
32736*/
32737static int winSetSystemCall(
32738  sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
32739  const char *zName,            /* Name of system call to override */
32740  sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
32741){
32742  unsigned int i;
32743  int rc = SQLITE_NOTFOUND;
32744
32745  UNUSED_PARAMETER(pNotUsed);
32746  if( zName==0 ){
32747    /* If no zName is given, restore all system calls to their default
32748    ** settings and return NULL
32749    */
32750    rc = SQLITE_OK;
32751    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32752      if( aSyscall[i].pDefault ){
32753        aSyscall[i].pCurrent = aSyscall[i].pDefault;
32754      }
32755    }
32756  }else{
32757    /* If zName is specified, operate on only the one system call
32758    ** specified.
32759    */
32760    for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32761      if( strcmp(zName, aSyscall[i].zName)==0 ){
32762        if( aSyscall[i].pDefault==0 ){
32763          aSyscall[i].pDefault = aSyscall[i].pCurrent;
32764        }
32765        rc = SQLITE_OK;
32766        if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
32767        aSyscall[i].pCurrent = pNewFunc;
32768        break;
32769      }
32770    }
32771  }
32772  return rc;
32773}
32774
32775/*
32776** Return the value of a system call.  Return NULL if zName is not a
32777** recognized system call name.  NULL is also returned if the system call
32778** is currently undefined.
32779*/
32780static sqlite3_syscall_ptr winGetSystemCall(
32781  sqlite3_vfs *pNotUsed,
32782  const char *zName
32783){
32784  unsigned int i;
32785
32786  UNUSED_PARAMETER(pNotUsed);
32787  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
32788    if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
32789  }
32790  return 0;
32791}
32792
32793/*
32794** Return the name of the first system call after zName.  If zName==NULL
32795** then return the name of the first system call.  Return NULL if zName
32796** is the last system call or if zName is not the name of a valid
32797** system call.
32798*/
32799static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
32800  int i = -1;
32801
32802  UNUSED_PARAMETER(p);
32803  if( zName ){
32804    for(i=0; i<ArraySize(aSyscall)-1; i++){
32805      if( strcmp(zName, aSyscall[i].zName)==0 ) break;
32806    }
32807  }
32808  for(i++; i<ArraySize(aSyscall); i++){
32809    if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
32810  }
32811  return 0;
32812}
32813
32814/*
32815** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
32816** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
32817**
32818** Here is an interesting observation:  Win95, Win98, and WinME lack
32819** the LockFileEx() API.  But we can still statically link against that
32820** API as long as we don't call it when running Win95/98/ME.  A call to
32821** this routine is used to determine if the host is Win95/98/ME or
32822** WinNT/2K/XP so that we will know whether or not we can safely call
32823** the LockFileEx() API.
32824*/
32825#if SQLITE_OS_WINCE
32826# define isNT()  (1)
32827#else
32828  static int isNT(void){
32829    if( sqlite3_os_type==0 ){
32830      OSVERSIONINFOA sInfo;
32831      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
32832      osGetVersionExA(&sInfo);
32833      sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
32834    }
32835    return sqlite3_os_type==2;
32836  }
32837#endif /* SQLITE_OS_WINCE */
32838
32839#ifdef SQLITE_WIN32_MALLOC
32840/*
32841** Allocate nBytes of memory.
32842*/
32843static void *winMemMalloc(int nBytes){
32844  HANDLE hHeap;
32845  void *p;
32846
32847  winMemAssertMagic();
32848  hHeap = winMemGetHeap();
32849  assert( hHeap!=0 );
32850  assert( hHeap!=INVALID_HANDLE_VALUE );
32851#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32852  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32853#endif
32854  assert( nBytes>=0 );
32855  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
32856  if( !p ){
32857    sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
32858                nBytes, osGetLastError(), (void*)hHeap);
32859  }
32860  return p;
32861}
32862
32863/*
32864** Free memory.
32865*/
32866static void winMemFree(void *pPrior){
32867  HANDLE hHeap;
32868
32869  winMemAssertMagic();
32870  hHeap = winMemGetHeap();
32871  assert( hHeap!=0 );
32872  assert( hHeap!=INVALID_HANDLE_VALUE );
32873#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32874  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
32875#endif
32876  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
32877  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
32878    sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
32879                pPrior, osGetLastError(), (void*)hHeap);
32880  }
32881}
32882
32883/*
32884** Change the size of an existing memory allocation
32885*/
32886static void *winMemRealloc(void *pPrior, int nBytes){
32887  HANDLE hHeap;
32888  void *p;
32889
32890  winMemAssertMagic();
32891  hHeap = winMemGetHeap();
32892  assert( hHeap!=0 );
32893  assert( hHeap!=INVALID_HANDLE_VALUE );
32894#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32895  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
32896#endif
32897  assert( nBytes>=0 );
32898  if( !pPrior ){
32899    p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
32900  }else{
32901    p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
32902  }
32903  if( !p ){
32904    sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
32905                pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
32906                (void*)hHeap);
32907  }
32908  return p;
32909}
32910
32911/*
32912** Return the size of an outstanding allocation, in bytes.
32913*/
32914static int winMemSize(void *p){
32915  HANDLE hHeap;
32916  SIZE_T n;
32917
32918  winMemAssertMagic();
32919  hHeap = winMemGetHeap();
32920  assert( hHeap!=0 );
32921  assert( hHeap!=INVALID_HANDLE_VALUE );
32922#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32923  assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32924#endif
32925  if( !p ) return 0;
32926  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
32927  if( n==(SIZE_T)-1 ){
32928    sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
32929                p, osGetLastError(), (void*)hHeap);
32930    return 0;
32931  }
32932  return (int)n;
32933}
32934
32935/*
32936** Round up a request size to the next valid allocation size.
32937*/
32938static int winMemRoundup(int n){
32939  return n;
32940}
32941
32942/*
32943** Initialize this module.
32944*/
32945static int winMemInit(void *pAppData){
32946  winMemData *pWinMemData = (winMemData *)pAppData;
32947
32948  if( !pWinMemData ) return SQLITE_ERROR;
32949  assert( pWinMemData->magic==WINMEM_MAGIC );
32950  if( !pWinMemData->hHeap ){
32951    pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
32952                                      SQLITE_WIN32_HEAP_INIT_SIZE,
32953                                      SQLITE_WIN32_HEAP_MAX_SIZE);
32954    if( !pWinMemData->hHeap ){
32955      sqlite3_log(SQLITE_NOMEM,
32956          "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
32957          osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
32958          SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
32959      return SQLITE_NOMEM;
32960    }
32961    pWinMemData->bOwned = TRUE;
32962  }
32963  assert( pWinMemData->hHeap!=0 );
32964  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
32965#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32966  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32967#endif
32968  return SQLITE_OK;
32969}
32970
32971/*
32972** Deinitialize this module.
32973*/
32974static void winMemShutdown(void *pAppData){
32975  winMemData *pWinMemData = (winMemData *)pAppData;
32976
32977  if( !pWinMemData ) return;
32978  if( pWinMemData->hHeap ){
32979    assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
32980#ifdef SQLITE_WIN32_MALLOC_VALIDATE
32981    assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
32982#endif
32983    if( pWinMemData->bOwned ){
32984      if( !osHeapDestroy(pWinMemData->hHeap) ){
32985        sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
32986                    osGetLastError(), (void*)pWinMemData->hHeap);
32987      }
32988      pWinMemData->bOwned = FALSE;
32989    }
32990    pWinMemData->hHeap = NULL;
32991  }
32992}
32993
32994/*
32995** Populate the low-level memory allocation function pointers in
32996** sqlite3GlobalConfig.m with pointers to the routines in this file. The
32997** arguments specify the block of memory to manage.
32998**
32999** This routine is only called by sqlite3_config(), and therefore
33000** is not required to be threadsafe (it is not).
33001*/
33002SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
33003  static const sqlite3_mem_methods winMemMethods = {
33004    winMemMalloc,
33005    winMemFree,
33006    winMemRealloc,
33007    winMemSize,
33008    winMemRoundup,
33009    winMemInit,
33010    winMemShutdown,
33011    &win_mem_data
33012  };
33013  return &winMemMethods;
33014}
33015
33016SQLITE_PRIVATE void sqlite3MemSetDefault(void){
33017  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
33018}
33019#endif /* SQLITE_WIN32_MALLOC */
33020
33021/*
33022** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
33023**
33024** Space to hold the returned string is obtained from malloc.
33025*/
33026static LPWSTR utf8ToUnicode(const char *zFilename){
33027  int nChar;
33028  LPWSTR zWideFilename;
33029
33030  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
33031  if( nChar==0 ){
33032    return 0;
33033  }
33034  zWideFilename = sqlite3_malloc( nChar*sizeof(zWideFilename[0]) );
33035  if( zWideFilename==0 ){
33036    return 0;
33037  }
33038  nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
33039                                nChar);
33040  if( nChar==0 ){
33041    sqlite3_free(zWideFilename);
33042    zWideFilename = 0;
33043  }
33044  return zWideFilename;
33045}
33046
33047/*
33048** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
33049** obtained from sqlite3_malloc().
33050*/
33051static char *unicodeToUtf8(LPCWSTR zWideFilename){
33052  int nByte;
33053  char *zFilename;
33054
33055  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
33056  if( nByte == 0 ){
33057    return 0;
33058  }
33059  zFilename = sqlite3_malloc( nByte );
33060  if( zFilename==0 ){
33061    return 0;
33062  }
33063  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
33064                                0, 0);
33065  if( nByte == 0 ){
33066    sqlite3_free(zFilename);
33067    zFilename = 0;
33068  }
33069  return zFilename;
33070}
33071
33072/*
33073** Convert an ANSI string to Microsoft Unicode, based on the
33074** current codepage settings for file apis.
33075**
33076** Space to hold the returned string is obtained
33077** from sqlite3_malloc.
33078*/
33079static LPWSTR mbcsToUnicode(const char *zFilename){
33080  int nByte;
33081  LPWSTR zMbcsFilename;
33082  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33083
33084  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
33085                                0)*sizeof(WCHAR);
33086  if( nByte==0 ){
33087    return 0;
33088  }
33089  zMbcsFilename = sqlite3_malloc( nByte*sizeof(zMbcsFilename[0]) );
33090  if( zMbcsFilename==0 ){
33091    return 0;
33092  }
33093  nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
33094                                nByte);
33095  if( nByte==0 ){
33096    sqlite3_free(zMbcsFilename);
33097    zMbcsFilename = 0;
33098  }
33099  return zMbcsFilename;
33100}
33101
33102/*
33103** Convert Microsoft Unicode to multi-byte character string, based on the
33104** user's ANSI codepage.
33105**
33106** Space to hold the returned string is obtained from
33107** sqlite3_malloc().
33108*/
33109static char *unicodeToMbcs(LPCWSTR zWideFilename){
33110  int nByte;
33111  char *zFilename;
33112  int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
33113
33114  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
33115  if( nByte == 0 ){
33116    return 0;
33117  }
33118  zFilename = sqlite3_malloc( nByte );
33119  if( zFilename==0 ){
33120    return 0;
33121  }
33122  nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
33123                                nByte, 0, 0);
33124  if( nByte == 0 ){
33125    sqlite3_free(zFilename);
33126    zFilename = 0;
33127  }
33128  return zFilename;
33129}
33130
33131/*
33132** Convert multibyte character string to UTF-8.  Space to hold the
33133** returned string is obtained from sqlite3_malloc().
33134*/
33135SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
33136  char *zFilenameUtf8;
33137  LPWSTR zTmpWide;
33138
33139  zTmpWide = mbcsToUnicode(zFilename);
33140  if( zTmpWide==0 ){
33141    return 0;
33142  }
33143  zFilenameUtf8 = unicodeToUtf8(zTmpWide);
33144  sqlite3_free(zTmpWide);
33145  return zFilenameUtf8;
33146}
33147
33148/*
33149** Convert UTF-8 to multibyte character string.  Space to hold the
33150** returned string is obtained from sqlite3_malloc().
33151*/
33152SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
33153  char *zFilenameMbcs;
33154  LPWSTR zTmpWide;
33155
33156  zTmpWide = utf8ToUnicode(zFilename);
33157  if( zTmpWide==0 ){
33158    return 0;
33159  }
33160  zFilenameMbcs = unicodeToMbcs(zTmpWide);
33161  sqlite3_free(zTmpWide);
33162  return zFilenameMbcs;
33163}
33164
33165
33166/*
33167** The return value of getLastErrorMsg
33168** is zero if the error message fits in the buffer, or non-zero
33169** otherwise (if the message was truncated).
33170*/
33171static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
33172  /* FormatMessage returns 0 on failure.  Otherwise it
33173  ** returns the number of TCHARs written to the output
33174  ** buffer, excluding the terminating null char.
33175  */
33176  DWORD dwLen = 0;
33177  char *zOut = 0;
33178
33179  if( isNT() ){
33180    LPWSTR zTempWide = NULL;
33181    dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33182                             FORMAT_MESSAGE_FROM_SYSTEM |
33183                             FORMAT_MESSAGE_IGNORE_INSERTS,
33184                             NULL,
33185                             lastErrno,
33186                             0,
33187                             (LPWSTR) &zTempWide,
33188                             0,
33189                             0);
33190    if( dwLen > 0 ){
33191      /* allocate a buffer and convert to UTF8 */
33192      sqlite3BeginBenignMalloc();
33193      zOut = unicodeToUtf8(zTempWide);
33194      sqlite3EndBenignMalloc();
33195      /* free the system buffer allocated by FormatMessage */
33196      osLocalFree(zTempWide);
33197    }
33198/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33199** Since the ANSI version of these Windows API do not exist for WINCE,
33200** it's important to not reference them for WINCE builds.
33201*/
33202#if SQLITE_OS_WINCE==0
33203  }else{
33204    char *zTemp = NULL;
33205    dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
33206                             FORMAT_MESSAGE_FROM_SYSTEM |
33207                             FORMAT_MESSAGE_IGNORE_INSERTS,
33208                             NULL,
33209                             lastErrno,
33210                             0,
33211                             (LPSTR) &zTemp,
33212                             0,
33213                             0);
33214    if( dwLen > 0 ){
33215      /* allocate a buffer and convert to UTF8 */
33216      sqlite3BeginBenignMalloc();
33217      zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
33218      sqlite3EndBenignMalloc();
33219      /* free the system buffer allocated by FormatMessage */
33220      osLocalFree(zTemp);
33221    }
33222#endif
33223  }
33224  if( 0 == dwLen ){
33225    sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", lastErrno, lastErrno);
33226  }else{
33227    /* copy a maximum of nBuf chars to output buffer */
33228    sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
33229    /* free the UTF8 buffer */
33230    sqlite3_free(zOut);
33231  }
33232  return 0;
33233}
33234
33235/*
33236**
33237** This function - winLogErrorAtLine() - is only ever called via the macro
33238** winLogError().
33239**
33240** This routine is invoked after an error occurs in an OS function.
33241** It logs a message using sqlite3_log() containing the current value of
33242** error code and, if possible, the human-readable equivalent from
33243** FormatMessage.
33244**
33245** The first argument passed to the macro should be the error code that
33246** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
33247** The two subsequent arguments should be the name of the OS function that
33248** failed and the the associated file-system path, if any.
33249*/
33250#define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
33251static int winLogErrorAtLine(
33252  int errcode,                    /* SQLite error code */
33253  DWORD lastErrno,                /* Win32 last error */
33254  const char *zFunc,              /* Name of OS function that failed */
33255  const char *zPath,              /* File path associated with error */
33256  int iLine                       /* Source line number where error occurred */
33257){
33258  char zMsg[500];                 /* Human readable error text */
33259  int i;                          /* Loop counter */
33260
33261  zMsg[0] = 0;
33262  getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
33263  assert( errcode!=SQLITE_OK );
33264  if( zPath==0 ) zPath = "";
33265  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
33266  zMsg[i] = 0;
33267  sqlite3_log(errcode,
33268      "os_win.c:%d: (%d) %s(%s) - %s",
33269      iLine, lastErrno, zFunc, zPath, zMsg
33270  );
33271
33272  return errcode;
33273}
33274
33275/*
33276** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
33277** will be retried following a locking error - probably caused by
33278** antivirus software.  Also the initial delay before the first retry.
33279** The delay increases linearly with each retry.
33280*/
33281#ifndef SQLITE_WIN32_IOERR_RETRY
33282# define SQLITE_WIN32_IOERR_RETRY 10
33283#endif
33284#ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
33285# define SQLITE_WIN32_IOERR_RETRY_DELAY 25
33286#endif
33287static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
33288static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
33289
33290/*
33291** If a ReadFile() or WriteFile() error occurs, invoke this routine
33292** to see if it should be retried.  Return TRUE to retry.  Return FALSE
33293** to give up with an error.
33294*/
33295static int retryIoerr(int *pnRetry, DWORD *pError){
33296  DWORD e = osGetLastError();
33297  if( *pnRetry>=win32IoerrRetry ){
33298    if( pError ){
33299      *pError = e;
33300    }
33301    return 0;
33302  }
33303  if( e==ERROR_ACCESS_DENIED ||
33304      e==ERROR_LOCK_VIOLATION ||
33305      e==ERROR_SHARING_VIOLATION ){
33306    osSleep(win32IoerrRetryDelay*(1+*pnRetry));
33307    ++*pnRetry;
33308    return 1;
33309  }
33310  if( pError ){
33311    *pError = e;
33312  }
33313  return 0;
33314}
33315
33316/*
33317** Log a I/O error retry episode.
33318*/
33319static void logIoerr(int nRetry){
33320  if( nRetry ){
33321    sqlite3_log(SQLITE_IOERR,
33322      "delayed %dms for lock/sharing conflict",
33323      win32IoerrRetryDelay*nRetry*(nRetry+1)/2
33324    );
33325  }
33326}
33327
33328#if SQLITE_OS_WINCE
33329/*************************************************************************
33330** This section contains code for WinCE only.
33331*/
33332/*
33333** Windows CE does not have a localtime() function.  So create a
33334** substitute.
33335*/
33336/* #include <time.h> */
33337struct tm *__cdecl localtime(const time_t *t)
33338{
33339  static struct tm y;
33340  FILETIME uTm, lTm;
33341  SYSTEMTIME pTm;
33342  sqlite3_int64 t64;
33343  t64 = *t;
33344  t64 = (t64 + 11644473600)*10000000;
33345  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
33346  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
33347  osFileTimeToLocalFileTime(&uTm,&lTm);
33348  osFileTimeToSystemTime(&lTm,&pTm);
33349  y.tm_year = pTm.wYear - 1900;
33350  y.tm_mon = pTm.wMonth - 1;
33351  y.tm_wday = pTm.wDayOfWeek;
33352  y.tm_mday = pTm.wDay;
33353  y.tm_hour = pTm.wHour;
33354  y.tm_min = pTm.wMinute;
33355  y.tm_sec = pTm.wSecond;
33356  return &y;
33357}
33358
33359#define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
33360
33361/*
33362** Acquire a lock on the handle h
33363*/
33364static void winceMutexAcquire(HANDLE h){
33365   DWORD dwErr;
33366   do {
33367     dwErr = WaitForSingleObject(h, INFINITE);
33368   } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
33369}
33370/*
33371** Release a lock acquired by winceMutexAcquire()
33372*/
33373#define winceMutexRelease(h) ReleaseMutex(h)
33374
33375/*
33376** Create the mutex and shared memory used for locking in the file
33377** descriptor pFile
33378*/
33379static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
33380  LPWSTR zTok;
33381  LPWSTR zName;
33382  BOOL bInit = TRUE;
33383
33384  zName = utf8ToUnicode(zFilename);
33385  if( zName==0 ){
33386    /* out of memory */
33387    return FALSE;
33388  }
33389
33390  /* Initialize the local lockdata */
33391  memset(&pFile->local, 0, sizeof(pFile->local));
33392
33393  /* Replace the backslashes from the filename and lowercase it
33394  ** to derive a mutex name. */
33395  zTok = osCharLowerW(zName);
33396  for (;*zTok;zTok++){
33397    if (*zTok == '\\') *zTok = '_';
33398  }
33399
33400  /* Create/open the named mutex */
33401  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
33402  if (!pFile->hMutex){
33403    pFile->lastErrno = osGetLastError();
33404    winLogError(SQLITE_ERROR, pFile->lastErrno, "winceCreateLock1", zFilename);
33405    sqlite3_free(zName);
33406    return FALSE;
33407  }
33408
33409  /* Acquire the mutex before continuing */
33410  winceMutexAcquire(pFile->hMutex);
33411
33412  /* Since the names of named mutexes, semaphores, file mappings etc are
33413  ** case-sensitive, take advantage of that by uppercasing the mutex name
33414  ** and using that as the shared filemapping name.
33415  */
33416  osCharUpperW(zName);
33417  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
33418                                        PAGE_READWRITE, 0, sizeof(winceLock),
33419                                        zName);
33420
33421  /* Set a flag that indicates we're the first to create the memory so it
33422  ** must be zero-initialized */
33423  if (osGetLastError() == ERROR_ALREADY_EXISTS){
33424    bInit = FALSE;
33425  }
33426
33427  sqlite3_free(zName);
33428
33429  /* If we succeeded in making the shared memory handle, map it. */
33430  if (pFile->hShared){
33431    pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
33432             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
33433    /* If mapping failed, close the shared memory handle and erase it */
33434    if (!pFile->shared){
33435      pFile->lastErrno = osGetLastError();
33436      winLogError(SQLITE_ERROR, pFile->lastErrno,
33437               "winceCreateLock2", zFilename);
33438      osCloseHandle(pFile->hShared);
33439      pFile->hShared = NULL;
33440    }
33441  }
33442
33443  /* If shared memory could not be created, then close the mutex and fail */
33444  if (pFile->hShared == NULL){
33445    winceMutexRelease(pFile->hMutex);
33446    osCloseHandle(pFile->hMutex);
33447    pFile->hMutex = NULL;
33448    return FALSE;
33449  }
33450
33451  /* Initialize the shared memory if we're supposed to */
33452  if (bInit) {
33453    memset(pFile->shared, 0, sizeof(winceLock));
33454  }
33455
33456  winceMutexRelease(pFile->hMutex);
33457  return TRUE;
33458}
33459
33460/*
33461** Destroy the part of winFile that deals with wince locks
33462*/
33463static void winceDestroyLock(winFile *pFile){
33464  if (pFile->hMutex){
33465    /* Acquire the mutex */
33466    winceMutexAcquire(pFile->hMutex);
33467
33468    /* The following blocks should probably assert in debug mode, but they
33469       are to cleanup in case any locks remained open */
33470    if (pFile->local.nReaders){
33471      pFile->shared->nReaders --;
33472    }
33473    if (pFile->local.bReserved){
33474      pFile->shared->bReserved = FALSE;
33475    }
33476    if (pFile->local.bPending){
33477      pFile->shared->bPending = FALSE;
33478    }
33479    if (pFile->local.bExclusive){
33480      pFile->shared->bExclusive = FALSE;
33481    }
33482
33483    /* De-reference and close our copy of the shared memory handle */
33484    osUnmapViewOfFile(pFile->shared);
33485    osCloseHandle(pFile->hShared);
33486
33487    /* Done with the mutex */
33488    winceMutexRelease(pFile->hMutex);
33489    osCloseHandle(pFile->hMutex);
33490    pFile->hMutex = NULL;
33491  }
33492}
33493
33494/*
33495** An implementation of the LockFile() API of Windows for CE
33496*/
33497static BOOL winceLockFile(
33498  HANDLE *phFile,
33499  DWORD dwFileOffsetLow,
33500  DWORD dwFileOffsetHigh,
33501  DWORD nNumberOfBytesToLockLow,
33502  DWORD nNumberOfBytesToLockHigh
33503){
33504  winFile *pFile = HANDLE_TO_WINFILE(phFile);
33505  BOOL bReturn = FALSE;
33506
33507  UNUSED_PARAMETER(dwFileOffsetHigh);
33508  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
33509
33510  if (!pFile->hMutex) return TRUE;
33511  winceMutexAcquire(pFile->hMutex);
33512
33513  /* Wanting an exclusive lock? */
33514  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
33515       && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
33516    if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
33517       pFile->shared->bExclusive = TRUE;
33518       pFile->local.bExclusive = TRUE;
33519       bReturn = TRUE;
33520    }
33521  }
33522
33523  /* Want a read-only lock? */
33524  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
33525           nNumberOfBytesToLockLow == 1){
33526    if (pFile->shared->bExclusive == 0){
33527      pFile->local.nReaders ++;
33528      if (pFile->local.nReaders == 1){
33529        pFile->shared->nReaders ++;
33530      }
33531      bReturn = TRUE;
33532    }
33533  }
33534
33535  /* Want a pending lock? */
33536  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
33537    /* If no pending lock has been acquired, then acquire it */
33538    if (pFile->shared->bPending == 0) {
33539      pFile->shared->bPending = TRUE;
33540      pFile->local.bPending = TRUE;
33541      bReturn = TRUE;
33542    }
33543  }
33544
33545  /* Want a reserved lock? */
33546  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
33547    if (pFile->shared->bReserved == 0) {
33548      pFile->shared->bReserved = TRUE;
33549      pFile->local.bReserved = TRUE;
33550      bReturn = TRUE;
33551    }
33552  }
33553
33554  winceMutexRelease(pFile->hMutex);
33555  return bReturn;
33556}
33557
33558/*
33559** An implementation of the UnlockFile API of Windows for CE
33560*/
33561static BOOL winceUnlockFile(
33562  HANDLE *phFile,
33563  DWORD dwFileOffsetLow,
33564  DWORD dwFileOffsetHigh,
33565  DWORD nNumberOfBytesToUnlockLow,
33566  DWORD nNumberOfBytesToUnlockHigh
33567){
33568  winFile *pFile = HANDLE_TO_WINFILE(phFile);
33569  BOOL bReturn = FALSE;
33570
33571  UNUSED_PARAMETER(dwFileOffsetHigh);
33572  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
33573
33574  if (!pFile->hMutex) return TRUE;
33575  winceMutexAcquire(pFile->hMutex);
33576
33577  /* Releasing a reader lock or an exclusive lock */
33578  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
33579    /* Did we have an exclusive lock? */
33580    if (pFile->local.bExclusive){
33581      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
33582      pFile->local.bExclusive = FALSE;
33583      pFile->shared->bExclusive = FALSE;
33584      bReturn = TRUE;
33585    }
33586
33587    /* Did we just have a reader lock? */
33588    else if (pFile->local.nReaders){
33589      assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
33590      pFile->local.nReaders --;
33591      if (pFile->local.nReaders == 0)
33592      {
33593        pFile->shared->nReaders --;
33594      }
33595      bReturn = TRUE;
33596    }
33597  }
33598
33599  /* Releasing a pending lock */
33600  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
33601    if (pFile->local.bPending){
33602      pFile->local.bPending = FALSE;
33603      pFile->shared->bPending = FALSE;
33604      bReturn = TRUE;
33605    }
33606  }
33607  /* Releasing a reserved lock */
33608  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
33609    if (pFile->local.bReserved) {
33610      pFile->local.bReserved = FALSE;
33611      pFile->shared->bReserved = FALSE;
33612      bReturn = TRUE;
33613    }
33614  }
33615
33616  winceMutexRelease(pFile->hMutex);
33617  return bReturn;
33618}
33619
33620/*
33621** An implementation of the LockFileEx() API of Windows for CE
33622*/
33623static BOOL winceLockFileEx(
33624  HANDLE *phFile,
33625  DWORD dwFlags,
33626  DWORD dwReserved,
33627  DWORD nNumberOfBytesToLockLow,
33628  DWORD nNumberOfBytesToLockHigh,
33629  LPOVERLAPPED lpOverlapped
33630){
33631  UNUSED_PARAMETER(dwReserved);
33632  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
33633
33634  /* If the caller wants a shared read lock, forward this call
33635  ** to winceLockFile */
33636  if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
33637      dwFlags == 1 &&
33638      nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
33639    return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
33640  }
33641  return FALSE;
33642}
33643/*
33644** End of the special code for wince
33645*****************************************************************************/
33646#endif /* SQLITE_OS_WINCE */
33647
33648/*****************************************************************************
33649** The next group of routines implement the I/O methods specified
33650** by the sqlite3_io_methods object.
33651******************************************************************************/
33652
33653/*
33654** Some Microsoft compilers lack this definition.
33655*/
33656#ifndef INVALID_SET_FILE_POINTER
33657# define INVALID_SET_FILE_POINTER ((DWORD)-1)
33658#endif
33659
33660/*
33661** Move the current position of the file handle passed as the first
33662** argument to offset iOffset within the file. If successful, return 0.
33663** Otherwise, set pFile->lastErrno and return non-zero.
33664*/
33665static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
33666  LONG upperBits;                 /* Most sig. 32 bits of new offset */
33667  LONG lowerBits;                 /* Least sig. 32 bits of new offset */
33668  DWORD dwRet;                    /* Value returned by SetFilePointer() */
33669  DWORD lastErrno;                /* Value returned by GetLastError() */
33670
33671  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
33672  lowerBits = (LONG)(iOffset & 0xffffffff);
33673
33674  /* API oddity: If successful, SetFilePointer() returns a dword
33675  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
33676  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
33677  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
33678  ** whether an error has actually occured, it is also necessary to call
33679  ** GetLastError().
33680  */
33681  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
33682
33683  if( (dwRet==INVALID_SET_FILE_POINTER
33684      && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
33685    pFile->lastErrno = lastErrno;
33686    winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
33687             "seekWinFile", pFile->zPath);
33688    return 1;
33689  }
33690
33691  return 0;
33692}
33693
33694/*
33695** Close a file.
33696**
33697** It is reported that an attempt to close a handle might sometimes
33698** fail.  This is a very unreasonable result, but Windows is notorious
33699** for being unreasonable so I do not doubt that it might happen.  If
33700** the close fails, we pause for 100 milliseconds and try again.  As
33701** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
33702** giving up and returning an error.
33703*/
33704#define MX_CLOSE_ATTEMPT 3
33705static int winClose(sqlite3_file *id){
33706  int rc, cnt = 0;
33707  winFile *pFile = (winFile*)id;
33708
33709  assert( id!=0 );
33710  assert( pFile->pShm==0 );
33711  OSTRACE(("CLOSE %d\n", pFile->h));
33712  do{
33713    rc = osCloseHandle(pFile->h);
33714    /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
33715  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (osSleep(100), 1) );
33716#if SQLITE_OS_WINCE
33717#define WINCE_DELETION_ATTEMPTS 3
33718  winceDestroyLock(pFile);
33719  if( pFile->zDeleteOnClose ){
33720    int cnt = 0;
33721    while(
33722           osDeleteFileW(pFile->zDeleteOnClose)==0
33723        && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
33724        && cnt++ < WINCE_DELETION_ATTEMPTS
33725    ){
33726       osSleep(100);  /* Wait a little before trying again */
33727    }
33728    sqlite3_free(pFile->zDeleteOnClose);
33729  }
33730#endif
33731  OSTRACE(("CLOSE %d %s\n", pFile->h, rc ? "ok" : "failed"));
33732  OpenCounter(-1);
33733  return rc ? SQLITE_OK
33734            : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
33735                          "winClose", pFile->zPath);
33736}
33737
33738/*
33739** Read data from a file into a buffer.  Return SQLITE_OK if all
33740** bytes were read successfully and SQLITE_IOERR if anything goes
33741** wrong.
33742*/
33743static int winRead(
33744  sqlite3_file *id,          /* File to read from */
33745  void *pBuf,                /* Write content into this buffer */
33746  int amt,                   /* Number of bytes to read */
33747  sqlite3_int64 offset       /* Begin reading at this offset */
33748){
33749  winFile *pFile = (winFile*)id;  /* file handle */
33750  DWORD nRead;                    /* Number of bytes actually read from file */
33751  int nRetry = 0;                 /* Number of retrys */
33752
33753  assert( id!=0 );
33754  SimulateIOError(return SQLITE_IOERR_READ);
33755  OSTRACE(("READ %d lock=%d\n", pFile->h, pFile->locktype));
33756
33757  if( seekWinFile(pFile, offset) ){
33758    return SQLITE_FULL;
33759  }
33760  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
33761    DWORD lastErrno;
33762    if( retryIoerr(&nRetry, &lastErrno) ) continue;
33763    pFile->lastErrno = lastErrno;
33764    return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
33765             "winRead", pFile->zPath);
33766  }
33767  logIoerr(nRetry);
33768  if( nRead<(DWORD)amt ){
33769    /* Unread parts of the buffer must be zero-filled */
33770    memset(&((char*)pBuf)[nRead], 0, amt-nRead);
33771    return SQLITE_IOERR_SHORT_READ;
33772  }
33773
33774  return SQLITE_OK;
33775}
33776
33777/*
33778** Write data from a buffer into a file.  Return SQLITE_OK on success
33779** or some other error code on failure.
33780*/
33781static int winWrite(
33782  sqlite3_file *id,               /* File to write into */
33783  const void *pBuf,               /* The bytes to be written */
33784  int amt,                        /* Number of bytes to write */
33785  sqlite3_int64 offset            /* Offset into the file to begin writing at */
33786){
33787  int rc;                         /* True if error has occured, else false */
33788  winFile *pFile = (winFile*)id;  /* File handle */
33789  int nRetry = 0;                 /* Number of retries */
33790
33791  assert( amt>0 );
33792  assert( pFile );
33793  SimulateIOError(return SQLITE_IOERR_WRITE);
33794  SimulateDiskfullError(return SQLITE_FULL);
33795
33796  OSTRACE(("WRITE %d lock=%d\n", pFile->h, pFile->locktype));
33797
33798  rc = seekWinFile(pFile, offset);
33799  if( rc==0 ){
33800    u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
33801    int nRem = amt;               /* Number of bytes yet to be written */
33802    DWORD nWrite;                 /* Bytes written by each WriteFile() call */
33803    DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
33804
33805    while( nRem>0 ){
33806      if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
33807        if( retryIoerr(&nRetry, &lastErrno) ) continue;
33808        break;
33809      }
33810      if( nWrite<=0 ) break;
33811      aRem += nWrite;
33812      nRem -= nWrite;
33813    }
33814    if( nRem>0 ){
33815      pFile->lastErrno = lastErrno;
33816      rc = 1;
33817    }
33818  }
33819
33820  if( rc ){
33821    if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
33822       || ( pFile->lastErrno==ERROR_DISK_FULL )){
33823      return SQLITE_FULL;
33824    }
33825    return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
33826             "winWrite", pFile->zPath);
33827  }else{
33828    logIoerr(nRetry);
33829  }
33830  return SQLITE_OK;
33831}
33832
33833/*
33834** Truncate an open file to a specified size
33835*/
33836static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
33837  winFile *pFile = (winFile*)id;  /* File handle object */
33838  int rc = SQLITE_OK;             /* Return code for this function */
33839
33840  assert( pFile );
33841
33842  OSTRACE(("TRUNCATE %d %lld\n", pFile->h, nByte));
33843  SimulateIOError(return SQLITE_IOERR_TRUNCATE);
33844
33845  /* If the user has configured a chunk-size for this file, truncate the
33846  ** file so that it consists of an integer number of chunks (i.e. the
33847  ** actual file size after the operation may be larger than the requested
33848  ** size).
33849  */
33850  if( pFile->szChunk>0 ){
33851    nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
33852  }
33853
33854  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
33855  if( seekWinFile(pFile, nByte) ){
33856    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33857             "winTruncate1", pFile->zPath);
33858  }else if( 0==osSetEndOfFile(pFile->h) ){
33859    pFile->lastErrno = osGetLastError();
33860    rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33861             "winTruncate2", pFile->zPath);
33862  }
33863
33864  OSTRACE(("TRUNCATE %d %lld %s\n", pFile->h, nByte, rc ? "failed" : "ok"));
33865  return rc;
33866}
33867
33868#ifdef SQLITE_TEST
33869/*
33870** Count the number of fullsyncs and normal syncs.  This is used to test
33871** that syncs and fullsyncs are occuring at the right times.
33872*/
33873SQLITE_API int sqlite3_sync_count = 0;
33874SQLITE_API int sqlite3_fullsync_count = 0;
33875#endif
33876
33877/*
33878** Make sure all writes to a particular file are committed to disk.
33879*/
33880static int winSync(sqlite3_file *id, int flags){
33881#ifndef SQLITE_NO_SYNC
33882  /*
33883  ** Used only when SQLITE_NO_SYNC is not defined.
33884   */
33885  BOOL rc;
33886#endif
33887#if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
33888    (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
33889  /*
33890  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
33891  ** OSTRACE() macros.
33892   */
33893  winFile *pFile = (winFile*)id;
33894#else
33895  UNUSED_PARAMETER(id);
33896#endif
33897
33898  assert( pFile );
33899  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33900  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33901      || (flags&0x0F)==SQLITE_SYNC_FULL
33902  );
33903
33904  OSTRACE(("SYNC %d lock=%d\n", pFile->h, pFile->locktype));
33905
33906  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33907  ** line is to test that doing so does not cause any problems.
33908  */
33909  SimulateDiskfullError( return SQLITE_FULL );
33910
33911#ifndef SQLITE_TEST
33912  UNUSED_PARAMETER(flags);
33913#else
33914  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
33915    sqlite3_fullsync_count++;
33916  }
33917  sqlite3_sync_count++;
33918#endif
33919
33920  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33921  ** no-op
33922  */
33923#ifdef SQLITE_NO_SYNC
33924  return SQLITE_OK;
33925#else
33926  rc = osFlushFileBuffers(pFile->h);
33927  SimulateIOError( rc=FALSE );
33928  if( rc ){
33929    return SQLITE_OK;
33930  }else{
33931    pFile->lastErrno = osGetLastError();
33932    return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
33933             "winSync", pFile->zPath);
33934  }
33935#endif
33936}
33937
33938/*
33939** Determine the current size of a file in bytes
33940*/
33941static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
33942  DWORD upperBits;
33943  DWORD lowerBits;
33944  winFile *pFile = (winFile*)id;
33945  DWORD lastErrno;
33946
33947  assert( id!=0 );
33948  SimulateIOError(return SQLITE_IOERR_FSTAT);
33949  lowerBits = osGetFileSize(pFile->h, &upperBits);
33950  if(   (lowerBits == INVALID_FILE_SIZE)
33951     && ((lastErrno = osGetLastError())!=NO_ERROR) )
33952  {
33953    pFile->lastErrno = lastErrno;
33954    return winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33955             "winFileSize", pFile->zPath);
33956  }
33957  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
33958  return SQLITE_OK;
33959}
33960
33961/*
33962** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
33963*/
33964#ifndef LOCKFILE_FAIL_IMMEDIATELY
33965# define LOCKFILE_FAIL_IMMEDIATELY 1
33966#endif
33967
33968/*
33969** Acquire a reader lock.
33970** Different API routines are called depending on whether or not this
33971** is Win9x or WinNT.
33972*/
33973static int getReadLock(winFile *pFile){
33974  int res;
33975  if( isNT() ){
33976    OVERLAPPED ovlp;
33977    ovlp.Offset = SHARED_FIRST;
33978    ovlp.OffsetHigh = 0;
33979    ovlp.hEvent = 0;
33980    res = osLockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
33981                       0, SHARED_SIZE, 0, &ovlp);
33982/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
33983*/
33984#if SQLITE_OS_WINCE==0
33985  }else{
33986    int lk;
33987    sqlite3_randomness(sizeof(lk), &lk);
33988    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
33989    res = osLockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
33990#endif
33991  }
33992  if( res == 0 ){
33993    pFile->lastErrno = osGetLastError();
33994    /* No need to log a failure to lock */
33995  }
33996  return res;
33997}
33998
33999/*
34000** Undo a readlock
34001*/
34002static int unlockReadLock(winFile *pFile){
34003  int res;
34004  DWORD lastErrno;
34005  if( isNT() ){
34006    res = osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34007/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
34008*/
34009#if SQLITE_OS_WINCE==0
34010  }else{
34011    res = osUnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
34012#endif
34013  }
34014  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
34015    pFile->lastErrno = lastErrno;
34016    winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
34017             "unlockReadLock", pFile->zPath);
34018  }
34019  return res;
34020}
34021
34022/*
34023** Lock the file with the lock specified by parameter locktype - one
34024** of the following:
34025**
34026**     (1) SHARED_LOCK
34027**     (2) RESERVED_LOCK
34028**     (3) PENDING_LOCK
34029**     (4) EXCLUSIVE_LOCK
34030**
34031** Sometimes when requesting one lock state, additional lock states
34032** are inserted in between.  The locking might fail on one of the later
34033** transitions leaving the lock state different from what it started but
34034** still short of its goal.  The following chart shows the allowed
34035** transitions and the inserted intermediate states:
34036**
34037**    UNLOCKED -> SHARED
34038**    SHARED -> RESERVED
34039**    SHARED -> (PENDING) -> EXCLUSIVE
34040**    RESERVED -> (PENDING) -> EXCLUSIVE
34041**    PENDING -> EXCLUSIVE
34042**
34043** This routine will only increase a lock.  The winUnlock() routine
34044** erases all locks at once and returns us immediately to locking level 0.
34045** It is not possible to lower the locking level one step at a time.  You
34046** must go straight to locking level 0.
34047*/
34048static int winLock(sqlite3_file *id, int locktype){
34049  int rc = SQLITE_OK;    /* Return code from subroutines */
34050  int res = 1;           /* Result of a Windows lock call */
34051  int newLocktype;       /* Set pFile->locktype to this value before exiting */
34052  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
34053  winFile *pFile = (winFile*)id;
34054  DWORD lastErrno = NO_ERROR;
34055
34056  assert( id!=0 );
34057  OSTRACE(("LOCK %d %d was %d(%d)\n",
34058           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte));
34059
34060  /* If there is already a lock of this type or more restrictive on the
34061  ** OsFile, do nothing. Don't use the end_lock: exit path, as
34062  ** sqlite3OsEnterMutex() hasn't been called yet.
34063  */
34064  if( pFile->locktype>=locktype ){
34065    return SQLITE_OK;
34066  }
34067
34068  /* Make sure the locking sequence is correct
34069  */
34070  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
34071  assert( locktype!=PENDING_LOCK );
34072  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
34073
34074  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
34075  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
34076  ** the PENDING_LOCK byte is temporary.
34077  */
34078  newLocktype = pFile->locktype;
34079  if(   (pFile->locktype==NO_LOCK)
34080     || (   (locktype==EXCLUSIVE_LOCK)
34081         && (pFile->locktype==RESERVED_LOCK))
34082  ){
34083    int cnt = 3;
34084    while( cnt-->0 && (res = osLockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
34085      /* Try 3 times to get the pending lock.  This is needed to work
34086      ** around problems caused by indexing and/or anti-virus software on
34087      ** Windows systems.
34088      ** If you are using this code as a model for alternative VFSes, do not
34089      ** copy this retry logic.  It is a hack intended for Windows only.
34090      */
34091      OSTRACE(("could not get a PENDING lock. cnt=%d\n", cnt));
34092      if( cnt ) osSleep(1);
34093    }
34094    gotPendingLock = res;
34095    if( !res ){
34096      lastErrno = osGetLastError();
34097    }
34098  }
34099
34100  /* Acquire a shared lock
34101  */
34102  if( locktype==SHARED_LOCK && res ){
34103    assert( pFile->locktype==NO_LOCK );
34104    res = getReadLock(pFile);
34105    if( res ){
34106      newLocktype = SHARED_LOCK;
34107    }else{
34108      lastErrno = osGetLastError();
34109    }
34110  }
34111
34112  /* Acquire a RESERVED lock
34113  */
34114  if( locktype==RESERVED_LOCK && res ){
34115    assert( pFile->locktype==SHARED_LOCK );
34116    res = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
34117    if( res ){
34118      newLocktype = RESERVED_LOCK;
34119    }else{
34120      lastErrno = osGetLastError();
34121    }
34122  }
34123
34124  /* Acquire a PENDING lock
34125  */
34126  if( locktype==EXCLUSIVE_LOCK && res ){
34127    newLocktype = PENDING_LOCK;
34128    gotPendingLock = 0;
34129  }
34130
34131  /* Acquire an EXCLUSIVE lock
34132  */
34133  if( locktype==EXCLUSIVE_LOCK && res ){
34134    assert( pFile->locktype>=SHARED_LOCK );
34135    res = unlockReadLock(pFile);
34136    OSTRACE(("unreadlock = %d\n", res));
34137    res = osLockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34138    if( res ){
34139      newLocktype = EXCLUSIVE_LOCK;
34140    }else{
34141      lastErrno = osGetLastError();
34142      OSTRACE(("error-code = %d\n", lastErrno));
34143      getReadLock(pFile);
34144    }
34145  }
34146
34147  /* If we are holding a PENDING lock that ought to be released, then
34148  ** release it now.
34149  */
34150  if( gotPendingLock && locktype==SHARED_LOCK ){
34151    osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
34152  }
34153
34154  /* Update the state of the lock has held in the file descriptor then
34155  ** return the appropriate result code.
34156  */
34157  if( res ){
34158    rc = SQLITE_OK;
34159  }else{
34160    OSTRACE(("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
34161           locktype, newLocktype));
34162    pFile->lastErrno = lastErrno;
34163    rc = SQLITE_BUSY;
34164  }
34165  pFile->locktype = (u8)newLocktype;
34166  return rc;
34167}
34168
34169/*
34170** This routine checks if there is a RESERVED lock held on the specified
34171** file by this or any other process. If such a lock is held, return
34172** non-zero, otherwise zero.
34173*/
34174static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
34175  int rc;
34176  winFile *pFile = (winFile*)id;
34177
34178  SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
34179
34180  assert( id!=0 );
34181  if( pFile->locktype>=RESERVED_LOCK ){
34182    rc = 1;
34183    OSTRACE(("TEST WR-LOCK %d %d (local)\n", pFile->h, rc));
34184  }else{
34185    rc = osLockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
34186    if( rc ){
34187      osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
34188    }
34189    rc = !rc;
34190    OSTRACE(("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc));
34191  }
34192  *pResOut = rc;
34193  return SQLITE_OK;
34194}
34195
34196/*
34197** Lower the locking level on file descriptor id to locktype.  locktype
34198** must be either NO_LOCK or SHARED_LOCK.
34199**
34200** If the locking level of the file descriptor is already at or below
34201** the requested locking level, this routine is a no-op.
34202**
34203** It is not possible for this routine to fail if the second argument
34204** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
34205** might return SQLITE_IOERR;
34206*/
34207static int winUnlock(sqlite3_file *id, int locktype){
34208  int type;
34209  winFile *pFile = (winFile*)id;
34210  int rc = SQLITE_OK;
34211  assert( pFile!=0 );
34212  assert( locktype<=SHARED_LOCK );
34213  OSTRACE(("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
34214          pFile->locktype, pFile->sharedLockByte));
34215  type = pFile->locktype;
34216  if( type>=EXCLUSIVE_LOCK ){
34217    osUnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
34218    if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
34219      /* This should never happen.  We should always be able to
34220      ** reacquire the read lock */
34221      rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
34222               "winUnlock", pFile->zPath);
34223    }
34224  }
34225  if( type>=RESERVED_LOCK ){
34226    osUnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
34227  }
34228  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
34229    unlockReadLock(pFile);
34230  }
34231  if( type>=PENDING_LOCK ){
34232    osUnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
34233  }
34234  pFile->locktype = (u8)locktype;
34235  return rc;
34236}
34237
34238/*
34239** If *pArg is inititially negative then this is a query.  Set *pArg to
34240** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
34241**
34242** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
34243*/
34244static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
34245  if( *pArg<0 ){
34246    *pArg = (pFile->ctrlFlags & mask)!=0;
34247  }else if( (*pArg)==0 ){
34248    pFile->ctrlFlags &= ~mask;
34249  }else{
34250    pFile->ctrlFlags |= mask;
34251  }
34252}
34253
34254/*
34255** Control and query of the open file handle.
34256*/
34257static int winFileControl(sqlite3_file *id, int op, void *pArg){
34258  winFile *pFile = (winFile*)id;
34259  switch( op ){
34260    case SQLITE_FCNTL_LOCKSTATE: {
34261      *(int*)pArg = pFile->locktype;
34262      return SQLITE_OK;
34263    }
34264    case SQLITE_LAST_ERRNO: {
34265      *(int*)pArg = (int)pFile->lastErrno;
34266      return SQLITE_OK;
34267    }
34268    case SQLITE_FCNTL_CHUNK_SIZE: {
34269      pFile->szChunk = *(int *)pArg;
34270      return SQLITE_OK;
34271    }
34272    case SQLITE_FCNTL_SIZE_HINT: {
34273      if( pFile->szChunk>0 ){
34274        sqlite3_int64 oldSz;
34275        int rc = winFileSize(id, &oldSz);
34276        if( rc==SQLITE_OK ){
34277          sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
34278          if( newSz>oldSz ){
34279            SimulateIOErrorBenign(1);
34280            rc = winTruncate(id, newSz);
34281            SimulateIOErrorBenign(0);
34282          }
34283        }
34284        return rc;
34285      }
34286      return SQLITE_OK;
34287    }
34288    case SQLITE_FCNTL_PERSIST_WAL: {
34289      winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
34290      return SQLITE_OK;
34291    }
34292    case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
34293      winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
34294      return SQLITE_OK;
34295    }
34296    case SQLITE_FCNTL_VFSNAME: {
34297      *(char**)pArg = sqlite3_mprintf("win32");
34298      return SQLITE_OK;
34299    }
34300    case SQLITE_FCNTL_WIN32_AV_RETRY: {
34301      int *a = (int*)pArg;
34302      if( a[0]>0 ){
34303        win32IoerrRetry = a[0];
34304      }else{
34305        a[0] = win32IoerrRetry;
34306      }
34307      if( a[1]>0 ){
34308        win32IoerrRetryDelay = a[1];
34309      }else{
34310        a[1] = win32IoerrRetryDelay;
34311      }
34312      return SQLITE_OK;
34313    }
34314  }
34315  return SQLITE_NOTFOUND;
34316}
34317
34318/*
34319** Return the sector size in bytes of the underlying block device for
34320** the specified file. This is almost always 512 bytes, but may be
34321** larger for some devices.
34322**
34323** SQLite code assumes this function cannot fail. It also assumes that
34324** if two files are created in the same file-system directory (i.e.
34325** a database and its journal file) that the sector size will be the
34326** same for both.
34327*/
34328static int winSectorSize(sqlite3_file *id){
34329  (void)id;
34330  return SQLITE_DEFAULT_SECTOR_SIZE;
34331}
34332
34333/*
34334** Return a vector of device characteristics.
34335*/
34336static int winDeviceCharacteristics(sqlite3_file *id){
34337  winFile *p = (winFile*)id;
34338  return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
34339         ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
34340}
34341
34342#ifndef SQLITE_OMIT_WAL
34343
34344/*
34345** Windows will only let you create file view mappings
34346** on allocation size granularity boundaries.
34347** During sqlite3_os_init() we do a GetSystemInfo()
34348** to get the granularity size.
34349*/
34350SYSTEM_INFO winSysInfo;
34351
34352/*
34353** Helper functions to obtain and relinquish the global mutex. The
34354** global mutex is used to protect the winLockInfo objects used by
34355** this file, all of which may be shared by multiple threads.
34356**
34357** Function winShmMutexHeld() is used to assert() that the global mutex
34358** is held when required. This function is only used as part of assert()
34359** statements. e.g.
34360**
34361**   winShmEnterMutex()
34362**     assert( winShmMutexHeld() );
34363**   winShmLeaveMutex()
34364*/
34365static void winShmEnterMutex(void){
34366  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34367}
34368static void winShmLeaveMutex(void){
34369  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34370}
34371#ifdef SQLITE_DEBUG
34372static int winShmMutexHeld(void) {
34373  return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
34374}
34375#endif
34376
34377/*
34378** Object used to represent a single file opened and mmapped to provide
34379** shared memory.  When multiple threads all reference the same
34380** log-summary, each thread has its own winFile object, but they all
34381** point to a single instance of this object.  In other words, each
34382** log-summary is opened only once per process.
34383**
34384** winShmMutexHeld() must be true when creating or destroying
34385** this object or while reading or writing the following fields:
34386**
34387**      nRef
34388**      pNext
34389**
34390** The following fields are read-only after the object is created:
34391**
34392**      fid
34393**      zFilename
34394**
34395** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
34396** winShmMutexHeld() is true when reading or writing any other field
34397** in this structure.
34398**
34399*/
34400struct winShmNode {
34401  sqlite3_mutex *mutex;      /* Mutex to access this object */
34402  char *zFilename;           /* Name of the file */
34403  winFile hFile;             /* File handle from winOpen */
34404
34405  int szRegion;              /* Size of shared-memory regions */
34406  int nRegion;               /* Size of array apRegion */
34407  struct ShmRegion {
34408    HANDLE hMap;             /* File handle from CreateFileMapping */
34409    void *pMap;
34410  } *aRegion;
34411  DWORD lastErrno;           /* The Windows errno from the last I/O error */
34412
34413  int nRef;                  /* Number of winShm objects pointing to this */
34414  winShm *pFirst;            /* All winShm objects pointing to this */
34415  winShmNode *pNext;         /* Next in list of all winShmNode objects */
34416#ifdef SQLITE_DEBUG
34417  u8 nextShmId;              /* Next available winShm.id value */
34418#endif
34419};
34420
34421/*
34422** A global array of all winShmNode objects.
34423**
34424** The winShmMutexHeld() must be true while reading or writing this list.
34425*/
34426static winShmNode *winShmNodeList = 0;
34427
34428/*
34429** Structure used internally by this VFS to record the state of an
34430** open shared memory connection.
34431**
34432** The following fields are initialized when this object is created and
34433** are read-only thereafter:
34434**
34435**    winShm.pShmNode
34436**    winShm.id
34437**
34438** All other fields are read/write.  The winShm.pShmNode->mutex must be held
34439** while accessing any read/write fields.
34440*/
34441struct winShm {
34442  winShmNode *pShmNode;      /* The underlying winShmNode object */
34443  winShm *pNext;             /* Next winShm with the same winShmNode */
34444  u8 hasMutex;               /* True if holding the winShmNode mutex */
34445  u16 sharedMask;            /* Mask of shared locks held */
34446  u16 exclMask;              /* Mask of exclusive locks held */
34447#ifdef SQLITE_DEBUG
34448  u8 id;                     /* Id of this connection with its winShmNode */
34449#endif
34450};
34451
34452/*
34453** Constants used for locking
34454*/
34455#define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
34456#define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
34457
34458/*
34459** Apply advisory locks for all n bytes beginning at ofst.
34460*/
34461#define _SHM_UNLCK  1
34462#define _SHM_RDLCK  2
34463#define _SHM_WRLCK  3
34464static int winShmSystemLock(
34465  winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
34466  int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
34467  int ofst,             /* Offset to first byte to be locked/unlocked */
34468  int nByte             /* Number of bytes to lock or unlock */
34469){
34470  OVERLAPPED ovlp;
34471  DWORD dwFlags;
34472  int rc = 0;           /* Result code form Lock/UnlockFileEx() */
34473
34474  /* Access to the winShmNode object is serialized by the caller */
34475  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
34476
34477  /* Initialize the locking parameters */
34478  dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
34479  if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
34480
34481  memset(&ovlp, 0, sizeof(OVERLAPPED));
34482  ovlp.Offset = ofst;
34483
34484  /* Release/Acquire the system-level lock */
34485  if( lockType==_SHM_UNLCK ){
34486    rc = osUnlockFileEx(pFile->hFile.h, 0, nByte, 0, &ovlp);
34487  }else{
34488    rc = osLockFileEx(pFile->hFile.h, dwFlags, 0, nByte, 0, &ovlp);
34489  }
34490
34491  if( rc!= 0 ){
34492    rc = SQLITE_OK;
34493  }else{
34494    pFile->lastErrno =  osGetLastError();
34495    rc = SQLITE_BUSY;
34496  }
34497
34498  OSTRACE(("SHM-LOCK %d %s %s 0x%08lx\n",
34499           pFile->hFile.h,
34500           rc==SQLITE_OK ? "ok" : "failed",
34501           lockType==_SHM_UNLCK ? "UnlockFileEx" : "LockFileEx",
34502           pFile->lastErrno));
34503
34504  return rc;
34505}
34506
34507/* Forward references to VFS methods */
34508static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
34509static int winDelete(sqlite3_vfs *,const char*,int);
34510
34511/*
34512** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
34513**
34514** This is not a VFS shared-memory method; it is a utility function called
34515** by VFS shared-memory methods.
34516*/
34517static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
34518  winShmNode **pp;
34519  winShmNode *p;
34520  BOOL bRc;
34521  assert( winShmMutexHeld() );
34522  pp = &winShmNodeList;
34523  while( (p = *pp)!=0 ){
34524    if( p->nRef==0 ){
34525      int i;
34526      if( p->mutex ) sqlite3_mutex_free(p->mutex);
34527      for(i=0; i<p->nRegion; i++){
34528        bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
34529        OSTRACE(("SHM-PURGE pid-%d unmap region=%d %s\n",
34530                 (int)osGetCurrentProcessId(), i,
34531                 bRc ? "ok" : "failed"));
34532        bRc = osCloseHandle(p->aRegion[i].hMap);
34533        OSTRACE(("SHM-PURGE pid-%d close region=%d %s\n",
34534                 (int)osGetCurrentProcessId(), i,
34535                 bRc ? "ok" : "failed"));
34536      }
34537      if( p->hFile.h != INVALID_HANDLE_VALUE ){
34538        SimulateIOErrorBenign(1);
34539        winClose((sqlite3_file *)&p->hFile);
34540        SimulateIOErrorBenign(0);
34541      }
34542      if( deleteFlag ){
34543        SimulateIOErrorBenign(1);
34544        sqlite3BeginBenignMalloc();
34545        winDelete(pVfs, p->zFilename, 0);
34546        sqlite3EndBenignMalloc();
34547        SimulateIOErrorBenign(0);
34548      }
34549      *pp = p->pNext;
34550      sqlite3_free(p->aRegion);
34551      sqlite3_free(p);
34552    }else{
34553      pp = &p->pNext;
34554    }
34555  }
34556}
34557
34558/*
34559** Open the shared-memory area associated with database file pDbFd.
34560**
34561** When opening a new shared-memory file, if no other instances of that
34562** file are currently open, in this process or in other processes, then
34563** the file must be truncated to zero length or have its header cleared.
34564*/
34565static int winOpenSharedMemory(winFile *pDbFd){
34566  struct winShm *p;                  /* The connection to be opened */
34567  struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
34568  int rc;                            /* Result code */
34569  struct winShmNode *pNew;           /* Newly allocated winShmNode */
34570  int nName;                         /* Size of zName in bytes */
34571
34572  assert( pDbFd->pShm==0 );    /* Not previously opened */
34573
34574  /* Allocate space for the new sqlite3_shm object.  Also speculatively
34575  ** allocate space for a new winShmNode and filename.
34576  */
34577  p = sqlite3_malloc( sizeof(*p) );
34578  if( p==0 ) return SQLITE_IOERR_NOMEM;
34579  memset(p, 0, sizeof(*p));
34580  nName = sqlite3Strlen30(pDbFd->zPath);
34581  pNew = sqlite3_malloc( sizeof(*pShmNode) + nName + 17 );
34582  if( pNew==0 ){
34583    sqlite3_free(p);
34584    return SQLITE_IOERR_NOMEM;
34585  }
34586  memset(pNew, 0, sizeof(*pNew) + nName + 17);
34587  pNew->zFilename = (char*)&pNew[1];
34588  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
34589  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
34590
34591  /* Look to see if there is an existing winShmNode that can be used.
34592  ** If no matching winShmNode currently exists, create a new one.
34593  */
34594  winShmEnterMutex();
34595  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
34596    /* TBD need to come up with better match here.  Perhaps
34597    ** use FILE_ID_BOTH_DIR_INFO Structure.
34598    */
34599    if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
34600  }
34601  if( pShmNode ){
34602    sqlite3_free(pNew);
34603  }else{
34604    pShmNode = pNew;
34605    pNew = 0;
34606    ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
34607    pShmNode->pNext = winShmNodeList;
34608    winShmNodeList = pShmNode;
34609
34610    pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
34611    if( pShmNode->mutex==0 ){
34612      rc = SQLITE_IOERR_NOMEM;
34613      goto shm_open_err;
34614    }
34615
34616    rc = winOpen(pDbFd->pVfs,
34617                 pShmNode->zFilename,             /* Name of the file (UTF-8) */
34618                 (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
34619                 SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, /* Mode flags */
34620                 0);
34621    if( SQLITE_OK!=rc ){
34622      goto shm_open_err;
34623    }
34624
34625    /* Check to see if another process is holding the dead-man switch.
34626    ** If not, truncate the file to zero length.
34627    */
34628    if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
34629      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
34630      if( rc!=SQLITE_OK ){
34631        rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
34632                 "winOpenShm", pDbFd->zPath);
34633      }
34634    }
34635    if( rc==SQLITE_OK ){
34636      winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
34637      rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
34638    }
34639    if( rc ) goto shm_open_err;
34640  }
34641
34642  /* Make the new connection a child of the winShmNode */
34643  p->pShmNode = pShmNode;
34644#ifdef SQLITE_DEBUG
34645  p->id = pShmNode->nextShmId++;
34646#endif
34647  pShmNode->nRef++;
34648  pDbFd->pShm = p;
34649  winShmLeaveMutex();
34650
34651  /* The reference count on pShmNode has already been incremented under
34652  ** the cover of the winShmEnterMutex() mutex and the pointer from the
34653  ** new (struct winShm) object to the pShmNode has been set. All that is
34654  ** left to do is to link the new object into the linked list starting
34655  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
34656  ** mutex.
34657  */
34658  sqlite3_mutex_enter(pShmNode->mutex);
34659  p->pNext = pShmNode->pFirst;
34660  pShmNode->pFirst = p;
34661  sqlite3_mutex_leave(pShmNode->mutex);
34662  return SQLITE_OK;
34663
34664  /* Jump here on any error */
34665shm_open_err:
34666  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
34667  winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
34668  sqlite3_free(p);
34669  sqlite3_free(pNew);
34670  winShmLeaveMutex();
34671  return rc;
34672}
34673
34674/*
34675** Close a connection to shared-memory.  Delete the underlying
34676** storage if deleteFlag is true.
34677*/
34678static int winShmUnmap(
34679  sqlite3_file *fd,          /* Database holding shared memory */
34680  int deleteFlag             /* Delete after closing if true */
34681){
34682  winFile *pDbFd;       /* Database holding shared-memory */
34683  winShm *p;            /* The connection to be closed */
34684  winShmNode *pShmNode; /* The underlying shared-memory file */
34685  winShm **pp;          /* For looping over sibling connections */
34686
34687  pDbFd = (winFile*)fd;
34688  p = pDbFd->pShm;
34689  if( p==0 ) return SQLITE_OK;
34690  pShmNode = p->pShmNode;
34691
34692  /* Remove connection p from the set of connections associated
34693  ** with pShmNode */
34694  sqlite3_mutex_enter(pShmNode->mutex);
34695  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
34696  *pp = p->pNext;
34697
34698  /* Free the connection p */
34699  sqlite3_free(p);
34700  pDbFd->pShm = 0;
34701  sqlite3_mutex_leave(pShmNode->mutex);
34702
34703  /* If pShmNode->nRef has reached 0, then close the underlying
34704  ** shared-memory file, too */
34705  winShmEnterMutex();
34706  assert( pShmNode->nRef>0 );
34707  pShmNode->nRef--;
34708  if( pShmNode->nRef==0 ){
34709    winShmPurge(pDbFd->pVfs, deleteFlag);
34710  }
34711  winShmLeaveMutex();
34712
34713  return SQLITE_OK;
34714}
34715
34716/*
34717** Change the lock state for a shared-memory segment.
34718*/
34719static int winShmLock(
34720  sqlite3_file *fd,          /* Database file holding the shared memory */
34721  int ofst,                  /* First lock to acquire or release */
34722  int n,                     /* Number of locks to acquire or release */
34723  int flags                  /* What to do with the lock */
34724){
34725  winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
34726  winShm *p = pDbFd->pShm;              /* The shared memory being locked */
34727  winShm *pX;                           /* For looping over all siblings */
34728  winShmNode *pShmNode = p->pShmNode;
34729  int rc = SQLITE_OK;                   /* Result code */
34730  u16 mask;                             /* Mask of locks to take or release */
34731
34732  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34733  assert( n>=1 );
34734  assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34735       || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34736       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34737       || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34738  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34739
34740  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
34741  assert( n>1 || mask==(1<<ofst) );
34742  sqlite3_mutex_enter(pShmNode->mutex);
34743  if( flags & SQLITE_SHM_UNLOCK ){
34744    u16 allMask = 0; /* Mask of locks held by siblings */
34745
34746    /* See if any siblings hold this same lock */
34747    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34748      if( pX==p ) continue;
34749      assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34750      allMask |= pX->sharedMask;
34751    }
34752
34753    /* Unlock the system-level locks */
34754    if( (mask & allMask)==0 ){
34755      rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
34756    }else{
34757      rc = SQLITE_OK;
34758    }
34759
34760    /* Undo the local locks */
34761    if( rc==SQLITE_OK ){
34762      p->exclMask &= ~mask;
34763      p->sharedMask &= ~mask;
34764    }
34765  }else if( flags & SQLITE_SHM_SHARED ){
34766    u16 allShared = 0;  /* Union of locks held by connections other than "p" */
34767
34768    /* Find out which shared locks are already held by sibling connections.
34769    ** If any sibling already holds an exclusive lock, go ahead and return
34770    ** SQLITE_BUSY.
34771    */
34772    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34773      if( (pX->exclMask & mask)!=0 ){
34774        rc = SQLITE_BUSY;
34775        break;
34776      }
34777      allShared |= pX->sharedMask;
34778    }
34779
34780    /* Get shared locks at the system level, if necessary */
34781    if( rc==SQLITE_OK ){
34782      if( (allShared & mask)==0 ){
34783        rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
34784      }else{
34785        rc = SQLITE_OK;
34786      }
34787    }
34788
34789    /* Get the local shared locks */
34790    if( rc==SQLITE_OK ){
34791      p->sharedMask |= mask;
34792    }
34793  }else{
34794    /* Make sure no sibling connections hold locks that will block this
34795    ** lock.  If any do, return SQLITE_BUSY right away.
34796    */
34797    for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34798      if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
34799        rc = SQLITE_BUSY;
34800        break;
34801      }
34802    }
34803
34804    /* Get the exclusive locks at the system level.  Then if successful
34805    ** also mark the local connection as being locked.
34806    */
34807    if( rc==SQLITE_OK ){
34808      rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
34809      if( rc==SQLITE_OK ){
34810        assert( (p->sharedMask & mask)==0 );
34811        p->exclMask |= mask;
34812      }
34813    }
34814  }
34815  sqlite3_mutex_leave(pShmNode->mutex);
34816  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x %s\n",
34817           p->id, (int)osGetCurrentProcessId(), p->sharedMask, p->exclMask,
34818           rc ? "failed" : "ok"));
34819  return rc;
34820}
34821
34822/*
34823** Implement a memory barrier or memory fence on shared memory.
34824**
34825** All loads and stores begun before the barrier must complete before
34826** any load or store begun after the barrier.
34827*/
34828static void winShmBarrier(
34829  sqlite3_file *fd          /* Database holding the shared memory */
34830){
34831  UNUSED_PARAMETER(fd);
34832  /* MemoryBarrier(); // does not work -- do not know why not */
34833  winShmEnterMutex();
34834  winShmLeaveMutex();
34835}
34836
34837/*
34838** This function is called to obtain a pointer to region iRegion of the
34839** shared-memory associated with the database file fd. Shared-memory regions
34840** are numbered starting from zero. Each shared-memory region is szRegion
34841** bytes in size.
34842**
34843** If an error occurs, an error code is returned and *pp is set to NULL.
34844**
34845** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
34846** region has not been allocated (by any client, including one running in a
34847** separate process), then *pp is set to NULL and SQLITE_OK returned. If
34848** isWrite is non-zero and the requested shared-memory region has not yet
34849** been allocated, it is allocated by this function.
34850**
34851** If the shared-memory region has already been allocated or is allocated by
34852** this call as described above, then it is mapped into this processes
34853** address space (if it is not already), *pp is set to point to the mapped
34854** memory and SQLITE_OK returned.
34855*/
34856static int winShmMap(
34857  sqlite3_file *fd,               /* Handle open on database file */
34858  int iRegion,                    /* Region to retrieve */
34859  int szRegion,                   /* Size of regions */
34860  int isWrite,                    /* True to extend file if necessary */
34861  void volatile **pp              /* OUT: Mapped memory */
34862){
34863  winFile *pDbFd = (winFile*)fd;
34864  winShm *p = pDbFd->pShm;
34865  winShmNode *pShmNode;
34866  int rc = SQLITE_OK;
34867
34868  if( !p ){
34869    rc = winOpenSharedMemory(pDbFd);
34870    if( rc!=SQLITE_OK ) return rc;
34871    p = pDbFd->pShm;
34872  }
34873  pShmNode = p->pShmNode;
34874
34875  sqlite3_mutex_enter(pShmNode->mutex);
34876  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
34877
34878  if( pShmNode->nRegion<=iRegion ){
34879    struct ShmRegion *apNew;           /* New aRegion[] array */
34880    int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
34881    sqlite3_int64 sz;                  /* Current size of wal-index file */
34882
34883    pShmNode->szRegion = szRegion;
34884
34885    /* The requested region is not mapped into this processes address space.
34886    ** Check to see if it has been allocated (i.e. if the wal-index file is
34887    ** large enough to contain the requested region).
34888    */
34889    rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
34890    if( rc!=SQLITE_OK ){
34891      rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34892               "winShmMap1", pDbFd->zPath);
34893      goto shmpage_out;
34894    }
34895
34896    if( sz<nByte ){
34897      /* The requested memory region does not exist. If isWrite is set to
34898      ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
34899      **
34900      ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
34901      ** the requested memory region.
34902      */
34903      if( !isWrite ) goto shmpage_out;
34904      rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
34905      if( rc!=SQLITE_OK ){
34906        rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34907                 "winShmMap2", pDbFd->zPath);
34908        goto shmpage_out;
34909      }
34910    }
34911
34912    /* Map the requested memory region into this processes address space. */
34913    apNew = (struct ShmRegion *)sqlite3_realloc(
34914        pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
34915    );
34916    if( !apNew ){
34917      rc = SQLITE_IOERR_NOMEM;
34918      goto shmpage_out;
34919    }
34920    pShmNode->aRegion = apNew;
34921
34922    while( pShmNode->nRegion<=iRegion ){
34923      HANDLE hMap;                /* file-mapping handle */
34924      void *pMap = 0;             /* Mapped memory region */
34925
34926      hMap = osCreateFileMapping(pShmNode->hFile.h,
34927          NULL, PAGE_READWRITE, 0, nByte, NULL
34928      );
34929      OSTRACE(("SHM-MAP pid-%d create region=%d nbyte=%d %s\n",
34930               (int)osGetCurrentProcessId(), pShmNode->nRegion, nByte,
34931               hMap ? "ok" : "failed"));
34932      if( hMap ){
34933        int iOffset = pShmNode->nRegion*szRegion;
34934        int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34935        pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34936            0, iOffset - iOffsetShift, szRegion + iOffsetShift
34937        );
34938        OSTRACE(("SHM-MAP pid-%d map region=%d offset=%d size=%d %s\n",
34939                 (int)osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
34940                 szRegion, pMap ? "ok" : "failed"));
34941      }
34942      if( !pMap ){
34943        pShmNode->lastErrno = osGetLastError();
34944        rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
34945                 "winShmMap3", pDbFd->zPath);
34946        if( hMap ) osCloseHandle(hMap);
34947        goto shmpage_out;
34948      }
34949
34950      pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
34951      pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
34952      pShmNode->nRegion++;
34953    }
34954  }
34955
34956shmpage_out:
34957  if( pShmNode->nRegion>iRegion ){
34958    int iOffset = iRegion*szRegion;
34959    int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34960    char *p = (char *)pShmNode->aRegion[iRegion].pMap;
34961    *pp = (void *)&p[iOffsetShift];
34962  }else{
34963    *pp = 0;
34964  }
34965  sqlite3_mutex_leave(pShmNode->mutex);
34966  return rc;
34967}
34968
34969#else
34970# define winShmMap     0
34971# define winShmLock    0
34972# define winShmBarrier 0
34973# define winShmUnmap   0
34974#endif /* #ifndef SQLITE_OMIT_WAL */
34975
34976/*
34977** Here ends the implementation of all sqlite3_file methods.
34978**
34979********************** End sqlite3_file Methods *******************************
34980******************************************************************************/
34981
34982/*
34983** This vector defines all the methods that can operate on an
34984** sqlite3_file for win32.
34985*/
34986static const sqlite3_io_methods winIoMethod = {
34987  2,                              /* iVersion */
34988  winClose,                       /* xClose */
34989  winRead,                        /* xRead */
34990  winWrite,                       /* xWrite */
34991  winTruncate,                    /* xTruncate */
34992  winSync,                        /* xSync */
34993  winFileSize,                    /* xFileSize */
34994  winLock,                        /* xLock */
34995  winUnlock,                      /* xUnlock */
34996  winCheckReservedLock,           /* xCheckReservedLock */
34997  winFileControl,                 /* xFileControl */
34998  winSectorSize,                  /* xSectorSize */
34999  winDeviceCharacteristics,       /* xDeviceCharacteristics */
35000  winShmMap,                      /* xShmMap */
35001  winShmLock,                     /* xShmLock */
35002  winShmBarrier,                  /* xShmBarrier */
35003  winShmUnmap                     /* xShmUnmap */
35004};
35005
35006/****************************************************************************
35007**************************** sqlite3_vfs methods ****************************
35008**
35009** This division contains the implementation of methods on the
35010** sqlite3_vfs object.
35011*/
35012
35013/*
35014** Convert a UTF-8 filename into whatever form the underlying
35015** operating system wants filenames in.  Space to hold the result
35016** is obtained from malloc and must be freed by the calling
35017** function.
35018*/
35019static void *convertUtf8Filename(const char *zFilename){
35020  void *zConverted = 0;
35021  if( isNT() ){
35022    zConverted = utf8ToUnicode(zFilename);
35023/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35024*/
35025#if SQLITE_OS_WINCE==0
35026  }else{
35027    zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
35028#endif
35029  }
35030  /* caller will handle out of memory */
35031  return zConverted;
35032}
35033
35034/*
35035** Create a temporary file name in zBuf.  zBuf must be big enough to
35036** hold at pVfs->mxPathname characters.
35037*/
35038static int getTempname(int nBuf, char *zBuf){
35039  static char zChars[] =
35040    "abcdefghijklmnopqrstuvwxyz"
35041    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
35042    "0123456789";
35043  size_t i, j;
35044  char zTempPath[MAX_PATH+2];
35045
35046  /* It's odd to simulate an io-error here, but really this is just
35047  ** using the io-error infrastructure to test that SQLite handles this
35048  ** function failing.
35049  */
35050  SimulateIOError( return SQLITE_IOERR );
35051
35052  if( sqlite3_temp_directory ){
35053    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
35054  }else if( isNT() ){
35055    char *zMulti;
35056    WCHAR zWidePath[MAX_PATH];
35057    osGetTempPathW(MAX_PATH-30, zWidePath);
35058    zMulti = unicodeToUtf8(zWidePath);
35059    if( zMulti ){
35060      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
35061      sqlite3_free(zMulti);
35062    }else{
35063      return SQLITE_IOERR_NOMEM;
35064    }
35065/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35066** Since the ANSI version of these Windows API do not exist for WINCE,
35067** it's important to not reference them for WINCE builds.
35068*/
35069#if SQLITE_OS_WINCE==0
35070  }else{
35071    char *zUtf8;
35072    char zMbcsPath[MAX_PATH];
35073    osGetTempPathA(MAX_PATH-30, zMbcsPath);
35074    zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
35075    if( zUtf8 ){
35076      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
35077      sqlite3_free(zUtf8);
35078    }else{
35079      return SQLITE_IOERR_NOMEM;
35080    }
35081#endif
35082  }
35083
35084  /* Check that the output buffer is large enough for the temporary file
35085  ** name. If it is not, return SQLITE_ERROR.
35086  */
35087  if( (sqlite3Strlen30(zTempPath) + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
35088    return SQLITE_ERROR;
35089  }
35090
35091  for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
35092  zTempPath[i] = 0;
35093
35094  sqlite3_snprintf(nBuf-18, zBuf,
35095                   "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
35096  j = sqlite3Strlen30(zBuf);
35097  sqlite3_randomness(15, &zBuf[j]);
35098  for(i=0; i<15; i++, j++){
35099    zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
35100  }
35101  zBuf[j] = 0;
35102  zBuf[j+1] = 0;
35103
35104  OSTRACE(("TEMP FILENAME: %s\n", zBuf));
35105  return SQLITE_OK;
35106}
35107
35108/*
35109** Open a file.
35110*/
35111static int winOpen(
35112  sqlite3_vfs *pVfs,        /* Not used */
35113  const char *zName,        /* Name of the file (UTF-8) */
35114  sqlite3_file *id,         /* Write the SQLite file handle here */
35115  int flags,                /* Open mode flags */
35116  int *pOutFlags            /* Status return flags */
35117){
35118  HANDLE h;
35119  DWORD lastErrno;
35120  DWORD dwDesiredAccess;
35121  DWORD dwShareMode;
35122  DWORD dwCreationDisposition;
35123  DWORD dwFlagsAndAttributes = 0;
35124#if SQLITE_OS_WINCE
35125  int isTemp = 0;
35126#endif
35127  winFile *pFile = (winFile*)id;
35128  void *zConverted;              /* Filename in OS encoding */
35129  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
35130  int cnt = 0;
35131
35132  /* If argument zPath is a NULL pointer, this function is required to open
35133  ** a temporary file. Use this buffer to store the file name in.
35134  */
35135  char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
35136
35137  int rc = SQLITE_OK;            /* Function Return Code */
35138#if !defined(NDEBUG) || SQLITE_OS_WINCE
35139  int eType = flags&0xFFFFFF00;  /* Type of file to open */
35140#endif
35141
35142  int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
35143  int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
35144  int isCreate     = (flags & SQLITE_OPEN_CREATE);
35145#ifndef NDEBUG
35146  int isReadonly   = (flags & SQLITE_OPEN_READONLY);
35147#endif
35148  int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
35149
35150#ifndef NDEBUG
35151  int isOpenJournal = (isCreate && (
35152        eType==SQLITE_OPEN_MASTER_JOURNAL
35153     || eType==SQLITE_OPEN_MAIN_JOURNAL
35154     || eType==SQLITE_OPEN_WAL
35155  ));
35156#endif
35157
35158  /* Check the following statements are true:
35159  **
35160  **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
35161  **   (b) if CREATE is set, then READWRITE must also be set, and
35162  **   (c) if EXCLUSIVE is set, then CREATE must also be set.
35163  **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
35164  */
35165  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
35166  assert(isCreate==0 || isReadWrite);
35167  assert(isExclusive==0 || isCreate);
35168  assert(isDelete==0 || isCreate);
35169
35170  /* The main DB, main journal, WAL file and master journal are never
35171  ** automatically deleted. Nor are they ever temporary files.  */
35172  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
35173  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
35174  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
35175  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
35176
35177  /* Assert that the upper layer has set one of the "file-type" flags. */
35178  assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
35179       || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
35180       || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
35181       || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
35182  );
35183
35184  assert( id!=0 );
35185  UNUSED_PARAMETER(pVfs);
35186
35187  pFile->h = INVALID_HANDLE_VALUE;
35188
35189  /* If the second argument to this function is NULL, generate a
35190  ** temporary file name to use
35191  */
35192  if( !zUtf8Name ){
35193    assert(isDelete && !isOpenJournal);
35194    rc = getTempname(MAX_PATH+2, zTmpname);
35195    if( rc!=SQLITE_OK ){
35196      return rc;
35197    }
35198    zUtf8Name = zTmpname;
35199  }
35200
35201  /* Database filenames are double-zero terminated if they are not
35202  ** URIs with parameters.  Hence, they can always be passed into
35203  ** sqlite3_uri_parameter().
35204  */
35205  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
35206        zUtf8Name[strlen(zUtf8Name)+1]==0 );
35207
35208  /* Convert the filename to the system encoding. */
35209  zConverted = convertUtf8Filename(zUtf8Name);
35210  if( zConverted==0 ){
35211    return SQLITE_IOERR_NOMEM;
35212  }
35213
35214  if( isReadWrite ){
35215    dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
35216  }else{
35217    dwDesiredAccess = GENERIC_READ;
35218  }
35219
35220  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
35221  ** created. SQLite doesn't use it to indicate "exclusive access"
35222  ** as it is usually understood.
35223  */
35224  if( isExclusive ){
35225    /* Creates a new file, only if it does not already exist. */
35226    /* If the file exists, it fails. */
35227    dwCreationDisposition = CREATE_NEW;
35228  }else if( isCreate ){
35229    /* Open existing file, or create if it doesn't exist */
35230    dwCreationDisposition = OPEN_ALWAYS;
35231  }else{
35232    /* Opens a file, only if it exists. */
35233    dwCreationDisposition = OPEN_EXISTING;
35234  }
35235
35236  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
35237
35238  if( isDelete ){
35239#if SQLITE_OS_WINCE
35240    dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
35241    isTemp = 1;
35242#else
35243    dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
35244                               | FILE_ATTRIBUTE_HIDDEN
35245                               | FILE_FLAG_DELETE_ON_CLOSE;
35246#endif
35247  }else{
35248    dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
35249  }
35250  /* Reports from the internet are that performance is always
35251  ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
35252#if SQLITE_OS_WINCE
35253  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
35254#endif
35255
35256  if( isNT() ){
35257    while( (h = osCreateFileW((LPCWSTR)zConverted,
35258                              dwDesiredAccess,
35259                              dwShareMode, NULL,
35260                              dwCreationDisposition,
35261                              dwFlagsAndAttributes,
35262                              NULL))==INVALID_HANDLE_VALUE &&
35263                              retryIoerr(&cnt, &lastErrno) ){}
35264/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35265** Since the ANSI version of these Windows API do not exist for WINCE,
35266** it's important to not reference them for WINCE builds.
35267*/
35268#if SQLITE_OS_WINCE==0
35269  }else{
35270    while( (h = osCreateFileA((LPCSTR)zConverted,
35271                              dwDesiredAccess,
35272                              dwShareMode, NULL,
35273                              dwCreationDisposition,
35274                              dwFlagsAndAttributes,
35275                              NULL))==INVALID_HANDLE_VALUE &&
35276                              retryIoerr(&cnt, &lastErrno) ){}
35277#endif
35278  }
35279
35280  logIoerr(cnt);
35281
35282  OSTRACE(("OPEN %d %s 0x%lx %s\n",
35283           h, zName, dwDesiredAccess,
35284           h==INVALID_HANDLE_VALUE ? "failed" : "ok"));
35285
35286  if( h==INVALID_HANDLE_VALUE ){
35287    pFile->lastErrno = lastErrno;
35288    winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
35289    sqlite3_free(zConverted);
35290    if( isReadWrite && !isExclusive ){
35291      return winOpen(pVfs, zName, id,
35292             ((flags|SQLITE_OPEN_READONLY)&~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)), pOutFlags);
35293    }else{
35294      return SQLITE_CANTOPEN_BKPT;
35295    }
35296  }
35297
35298  if( pOutFlags ){
35299    if( isReadWrite ){
35300      *pOutFlags = SQLITE_OPEN_READWRITE;
35301    }else{
35302      *pOutFlags = SQLITE_OPEN_READONLY;
35303    }
35304  }
35305
35306  memset(pFile, 0, sizeof(*pFile));
35307  pFile->pMethod = &winIoMethod;
35308  pFile->h = h;
35309  pFile->lastErrno = NO_ERROR;
35310  pFile->pVfs = pVfs;
35311  pFile->pShm = 0;
35312  pFile->zPath = zName;
35313  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
35314    pFile->ctrlFlags |= WINFILE_PSOW;
35315  }
35316
35317#if SQLITE_OS_WINCE
35318  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
35319       && !winceCreateLock(zName, pFile)
35320  ){
35321    osCloseHandle(h);
35322    sqlite3_free(zConverted);
35323    return SQLITE_CANTOPEN_BKPT;
35324  }
35325  if( isTemp ){
35326    pFile->zDeleteOnClose = zConverted;
35327  }else
35328#endif
35329  {
35330    sqlite3_free(zConverted);
35331  }
35332
35333  OpenCounter(+1);
35334  return rc;
35335}
35336
35337/*
35338** Delete the named file.
35339**
35340** Note that Windows does not allow a file to be deleted if some other
35341** process has it open.  Sometimes a virus scanner or indexing program
35342** will open a journal file shortly after it is created in order to do
35343** whatever it does.  While this other process is holding the
35344** file open, we will be unable to delete it.  To work around this
35345** problem, we delay 100 milliseconds and try to delete again.  Up
35346** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
35347** up and returning an error.
35348*/
35349static int winDelete(
35350  sqlite3_vfs *pVfs,          /* Not used on win32 */
35351  const char *zFilename,      /* Name of file to delete */
35352  int syncDir                 /* Not used on win32 */
35353){
35354  int cnt = 0;
35355  int rc;
35356  DWORD lastErrno;
35357  void *zConverted;
35358  UNUSED_PARAMETER(pVfs);
35359  UNUSED_PARAMETER(syncDir);
35360
35361  SimulateIOError(return SQLITE_IOERR_DELETE);
35362  zConverted = convertUtf8Filename(zFilename);
35363  if( zConverted==0 ){
35364    return SQLITE_IOERR_NOMEM;
35365  }
35366  if( isNT() ){
35367    rc = 1;
35368    while( osGetFileAttributesW(zConverted)!=INVALID_FILE_ATTRIBUTES &&
35369         (rc = osDeleteFileW(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
35370    rc = rc ? SQLITE_OK : SQLITE_ERROR;
35371/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35372** Since the ANSI version of these Windows API do not exist for WINCE,
35373** it's important to not reference them for WINCE builds.
35374*/
35375#if SQLITE_OS_WINCE==0
35376  }else{
35377    rc = 1;
35378    while( osGetFileAttributesA(zConverted)!=INVALID_FILE_ATTRIBUTES &&
35379         (rc = osDeleteFileA(zConverted))==0 && retryIoerr(&cnt, &lastErrno) ){}
35380    rc = rc ? SQLITE_OK : SQLITE_ERROR;
35381#endif
35382  }
35383  if( rc ){
35384    rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
35385             "winDelete", zFilename);
35386  }else{
35387    logIoerr(cnt);
35388  }
35389  sqlite3_free(zConverted);
35390  OSTRACE(("DELETE \"%s\" %s\n", zFilename, (rc ? "failed" : "ok" )));
35391  return rc;
35392}
35393
35394/*
35395** Check the existance and status of a file.
35396*/
35397static int winAccess(
35398  sqlite3_vfs *pVfs,         /* Not used on win32 */
35399  const char *zFilename,     /* Name of file to check */
35400  int flags,                 /* Type of test to make on this file */
35401  int *pResOut               /* OUT: Result */
35402){
35403  DWORD attr;
35404  int rc = 0;
35405  DWORD lastErrno;
35406  void *zConverted;
35407  UNUSED_PARAMETER(pVfs);
35408
35409  SimulateIOError( return SQLITE_IOERR_ACCESS; );
35410  zConverted = convertUtf8Filename(zFilename);
35411  if( zConverted==0 ){
35412    return SQLITE_IOERR_NOMEM;
35413  }
35414  if( isNT() ){
35415    int cnt = 0;
35416    WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35417    memset(&sAttrData, 0, sizeof(sAttrData));
35418    while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
35419                             GetFileExInfoStandard,
35420                             &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
35421    if( rc ){
35422      /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
35423      ** as if it does not exist.
35424      */
35425      if(    flags==SQLITE_ACCESS_EXISTS
35426          && sAttrData.nFileSizeHigh==0
35427          && sAttrData.nFileSizeLow==0 ){
35428        attr = INVALID_FILE_ATTRIBUTES;
35429      }else{
35430        attr = sAttrData.dwFileAttributes;
35431      }
35432    }else{
35433      logIoerr(cnt);
35434      if( lastErrno!=ERROR_FILE_NOT_FOUND ){
35435        winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
35436        sqlite3_free(zConverted);
35437        return SQLITE_IOERR_ACCESS;
35438      }else{
35439        attr = INVALID_FILE_ATTRIBUTES;
35440      }
35441    }
35442/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35443** Since the ANSI version of these Windows API do not exist for WINCE,
35444** it's important to not reference them for WINCE builds.
35445*/
35446#if SQLITE_OS_WINCE==0
35447  }else{
35448    attr = osGetFileAttributesA((char*)zConverted);
35449#endif
35450  }
35451  sqlite3_free(zConverted);
35452  switch( flags ){
35453    case SQLITE_ACCESS_READ:
35454    case SQLITE_ACCESS_EXISTS:
35455      rc = attr!=INVALID_FILE_ATTRIBUTES;
35456      break;
35457    case SQLITE_ACCESS_READWRITE:
35458      rc = attr!=INVALID_FILE_ATTRIBUTES &&
35459             (attr & FILE_ATTRIBUTE_READONLY)==0;
35460      break;
35461    default:
35462      assert(!"Invalid flags argument");
35463  }
35464  *pResOut = rc;
35465  return SQLITE_OK;
35466}
35467
35468
35469/*
35470** Turn a relative pathname into a full pathname.  Write the full
35471** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
35472** bytes in size.
35473*/
35474static int winFullPathname(
35475  sqlite3_vfs *pVfs,            /* Pointer to vfs object */
35476  const char *zRelative,        /* Possibly relative input path */
35477  int nFull,                    /* Size of output buffer in bytes */
35478  char *zFull                   /* Output buffer */
35479){
35480
35481#if defined(__CYGWIN__)
35482  SimulateIOError( return SQLITE_ERROR );
35483  UNUSED_PARAMETER(nFull);
35484  cygwin_conv_to_full_win32_path(zRelative, zFull);
35485  return SQLITE_OK;
35486#endif
35487
35488#if SQLITE_OS_WINCE
35489  SimulateIOError( return SQLITE_ERROR );
35490  UNUSED_PARAMETER(nFull);
35491  /* WinCE has no concept of a relative pathname, or so I am told. */
35492  sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
35493  return SQLITE_OK;
35494#endif
35495
35496#if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
35497  int nByte;
35498  void *zConverted;
35499  char *zOut;
35500
35501  /* If this path name begins with "/X:", where "X" is any alphabetic
35502  ** character, discard the initial "/" from the pathname.
35503  */
35504  if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
35505    zRelative++;
35506  }
35507
35508  /* It's odd to simulate an io-error here, but really this is just
35509  ** using the io-error infrastructure to test that SQLite handles this
35510  ** function failing. This function could fail if, for example, the
35511  ** current working directory has been unlinked.
35512  */
35513  SimulateIOError( return SQLITE_ERROR );
35514  UNUSED_PARAMETER(nFull);
35515  zConverted = convertUtf8Filename(zRelative);
35516  if( zConverted==0 ){
35517    return SQLITE_IOERR_NOMEM;
35518  }
35519  if( isNT() ){
35520    LPWSTR zTemp;
35521    nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0) + 3;
35522    zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
35523    if( zTemp==0 ){
35524      sqlite3_free(zConverted);
35525      return SQLITE_IOERR_NOMEM;
35526    }
35527    osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
35528    sqlite3_free(zConverted);
35529    zOut = unicodeToUtf8(zTemp);
35530    sqlite3_free(zTemp);
35531/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35532** Since the ANSI version of these Windows API do not exist for WINCE,
35533** it's important to not reference them for WINCE builds.
35534*/
35535#if SQLITE_OS_WINCE==0
35536  }else{
35537    char *zTemp;
35538    nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
35539    zTemp = sqlite3_malloc( nByte*sizeof(zTemp[0]) );
35540    if( zTemp==0 ){
35541      sqlite3_free(zConverted);
35542      return SQLITE_IOERR_NOMEM;
35543    }
35544    osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
35545    sqlite3_free(zConverted);
35546    zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
35547    sqlite3_free(zTemp);
35548#endif
35549  }
35550  if( zOut ){
35551    sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
35552    sqlite3_free(zOut);
35553    return SQLITE_OK;
35554  }else{
35555    return SQLITE_IOERR_NOMEM;
35556  }
35557#endif
35558}
35559
35560#ifndef SQLITE_OMIT_LOAD_EXTENSION
35561/*
35562** Interfaces for opening a shared library, finding entry points
35563** within the shared library, and closing the shared library.
35564*/
35565/*
35566** Interfaces for opening a shared library, finding entry points
35567** within the shared library, and closing the shared library.
35568*/
35569static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
35570  HANDLE h;
35571  void *zConverted = convertUtf8Filename(zFilename);
35572  UNUSED_PARAMETER(pVfs);
35573  if( zConverted==0 ){
35574    return 0;
35575  }
35576  if( isNT() ){
35577    h = osLoadLibraryW((LPCWSTR)zConverted);
35578/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed.
35579** Since the ANSI version of these Windows API do not exist for WINCE,
35580** it's important to not reference them for WINCE builds.
35581*/
35582#if SQLITE_OS_WINCE==0
35583  }else{
35584    h = osLoadLibraryA((char*)zConverted);
35585#endif
35586  }
35587  sqlite3_free(zConverted);
35588  return (void*)h;
35589}
35590static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
35591  UNUSED_PARAMETER(pVfs);
35592  getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
35593}
35594static void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
35595  UNUSED_PARAMETER(pVfs);
35596  return (void(*)(void))osGetProcAddressA((HANDLE)pHandle, zSymbol);
35597}
35598static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
35599  UNUSED_PARAMETER(pVfs);
35600  osFreeLibrary((HANDLE)pHandle);
35601}
35602#else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
35603  #define winDlOpen  0
35604  #define winDlError 0
35605  #define winDlSym   0
35606  #define winDlClose 0
35607#endif
35608
35609
35610/*
35611** Write up to nBuf bytes of randomness into zBuf.
35612*/
35613static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35614  int n = 0;
35615  UNUSED_PARAMETER(pVfs);
35616#if defined(SQLITE_TEST)
35617  n = nBuf;
35618  memset(zBuf, 0, nBuf);
35619#else
35620  if( sizeof(SYSTEMTIME)<=nBuf-n ){
35621    SYSTEMTIME x;
35622    osGetSystemTime(&x);
35623    memcpy(&zBuf[n], &x, sizeof(x));
35624    n += sizeof(x);
35625  }
35626  if( sizeof(DWORD)<=nBuf-n ){
35627    DWORD pid = osGetCurrentProcessId();
35628    memcpy(&zBuf[n], &pid, sizeof(pid));
35629    n += sizeof(pid);
35630  }
35631  if( sizeof(DWORD)<=nBuf-n ){
35632    DWORD cnt = osGetTickCount();
35633    memcpy(&zBuf[n], &cnt, sizeof(cnt));
35634    n += sizeof(cnt);
35635  }
35636  if( sizeof(LARGE_INTEGER)<=nBuf-n ){
35637    LARGE_INTEGER i;
35638    osQueryPerformanceCounter(&i);
35639    memcpy(&zBuf[n], &i, sizeof(i));
35640    n += sizeof(i);
35641  }
35642#endif
35643  return n;
35644}
35645
35646
35647/*
35648** Sleep for a little while.  Return the amount of time slept.
35649*/
35650static int winSleep(sqlite3_vfs *pVfs, int microsec){
35651  osSleep((microsec+999)/1000);
35652  UNUSED_PARAMETER(pVfs);
35653  return ((microsec+999)/1000)*1000;
35654}
35655
35656/*
35657** The following variable, if set to a non-zero value, is interpreted as
35658** the number of seconds since 1970 and is used to set the result of
35659** sqlite3OsCurrentTime() during testing.
35660*/
35661#ifdef SQLITE_TEST
35662SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
35663#endif
35664
35665/*
35666** Find the current time (in Universal Coordinated Time).  Write into *piNow
35667** the current time and date as a Julian Day number times 86_400_000.  In
35668** other words, write into *piNow the number of milliseconds since the Julian
35669** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35670** proleptic Gregorian calendar.
35671**
35672** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
35673** cannot be found.
35674*/
35675static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
35676  /* FILETIME structure is a 64-bit value representing the number of
35677     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
35678  */
35679  FILETIME ft;
35680  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
35681#ifdef SQLITE_TEST
35682  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35683#endif
35684  /* 2^32 - to avoid use of LL and warnings in gcc */
35685  static const sqlite3_int64 max32BitValue =
35686      (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
35687
35688#if SQLITE_OS_WINCE
35689  SYSTEMTIME time;
35690  osGetSystemTime(&time);
35691  /* if SystemTimeToFileTime() fails, it returns zero. */
35692  if (!osSystemTimeToFileTime(&time,&ft)){
35693    return SQLITE_ERROR;
35694  }
35695#else
35696  osGetSystemTimeAsFileTime( &ft );
35697#endif
35698
35699  *piNow = winFiletimeEpoch +
35700            ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
35701               (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
35702
35703#ifdef SQLITE_TEST
35704  if( sqlite3_current_time ){
35705    *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35706  }
35707#endif
35708  UNUSED_PARAMETER(pVfs);
35709  return SQLITE_OK;
35710}
35711
35712/*
35713** Find the current time (in Universal Coordinated Time).  Write the
35714** current time and date as a Julian Day number into *prNow and
35715** return 0.  Return 1 if the time and date cannot be found.
35716*/
35717static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
35718  int rc;
35719  sqlite3_int64 i;
35720  rc = winCurrentTimeInt64(pVfs, &i);
35721  if( !rc ){
35722    *prNow = i/86400000.0;
35723  }
35724  return rc;
35725}
35726
35727/*
35728** The idea is that this function works like a combination of
35729** GetLastError() and FormatMessage() on Windows (or errno and
35730** strerror_r() on Unix). After an error is returned by an OS
35731** function, SQLite calls this function with zBuf pointing to
35732** a buffer of nBuf bytes. The OS layer should populate the
35733** buffer with a nul-terminated UTF-8 encoded error message
35734** describing the last IO error to have occurred within the calling
35735** thread.
35736**
35737** If the error message is too large for the supplied buffer,
35738** it should be truncated. The return value of xGetLastError
35739** is zero if the error message fits in the buffer, or non-zero
35740** otherwise (if the message was truncated). If non-zero is returned,
35741** then it is not necessary to include the nul-terminator character
35742** in the output buffer.
35743**
35744** Not supplying an error message will have no adverse effect
35745** on SQLite. It is fine to have an implementation that never
35746** returns an error message:
35747**
35748**   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35749**     assert(zBuf[0]=='\0');
35750**     return 0;
35751**   }
35752**
35753** However if an error message is supplied, it will be incorporated
35754** by sqlite into the error message available to the user using
35755** sqlite3_errmsg(), possibly making IO errors easier to debug.
35756*/
35757static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35758  UNUSED_PARAMETER(pVfs);
35759  return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
35760}
35761
35762/*
35763** Initialize and deinitialize the operating system interface.
35764*/
35765SQLITE_API int sqlite3_os_init(void){
35766  static sqlite3_vfs winVfs = {
35767    3,                   /* iVersion */
35768    sizeof(winFile),     /* szOsFile */
35769    MAX_PATH,            /* mxPathname */
35770    0,                   /* pNext */
35771    "win32",             /* zName */
35772    0,                   /* pAppData */
35773    winOpen,             /* xOpen */
35774    winDelete,           /* xDelete */
35775    winAccess,           /* xAccess */
35776    winFullPathname,     /* xFullPathname */
35777    winDlOpen,           /* xDlOpen */
35778    winDlError,          /* xDlError */
35779    winDlSym,            /* xDlSym */
35780    winDlClose,          /* xDlClose */
35781    winRandomness,       /* xRandomness */
35782    winSleep,            /* xSleep */
35783    winCurrentTime,      /* xCurrentTime */
35784    winGetLastError,     /* xGetLastError */
35785    winCurrentTimeInt64, /* xCurrentTimeInt64 */
35786    winSetSystemCall,    /* xSetSystemCall */
35787    winGetSystemCall,    /* xGetSystemCall */
35788    winNextSystemCall,   /* xNextSystemCall */
35789  };
35790
35791  /* Double-check that the aSyscall[] array has been constructed
35792  ** correctly.  See ticket [bb3a86e890c8e96ab] */
35793  assert( ArraySize(aSyscall)==60 );
35794
35795#ifndef SQLITE_OMIT_WAL
35796  /* get memory map allocation granularity */
35797  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
35798  osGetSystemInfo(&winSysInfo);
35799  assert(winSysInfo.dwAllocationGranularity > 0);
35800#endif
35801
35802  sqlite3_vfs_register(&winVfs, 1);
35803  return SQLITE_OK;
35804}
35805
35806SQLITE_API int sqlite3_os_end(void){
35807  return SQLITE_OK;
35808}
35809
35810#endif /* SQLITE_OS_WIN */
35811
35812/************** End of os_win.c **********************************************/
35813/************** Begin file bitvec.c ******************************************/
35814/*
35815** 2008 February 16
35816**
35817** The author disclaims copyright to this source code.  In place of
35818** a legal notice, here is a blessing:
35819**
35820**    May you do good and not evil.
35821**    May you find forgiveness for yourself and forgive others.
35822**    May you share freely, never taking more than you give.
35823**
35824*************************************************************************
35825** This file implements an object that represents a fixed-length
35826** bitmap.  Bits are numbered starting with 1.
35827**
35828** A bitmap is used to record which pages of a database file have been
35829** journalled during a transaction, or which pages have the "dont-write"
35830** property.  Usually only a few pages are meet either condition.
35831** So the bitmap is usually sparse and has low cardinality.
35832** But sometimes (for example when during a DROP of a large table) most
35833** or all of the pages in a database can get journalled.  In those cases,
35834** the bitmap becomes dense with high cardinality.  The algorithm needs
35835** to handle both cases well.
35836**
35837** The size of the bitmap is fixed when the object is created.
35838**
35839** All bits are clear when the bitmap is created.  Individual bits
35840** may be set or cleared one at a time.
35841**
35842** Test operations are about 100 times more common that set operations.
35843** Clear operations are exceedingly rare.  There are usually between
35844** 5 and 500 set operations per Bitvec object, though the number of sets can
35845** sometimes grow into tens of thousands or larger.  The size of the
35846** Bitvec object is the number of pages in the database file at the
35847** start of a transaction, and is thus usually less than a few thousand,
35848** but can be as large as 2 billion for a really big database.
35849*/
35850
35851/* Size of the Bitvec structure in bytes. */
35852#define BITVEC_SZ        512
35853
35854/* Round the union size down to the nearest pointer boundary, since that's how
35855** it will be aligned within the Bitvec struct. */
35856#define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
35857
35858/* Type of the array "element" for the bitmap representation.
35859** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
35860** Setting this to the "natural word" size of your CPU may improve
35861** performance. */
35862#define BITVEC_TELEM     u8
35863/* Size, in bits, of the bitmap element. */
35864#define BITVEC_SZELEM    8
35865/* Number of elements in a bitmap array. */
35866#define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
35867/* Number of bits in the bitmap array. */
35868#define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
35869
35870/* Number of u32 values in hash table. */
35871#define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
35872/* Maximum number of entries in hash table before
35873** sub-dividing and re-hashing. */
35874#define BITVEC_MXHASH    (BITVEC_NINT/2)
35875/* Hashing function for the aHash representation.
35876** Empirical testing showed that the *37 multiplier
35877** (an arbitrary prime)in the hash function provided
35878** no fewer collisions than the no-op *1. */
35879#define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
35880
35881#define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
35882
35883
35884/*
35885** A bitmap is an instance of the following structure.
35886**
35887** This bitmap records the existance of zero or more bits
35888** with values between 1 and iSize, inclusive.
35889**
35890** There are three possible representations of the bitmap.
35891** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
35892** bitmap.  The least significant bit is bit 1.
35893**
35894** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
35895** a hash table that will hold up to BITVEC_MXHASH distinct values.
35896**
35897** Otherwise, the value i is redirected into one of BITVEC_NPTR
35898** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
35899** handles up to iDivisor separate values of i.  apSub[0] holds
35900** values between 1 and iDivisor.  apSub[1] holds values between
35901** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
35902** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
35903** to hold deal with values between 1 and iDivisor.
35904*/
35905struct Bitvec {
35906  u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
35907  u32 nSet;       /* Number of bits that are set - only valid for aHash
35908                  ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
35909                  ** this would be 125. */
35910  u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
35911                  /* Should >=0 for apSub element. */
35912                  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
35913                  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
35914  union {
35915    BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
35916    u32 aHash[BITVEC_NINT];      /* Hash table representation */
35917    Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
35918  } u;
35919};
35920
35921/*
35922** Create a new bitmap object able to handle bits between 0 and iSize,
35923** inclusive.  Return a pointer to the new object.  Return NULL if
35924** malloc fails.
35925*/
35926SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
35927  Bitvec *p;
35928  assert( sizeof(*p)==BITVEC_SZ );
35929  p = sqlite3MallocZero( sizeof(*p) );
35930  if( p ){
35931    p->iSize = iSize;
35932  }
35933  return p;
35934}
35935
35936/*
35937** Check to see if the i-th bit is set.  Return true or false.
35938** If p is NULL (if the bitmap has not been created) or if
35939** i is out of range, then return false.
35940*/
35941SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
35942  if( p==0 ) return 0;
35943  if( i>p->iSize || i==0 ) return 0;
35944  i--;
35945  while( p->iDivisor ){
35946    u32 bin = i/p->iDivisor;
35947    i = i%p->iDivisor;
35948    p = p->u.apSub[bin];
35949    if (!p) {
35950      return 0;
35951    }
35952  }
35953  if( p->iSize<=BITVEC_NBIT ){
35954    return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
35955  } else{
35956    u32 h = BITVEC_HASH(i++);
35957    while( p->u.aHash[h] ){
35958      if( p->u.aHash[h]==i ) return 1;
35959      h = (h+1) % BITVEC_NINT;
35960    }
35961    return 0;
35962  }
35963}
35964
35965/*
35966** Set the i-th bit.  Return 0 on success and an error code if
35967** anything goes wrong.
35968**
35969** This routine might cause sub-bitmaps to be allocated.  Failing
35970** to get the memory needed to hold the sub-bitmap is the only
35971** that can go wrong with an insert, assuming p and i are valid.
35972**
35973** The calling function must ensure that p is a valid Bitvec object
35974** and that the value for "i" is within range of the Bitvec object.
35975** Otherwise the behavior is undefined.
35976*/
35977SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
35978  u32 h;
35979  if( p==0 ) return SQLITE_OK;
35980  assert( i>0 );
35981  assert( i<=p->iSize );
35982  i--;
35983  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
35984    u32 bin = i/p->iDivisor;
35985    i = i%p->iDivisor;
35986    if( p->u.apSub[bin]==0 ){
35987      p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
35988      if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
35989    }
35990    p = p->u.apSub[bin];
35991  }
35992  if( p->iSize<=BITVEC_NBIT ){
35993    p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
35994    return SQLITE_OK;
35995  }
35996  h = BITVEC_HASH(i++);
35997  /* if there wasn't a hash collision, and this doesn't */
35998  /* completely fill the hash, then just add it without */
35999  /* worring about sub-dividing and re-hashing. */
36000  if( !p->u.aHash[h] ){
36001    if (p->nSet<(BITVEC_NINT-1)) {
36002      goto bitvec_set_end;
36003    } else {
36004      goto bitvec_set_rehash;
36005    }
36006  }
36007  /* there was a collision, check to see if it's already */
36008  /* in hash, if not, try to find a spot for it */
36009  do {
36010    if( p->u.aHash[h]==i ) return SQLITE_OK;
36011    h++;
36012    if( h>=BITVEC_NINT ) h = 0;
36013  } while( p->u.aHash[h] );
36014  /* we didn't find it in the hash.  h points to the first */
36015  /* available free spot. check to see if this is going to */
36016  /* make our hash too "full".  */
36017bitvec_set_rehash:
36018  if( p->nSet>=BITVEC_MXHASH ){
36019    unsigned int j;
36020    int rc;
36021    u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
36022    if( aiValues==0 ){
36023      return SQLITE_NOMEM;
36024    }else{
36025      memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36026      memset(p->u.apSub, 0, sizeof(p->u.apSub));
36027      p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
36028      rc = sqlite3BitvecSet(p, i);
36029      for(j=0; j<BITVEC_NINT; j++){
36030        if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
36031      }
36032      sqlite3StackFree(0, aiValues);
36033      return rc;
36034    }
36035  }
36036bitvec_set_end:
36037  p->nSet++;
36038  p->u.aHash[h] = i;
36039  return SQLITE_OK;
36040}
36041
36042/*
36043** Clear the i-th bit.
36044**
36045** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
36046** that BitvecClear can use to rebuilt its hash table.
36047*/
36048SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
36049  if( p==0 ) return;
36050  assert( i>0 );
36051  i--;
36052  while( p->iDivisor ){
36053    u32 bin = i/p->iDivisor;
36054    i = i%p->iDivisor;
36055    p = p->u.apSub[bin];
36056    if (!p) {
36057      return;
36058    }
36059  }
36060  if( p->iSize<=BITVEC_NBIT ){
36061    p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
36062  }else{
36063    unsigned int j;
36064    u32 *aiValues = pBuf;
36065    memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
36066    memset(p->u.aHash, 0, sizeof(p->u.aHash));
36067    p->nSet = 0;
36068    for(j=0; j<BITVEC_NINT; j++){
36069      if( aiValues[j] && aiValues[j]!=(i+1) ){
36070        u32 h = BITVEC_HASH(aiValues[j]-1);
36071        p->nSet++;
36072        while( p->u.aHash[h] ){
36073          h++;
36074          if( h>=BITVEC_NINT ) h = 0;
36075        }
36076        p->u.aHash[h] = aiValues[j];
36077      }
36078    }
36079  }
36080}
36081
36082/*
36083** Destroy a bitmap object.  Reclaim all memory used.
36084*/
36085SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
36086  if( p==0 ) return;
36087  if( p->iDivisor ){
36088    unsigned int i;
36089    for(i=0; i<BITVEC_NPTR; i++){
36090      sqlite3BitvecDestroy(p->u.apSub[i]);
36091    }
36092  }
36093  sqlite3_free(p);
36094}
36095
36096/*
36097** Return the value of the iSize parameter specified when Bitvec *p
36098** was created.
36099*/
36100SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
36101  return p->iSize;
36102}
36103
36104#ifndef SQLITE_OMIT_BUILTIN_TEST
36105/*
36106** Let V[] be an array of unsigned characters sufficient to hold
36107** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
36108** Then the following macros can be used to set, clear, or test
36109** individual bits within V.
36110*/
36111#define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
36112#define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
36113#define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
36114
36115/*
36116** This routine runs an extensive test of the Bitvec code.
36117**
36118** The input is an array of integers that acts as a program
36119** to test the Bitvec.  The integers are opcodes followed
36120** by 0, 1, or 3 operands, depending on the opcode.  Another
36121** opcode follows immediately after the last operand.
36122**
36123** There are 6 opcodes numbered from 0 through 5.  0 is the
36124** "halt" opcode and causes the test to end.
36125**
36126**    0          Halt and return the number of errors
36127**    1 N S X    Set N bits beginning with S and incrementing by X
36128**    2 N S X    Clear N bits beginning with S and incrementing by X
36129**    3 N        Set N randomly chosen bits
36130**    4 N        Clear N randomly chosen bits
36131**    5 N S X    Set N bits from S increment X in array only, not in bitvec
36132**
36133** The opcodes 1 through 4 perform set and clear operations are performed
36134** on both a Bitvec object and on a linear array of bits obtained from malloc.
36135** Opcode 5 works on the linear array only, not on the Bitvec.
36136** Opcode 5 is used to deliberately induce a fault in order to
36137** confirm that error detection works.
36138**
36139** At the conclusion of the test the linear array is compared
36140** against the Bitvec object.  If there are any differences,
36141** an error is returned.  If they are the same, zero is returned.
36142**
36143** If a memory allocation error occurs, return -1.
36144*/
36145SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
36146  Bitvec *pBitvec = 0;
36147  unsigned char *pV = 0;
36148  int rc = -1;
36149  int i, nx, pc, op;
36150  void *pTmpSpace;
36151
36152  /* Allocate the Bitvec to be tested and a linear array of
36153  ** bits to act as the reference */
36154  pBitvec = sqlite3BitvecCreate( sz );
36155  pV = sqlite3_malloc( (sz+7)/8 + 1 );
36156  pTmpSpace = sqlite3_malloc(BITVEC_SZ);
36157  if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
36158  memset(pV, 0, (sz+7)/8 + 1);
36159
36160  /* NULL pBitvec tests */
36161  sqlite3BitvecSet(0, 1);
36162  sqlite3BitvecClear(0, 1, pTmpSpace);
36163
36164  /* Run the program */
36165  pc = 0;
36166  while( (op = aOp[pc])!=0 ){
36167    switch( op ){
36168      case 1:
36169      case 2:
36170      case 5: {
36171        nx = 4;
36172        i = aOp[pc+2] - 1;
36173        aOp[pc+2] += aOp[pc+3];
36174        break;
36175      }
36176      case 3:
36177      case 4:
36178      default: {
36179        nx = 2;
36180        sqlite3_randomness(sizeof(i), &i);
36181        break;
36182      }
36183    }
36184    if( (--aOp[pc+1]) > 0 ) nx = 0;
36185    pc += nx;
36186    i = (i & 0x7fffffff)%sz;
36187    if( (op & 1)!=0 ){
36188      SETBIT(pV, (i+1));
36189      if( op!=5 ){
36190        if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
36191      }
36192    }else{
36193      CLEARBIT(pV, (i+1));
36194      sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
36195    }
36196  }
36197
36198  /* Test to make sure the linear array exactly matches the
36199  ** Bitvec object.  Start with the assumption that they do
36200  ** match (rc==0).  Change rc to non-zero if a discrepancy
36201  ** is found.
36202  */
36203  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
36204          + sqlite3BitvecTest(pBitvec, 0)
36205          + (sqlite3BitvecSize(pBitvec) - sz);
36206  for(i=1; i<=sz; i++){
36207    if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
36208      rc = i;
36209      break;
36210    }
36211  }
36212
36213  /* Free allocated structure */
36214bitvec_end:
36215  sqlite3_free(pTmpSpace);
36216  sqlite3_free(pV);
36217  sqlite3BitvecDestroy(pBitvec);
36218  return rc;
36219}
36220#endif /* SQLITE_OMIT_BUILTIN_TEST */
36221
36222/************** End of bitvec.c **********************************************/
36223/************** Begin file pcache.c ******************************************/
36224/*
36225** 2008 August 05
36226**
36227** The author disclaims copyright to this source code.  In place of
36228** a legal notice, here is a blessing:
36229**
36230**    May you do good and not evil.
36231**    May you find forgiveness for yourself and forgive others.
36232**    May you share freely, never taking more than you give.
36233**
36234*************************************************************************
36235** This file implements that page cache.
36236*/
36237
36238/*
36239** A complete page cache is an instance of this structure.
36240*/
36241struct PCache {
36242  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
36243  PgHdr *pSynced;                     /* Last synced page in dirty page list */
36244  int nRef;                           /* Number of referenced pages */
36245  int szCache;                        /* Configured cache size */
36246  int szPage;                         /* Size of every page in this cache */
36247  int szExtra;                        /* Size of extra space for each page */
36248  int bPurgeable;                     /* True if pages are on backing store */
36249  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
36250  void *pStress;                      /* Argument to xStress */
36251  sqlite3_pcache *pCache;             /* Pluggable cache module */
36252  PgHdr *pPage1;                      /* Reference to page 1 */
36253};
36254
36255/*
36256** Some of the assert() macros in this code are too expensive to run
36257** even during normal debugging.  Use them only rarely on long-running
36258** tests.  Enable the expensive asserts using the
36259** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
36260*/
36261#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
36262# define expensive_assert(X)  assert(X)
36263#else
36264# define expensive_assert(X)
36265#endif
36266
36267/********************************** Linked List Management ********************/
36268
36269#if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
36270/*
36271** Check that the pCache->pSynced variable is set correctly. If it
36272** is not, either fail an assert or return zero. Otherwise, return
36273** non-zero. This is only used in debugging builds, as follows:
36274**
36275**   expensive_assert( pcacheCheckSynced(pCache) );
36276*/
36277static int pcacheCheckSynced(PCache *pCache){
36278  PgHdr *p;
36279  for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
36280    assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
36281  }
36282  return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
36283}
36284#endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
36285
36286/*
36287** Remove page pPage from the list of dirty pages.
36288*/
36289static void pcacheRemoveFromDirtyList(PgHdr *pPage){
36290  PCache *p = pPage->pCache;
36291
36292  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
36293  assert( pPage->pDirtyPrev || pPage==p->pDirty );
36294
36295  /* Update the PCache1.pSynced variable if necessary. */
36296  if( p->pSynced==pPage ){
36297    PgHdr *pSynced = pPage->pDirtyPrev;
36298    while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
36299      pSynced = pSynced->pDirtyPrev;
36300    }
36301    p->pSynced = pSynced;
36302  }
36303
36304  if( pPage->pDirtyNext ){
36305    pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
36306  }else{
36307    assert( pPage==p->pDirtyTail );
36308    p->pDirtyTail = pPage->pDirtyPrev;
36309  }
36310  if( pPage->pDirtyPrev ){
36311    pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
36312  }else{
36313    assert( pPage==p->pDirty );
36314    p->pDirty = pPage->pDirtyNext;
36315  }
36316  pPage->pDirtyNext = 0;
36317  pPage->pDirtyPrev = 0;
36318
36319  expensive_assert( pcacheCheckSynced(p) );
36320}
36321
36322/*
36323** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
36324** pPage).
36325*/
36326static void pcacheAddToDirtyList(PgHdr *pPage){
36327  PCache *p = pPage->pCache;
36328
36329  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
36330
36331  pPage->pDirtyNext = p->pDirty;
36332  if( pPage->pDirtyNext ){
36333    assert( pPage->pDirtyNext->pDirtyPrev==0 );
36334    pPage->pDirtyNext->pDirtyPrev = pPage;
36335  }
36336  p->pDirty = pPage;
36337  if( !p->pDirtyTail ){
36338    p->pDirtyTail = pPage;
36339  }
36340  if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
36341    p->pSynced = pPage;
36342  }
36343  expensive_assert( pcacheCheckSynced(p) );
36344}
36345
36346/*
36347** Wrapper around the pluggable caches xUnpin method. If the cache is
36348** being used for an in-memory database, this function is a no-op.
36349*/
36350static void pcacheUnpin(PgHdr *p){
36351  PCache *pCache = p->pCache;
36352  if( pCache->bPurgeable ){
36353    if( p->pgno==1 ){
36354      pCache->pPage1 = 0;
36355    }
36356    sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
36357  }
36358}
36359
36360/*************************************************** General Interfaces ******
36361**
36362** Initialize and shutdown the page cache subsystem. Neither of these
36363** functions are threadsafe.
36364*/
36365SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
36366  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
36367    /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
36368    ** built-in default page cache is used instead of the application defined
36369    ** page cache. */
36370    sqlite3PCacheSetDefault();
36371  }
36372  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
36373}
36374SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
36375  if( sqlite3GlobalConfig.pcache2.xShutdown ){
36376    /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
36377    sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
36378  }
36379}
36380
36381/*
36382** Return the size in bytes of a PCache object.
36383*/
36384SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
36385
36386/*
36387** Create a new PCache object. Storage space to hold the object
36388** has already been allocated and is passed in as the p pointer.
36389** The caller discovers how much space needs to be allocated by
36390** calling sqlite3PcacheSize().
36391*/
36392SQLITE_PRIVATE void sqlite3PcacheOpen(
36393  int szPage,                  /* Size of every page */
36394  int szExtra,                 /* Extra space associated with each page */
36395  int bPurgeable,              /* True if pages are on backing store */
36396  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
36397  void *pStress,               /* Argument to xStress */
36398  PCache *p                    /* Preallocated space for the PCache */
36399){
36400  memset(p, 0, sizeof(PCache));
36401  p->szPage = szPage;
36402  p->szExtra = szExtra;
36403  p->bPurgeable = bPurgeable;
36404  p->xStress = xStress;
36405  p->pStress = pStress;
36406  p->szCache = 100;
36407}
36408
36409/*
36410** Change the page size for PCache object. The caller must ensure that there
36411** are no outstanding page references when this function is called.
36412*/
36413SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
36414  assert( pCache->nRef==0 && pCache->pDirty==0 );
36415  if( pCache->pCache ){
36416    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36417    pCache->pCache = 0;
36418    pCache->pPage1 = 0;
36419  }
36420  pCache->szPage = szPage;
36421}
36422
36423/*
36424** Compute the number of pages of cache requested.
36425*/
36426static int numberOfCachePages(PCache *p){
36427  if( p->szCache>=0 ){
36428    return p->szCache;
36429  }else{
36430    return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
36431  }
36432}
36433
36434/*
36435** Try to obtain a page from the cache.
36436*/
36437SQLITE_PRIVATE int sqlite3PcacheFetch(
36438  PCache *pCache,       /* Obtain the page from this cache */
36439  Pgno pgno,            /* Page number to obtain */
36440  int createFlag,       /* If true, create page if it does not exist already */
36441  PgHdr **ppPage        /* Write the page here */
36442){
36443  sqlite3_pcache_page *pPage = 0;
36444  PgHdr *pPgHdr = 0;
36445  int eCreate;
36446
36447  assert( pCache!=0 );
36448  assert( createFlag==1 || createFlag==0 );
36449  assert( pgno>0 );
36450
36451  /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
36452  ** allocate it now.
36453  */
36454  if( !pCache->pCache && createFlag ){
36455    sqlite3_pcache *p;
36456    p = sqlite3GlobalConfig.pcache2.xCreate(
36457        pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
36458    );
36459    if( !p ){
36460      return SQLITE_NOMEM;
36461    }
36462    sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
36463    pCache->pCache = p;
36464  }
36465
36466  eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
36467  if( pCache->pCache ){
36468    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
36469  }
36470
36471  if( !pPage && eCreate==1 ){
36472    PgHdr *pPg;
36473
36474    /* Find a dirty page to write-out and recycle. First try to find a
36475    ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
36476    ** cleared), but if that is not possible settle for any other
36477    ** unreferenced dirty page.
36478    */
36479    expensive_assert( pcacheCheckSynced(pCache) );
36480    for(pPg=pCache->pSynced;
36481        pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
36482        pPg=pPg->pDirtyPrev
36483    );
36484    pCache->pSynced = pPg;
36485    if( !pPg ){
36486      for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
36487    }
36488    if( pPg ){
36489      int rc;
36490#ifdef SQLITE_LOG_CACHE_SPILL
36491      sqlite3_log(SQLITE_FULL,
36492                  "spill page %d making room for %d - cache used: %d/%d",
36493                  pPg->pgno, pgno,
36494                  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
36495                  numberOfCachePages(pCache));
36496#endif
36497      rc = pCache->xStress(pCache->pStress, pPg);
36498      if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
36499        return rc;
36500      }
36501    }
36502
36503    pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
36504  }
36505
36506  if( pPage ){
36507    pPgHdr = (PgHdr *)pPage->pExtra;
36508
36509    if( !pPgHdr->pPage ){
36510      memset(pPgHdr, 0, sizeof(PgHdr));
36511      pPgHdr->pPage = pPage;
36512      pPgHdr->pData = pPage->pBuf;
36513      pPgHdr->pExtra = (void *)&pPgHdr[1];
36514      memset(pPgHdr->pExtra, 0, pCache->szExtra);
36515      pPgHdr->pCache = pCache;
36516      pPgHdr->pgno = pgno;
36517    }
36518    assert( pPgHdr->pCache==pCache );
36519    assert( pPgHdr->pgno==pgno );
36520    assert( pPgHdr->pData==pPage->pBuf );
36521    assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
36522
36523    if( 0==pPgHdr->nRef ){
36524      pCache->nRef++;
36525    }
36526    pPgHdr->nRef++;
36527    if( pgno==1 ){
36528      pCache->pPage1 = pPgHdr;
36529    }
36530  }
36531  *ppPage = pPgHdr;
36532  return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
36533}
36534
36535/*
36536** Decrement the reference count on a page. If the page is clean and the
36537** reference count drops to 0, then it is made elible for recycling.
36538*/
36539SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
36540  assert( p->nRef>0 );
36541  p->nRef--;
36542  if( p->nRef==0 ){
36543    PCache *pCache = p->pCache;
36544    pCache->nRef--;
36545    if( (p->flags&PGHDR_DIRTY)==0 ){
36546      pcacheUnpin(p);
36547    }else{
36548      /* Move the page to the head of the dirty list. */
36549      pcacheRemoveFromDirtyList(p);
36550      pcacheAddToDirtyList(p);
36551    }
36552  }
36553}
36554
36555/*
36556** Increase the reference count of a supplied page by 1.
36557*/
36558SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
36559  assert(p->nRef>0);
36560  p->nRef++;
36561}
36562
36563/*
36564** Drop a page from the cache. There must be exactly one reference to the
36565** page. This function deletes that reference, so after it returns the
36566** page pointed to by p is invalid.
36567*/
36568SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
36569  PCache *pCache;
36570  assert( p->nRef==1 );
36571  if( p->flags&PGHDR_DIRTY ){
36572    pcacheRemoveFromDirtyList(p);
36573  }
36574  pCache = p->pCache;
36575  pCache->nRef--;
36576  if( p->pgno==1 ){
36577    pCache->pPage1 = 0;
36578  }
36579  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
36580}
36581
36582/*
36583** Make sure the page is marked as dirty. If it isn't dirty already,
36584** make it so.
36585*/
36586SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
36587  p->flags &= ~PGHDR_DONT_WRITE;
36588  assert( p->nRef>0 );
36589  if( 0==(p->flags & PGHDR_DIRTY) ){
36590    p->flags |= PGHDR_DIRTY;
36591    pcacheAddToDirtyList( p);
36592  }
36593}
36594
36595/*
36596** Make sure the page is marked as clean. If it isn't clean already,
36597** make it so.
36598*/
36599SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
36600  if( (p->flags & PGHDR_DIRTY) ){
36601    pcacheRemoveFromDirtyList(p);
36602    p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
36603    if( p->nRef==0 ){
36604      pcacheUnpin(p);
36605    }
36606  }
36607}
36608
36609/*
36610** Make every page in the cache clean.
36611*/
36612SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
36613  PgHdr *p;
36614  while( (p = pCache->pDirty)!=0 ){
36615    sqlite3PcacheMakeClean(p);
36616  }
36617}
36618
36619/*
36620** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
36621*/
36622SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
36623  PgHdr *p;
36624  for(p=pCache->pDirty; p; p=p->pDirtyNext){
36625    p->flags &= ~PGHDR_NEED_SYNC;
36626  }
36627  pCache->pSynced = pCache->pDirtyTail;
36628}
36629
36630/*
36631** Change the page number of page p to newPgno.
36632*/
36633SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
36634  PCache *pCache = p->pCache;
36635  assert( p->nRef>0 );
36636  assert( newPgno>0 );
36637  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
36638  p->pgno = newPgno;
36639  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
36640    pcacheRemoveFromDirtyList(p);
36641    pcacheAddToDirtyList(p);
36642  }
36643}
36644
36645/*
36646** Drop every cache entry whose page number is greater than "pgno". The
36647** caller must ensure that there are no outstanding references to any pages
36648** other than page 1 with a page number greater than pgno.
36649**
36650** If there is a reference to page 1 and the pgno parameter passed to this
36651** function is 0, then the data area associated with page 1 is zeroed, but
36652** the page object is not dropped.
36653*/
36654SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
36655  if( pCache->pCache ){
36656    PgHdr *p;
36657    PgHdr *pNext;
36658    for(p=pCache->pDirty; p; p=pNext){
36659      pNext = p->pDirtyNext;
36660      /* This routine never gets call with a positive pgno except right
36661      ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
36662      ** it must be that pgno==0.
36663      */
36664      assert( p->pgno>0 );
36665      if( ALWAYS(p->pgno>pgno) ){
36666        assert( p->flags&PGHDR_DIRTY );
36667        sqlite3PcacheMakeClean(p);
36668      }
36669    }
36670    if( pgno==0 && pCache->pPage1 ){
36671      memset(pCache->pPage1->pData, 0, pCache->szPage);
36672      pgno = 1;
36673    }
36674    sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
36675  }
36676}
36677
36678/*
36679** Close a cache.
36680*/
36681SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
36682  if( pCache->pCache ){
36683    sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36684  }
36685}
36686
36687/*
36688** Discard the contents of the cache.
36689*/
36690SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
36691  sqlite3PcacheTruncate(pCache, 0);
36692}
36693
36694/*
36695** Merge two lists of pages connected by pDirty and in pgno order.
36696** Do not both fixing the pDirtyPrev pointers.
36697*/
36698static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
36699  PgHdr result, *pTail;
36700  pTail = &result;
36701  while( pA && pB ){
36702    if( pA->pgno<pB->pgno ){
36703      pTail->pDirty = pA;
36704      pTail = pA;
36705      pA = pA->pDirty;
36706    }else{
36707      pTail->pDirty = pB;
36708      pTail = pB;
36709      pB = pB->pDirty;
36710    }
36711  }
36712  if( pA ){
36713    pTail->pDirty = pA;
36714  }else if( pB ){
36715    pTail->pDirty = pB;
36716  }else{
36717    pTail->pDirty = 0;
36718  }
36719  return result.pDirty;
36720}
36721
36722/*
36723** Sort the list of pages in accending order by pgno.  Pages are
36724** connected by pDirty pointers.  The pDirtyPrev pointers are
36725** corrupted by this sort.
36726**
36727** Since there cannot be more than 2^31 distinct pages in a database,
36728** there cannot be more than 31 buckets required by the merge sorter.
36729** One extra bucket is added to catch overflow in case something
36730** ever changes to make the previous sentence incorrect.
36731*/
36732#define N_SORT_BUCKET  32
36733static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
36734  PgHdr *a[N_SORT_BUCKET], *p;
36735  int i;
36736  memset(a, 0, sizeof(a));
36737  while( pIn ){
36738    p = pIn;
36739    pIn = p->pDirty;
36740    p->pDirty = 0;
36741    for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
36742      if( a[i]==0 ){
36743        a[i] = p;
36744        break;
36745      }else{
36746        p = pcacheMergeDirtyList(a[i], p);
36747        a[i] = 0;
36748      }
36749    }
36750    if( NEVER(i==N_SORT_BUCKET-1) ){
36751      /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
36752      ** the input list.  But that is impossible.
36753      */
36754      a[i] = pcacheMergeDirtyList(a[i], p);
36755    }
36756  }
36757  p = a[0];
36758  for(i=1; i<N_SORT_BUCKET; i++){
36759    p = pcacheMergeDirtyList(p, a[i]);
36760  }
36761  return p;
36762}
36763
36764/*
36765** Return a list of all dirty pages in the cache, sorted by page number.
36766*/
36767SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
36768  PgHdr *p;
36769  for(p=pCache->pDirty; p; p=p->pDirtyNext){
36770    p->pDirty = p->pDirtyNext;
36771  }
36772  return pcacheSortDirtyList(pCache->pDirty);
36773}
36774
36775/*
36776** Return the total number of referenced pages held by the cache.
36777*/
36778SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
36779  return pCache->nRef;
36780}
36781
36782/*
36783** Return the number of references to the page supplied as an argument.
36784*/
36785SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
36786  return p->nRef;
36787}
36788
36789/*
36790** Return the total number of pages in the cache.
36791*/
36792SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
36793  int nPage = 0;
36794  if( pCache->pCache ){
36795    nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
36796  }
36797  return nPage;
36798}
36799
36800#ifdef SQLITE_TEST
36801/*
36802** Get the suggested cache-size value.
36803*/
36804SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
36805  return numberOfCachePages(pCache);
36806}
36807#endif
36808
36809/*
36810** Set the suggested cache-size value.
36811*/
36812SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
36813  pCache->szCache = mxPage;
36814  if( pCache->pCache ){
36815    sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
36816                                           numberOfCachePages(pCache));
36817  }
36818}
36819
36820/*
36821** Free up as much memory as possible from the page cache.
36822*/
36823SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
36824  if( pCache->pCache ){
36825    sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
36826  }
36827}
36828
36829#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
36830/*
36831** For all dirty pages currently in the cache, invoke the specified
36832** callback. This is only used if the SQLITE_CHECK_PAGES macro is
36833** defined.
36834*/
36835SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
36836  PgHdr *pDirty;
36837  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
36838    xIter(pDirty);
36839  }
36840}
36841#endif
36842
36843/************** End of pcache.c **********************************************/
36844/************** Begin file pcache1.c *****************************************/
36845/*
36846** 2008 November 05
36847**
36848** The author disclaims copyright to this source code.  In place of
36849** a legal notice, here is a blessing:
36850**
36851**    May you do good and not evil.
36852**    May you find forgiveness for yourself and forgive others.
36853**    May you share freely, never taking more than you give.
36854**
36855*************************************************************************
36856**
36857** This file implements the default page cache implementation (the
36858** sqlite3_pcache interface). It also contains part of the implementation
36859** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
36860** If the default page cache implementation is overriden, then neither of
36861** these two features are available.
36862*/
36863
36864
36865typedef struct PCache1 PCache1;
36866typedef struct PgHdr1 PgHdr1;
36867typedef struct PgFreeslot PgFreeslot;
36868typedef struct PGroup PGroup;
36869
36870/* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set
36871** of one or more PCaches that are able to recycle each others unpinned
36872** pages when they are under memory pressure.  A PGroup is an instance of
36873** the following object.
36874**
36875** This page cache implementation works in one of two modes:
36876**
36877**   (1)  Every PCache is the sole member of its own PGroup.  There is
36878**        one PGroup per PCache.
36879**
36880**   (2)  There is a single global PGroup that all PCaches are a member
36881**        of.
36882**
36883** Mode 1 uses more memory (since PCache instances are not able to rob
36884** unused pages from other PCaches) but it also operates without a mutex,
36885** and is therefore often faster.  Mode 2 requires a mutex in order to be
36886** threadsafe, but recycles pages more efficiently.
36887**
36888** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
36889** PGroup which is the pcache1.grp global variable and its mutex is
36890** SQLITE_MUTEX_STATIC_LRU.
36891*/
36892struct PGroup {
36893  sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
36894  unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
36895  unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
36896  unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
36897  unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
36898  PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
36899};
36900
36901/* Each page cache is an instance of the following object.  Every
36902** open database file (including each in-memory database and each
36903** temporary or transient database) has a single page cache which
36904** is an instance of this object.
36905**
36906** Pointers to structures of this type are cast and returned as
36907** opaque sqlite3_pcache* handles.
36908*/
36909struct PCache1 {
36910  /* Cache configuration parameters. Page size (szPage) and the purgeable
36911  ** flag (bPurgeable) are set when the cache is created. nMax may be
36912  ** modified at any time by a call to the pcache1Cachesize() method.
36913  ** The PGroup mutex must be held when accessing nMax.
36914  */
36915  PGroup *pGroup;                     /* PGroup this cache belongs to */
36916  int szPage;                         /* Size of allocated pages in bytes */
36917  int szExtra;                        /* Size of extra space in bytes */
36918  int bPurgeable;                     /* True if cache is purgeable */
36919  unsigned int nMin;                  /* Minimum number of pages reserved */
36920  unsigned int nMax;                  /* Configured "cache_size" value */
36921  unsigned int n90pct;                /* nMax*9/10 */
36922  unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
36923
36924  /* Hash table of all pages. The following variables may only be accessed
36925  ** when the accessor is holding the PGroup mutex.
36926  */
36927  unsigned int nRecyclable;           /* Number of pages in the LRU list */
36928  unsigned int nPage;                 /* Total number of pages in apHash */
36929  unsigned int nHash;                 /* Number of slots in apHash[] */
36930  PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
36931};
36932
36933/*
36934** Each cache entry is represented by an instance of the following
36935** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
36936** PgHdr1.pCache->szPage bytes is allocated directly before this structure
36937** in memory.
36938*/
36939struct PgHdr1 {
36940  sqlite3_pcache_page page;
36941  unsigned int iKey;             /* Key value (page number) */
36942  PgHdr1 *pNext;                 /* Next in hash table chain */
36943  PCache1 *pCache;               /* Cache that currently owns this page */
36944  PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
36945  PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
36946};
36947
36948/*
36949** Free slots in the allocator used to divide up the buffer provided using
36950** the SQLITE_CONFIG_PAGECACHE mechanism.
36951*/
36952struct PgFreeslot {
36953  PgFreeslot *pNext;  /* Next free slot */
36954};
36955
36956/*
36957** Global data used by this cache.
36958*/
36959static SQLITE_WSD struct PCacheGlobal {
36960  PGroup grp;                    /* The global PGroup for mode (2) */
36961
36962  /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
36963  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
36964  ** fixed at sqlite3_initialize() time and do not require mutex protection.
36965  ** The nFreeSlot and pFree values do require mutex protection.
36966  */
36967  int isInit;                    /* True if initialized */
36968  int szSlot;                    /* Size of each free slot */
36969  int nSlot;                     /* The number of pcache slots */
36970  int nReserve;                  /* Try to keep nFreeSlot above this */
36971  void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
36972  /* Above requires no mutex.  Use mutex below for variable that follow. */
36973  sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
36974  PgFreeslot *pFree;             /* Free page blocks */
36975  int nFreeSlot;                 /* Number of unused pcache slots */
36976  /* The following value requires a mutex to change.  We skip the mutex on
36977  ** reading because (1) most platforms read a 32-bit integer atomically and
36978  ** (2) even if an incorrect value is read, no great harm is done since this
36979  ** is really just an optimization. */
36980  int bUnderPressure;            /* True if low on PAGECACHE memory */
36981} pcache1_g;
36982
36983/*
36984** All code in this file should access the global structure above via the
36985** alias "pcache1". This ensures that the WSD emulation is used when
36986** compiling for systems that do not support real WSD.
36987*/
36988#define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
36989
36990/*
36991** Macros to enter and leave the PCache LRU mutex.
36992*/
36993#define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
36994#define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
36995
36996/******************************************************************************/
36997/******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
36998
36999/*
37000** This function is called during initialization if a static buffer is
37001** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
37002** verb to sqlite3_config(). Parameter pBuf points to an allocation large
37003** enough to contain 'n' buffers of 'sz' bytes each.
37004**
37005** This routine is called from sqlite3_initialize() and so it is guaranteed
37006** to be serialized already.  There is no need for further mutexing.
37007*/
37008SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
37009  if( pcache1.isInit ){
37010    PgFreeslot *p;
37011    sz = ROUNDDOWN8(sz);
37012    pcache1.szSlot = sz;
37013    pcache1.nSlot = pcache1.nFreeSlot = n;
37014    pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
37015    pcache1.pStart = pBuf;
37016    pcache1.pFree = 0;
37017    pcache1.bUnderPressure = 0;
37018    while( n-- ){
37019      p = (PgFreeslot*)pBuf;
37020      p->pNext = pcache1.pFree;
37021      pcache1.pFree = p;
37022      pBuf = (void*)&((char*)pBuf)[sz];
37023    }
37024    pcache1.pEnd = pBuf;
37025  }
37026}
37027
37028/*
37029** Malloc function used within this file to allocate space from the buffer
37030** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
37031** such buffer exists or there is no space left in it, this function falls
37032** back to sqlite3Malloc().
37033**
37034** Multiple threads can run this routine at the same time.  Global variables
37035** in pcache1 need to be protected via mutex.
37036*/
37037static void *pcache1Alloc(int nByte){
37038  void *p = 0;
37039  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37040  sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
37041  if( nByte<=pcache1.szSlot ){
37042    sqlite3_mutex_enter(pcache1.mutex);
37043    p = (PgHdr1 *)pcache1.pFree;
37044    if( p ){
37045      pcache1.pFree = pcache1.pFree->pNext;
37046      pcache1.nFreeSlot--;
37047      pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37048      assert( pcache1.nFreeSlot>=0 );
37049      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
37050    }
37051    sqlite3_mutex_leave(pcache1.mutex);
37052  }
37053  if( p==0 ){
37054    /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
37055    ** it from sqlite3Malloc instead.
37056    */
37057    p = sqlite3Malloc(nByte);
37058    if( p ){
37059      int sz = sqlite3MallocSize(p);
37060      sqlite3_mutex_enter(pcache1.mutex);
37061      sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
37062      sqlite3_mutex_leave(pcache1.mutex);
37063    }
37064    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
37065  }
37066  return p;
37067}
37068
37069/*
37070** Free an allocated buffer obtained from pcache1Alloc().
37071*/
37072static int pcache1Free(void *p){
37073  int nFreed = 0;
37074  if( p==0 ) return 0;
37075  if( p>=pcache1.pStart && p<pcache1.pEnd ){
37076    PgFreeslot *pSlot;
37077    sqlite3_mutex_enter(pcache1.mutex);
37078    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
37079    pSlot = (PgFreeslot*)p;
37080    pSlot->pNext = pcache1.pFree;
37081    pcache1.pFree = pSlot;
37082    pcache1.nFreeSlot++;
37083    pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
37084    assert( pcache1.nFreeSlot<=pcache1.nSlot );
37085    sqlite3_mutex_leave(pcache1.mutex);
37086  }else{
37087    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
37088    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
37089    nFreed = sqlite3MallocSize(p);
37090    sqlite3_mutex_enter(pcache1.mutex);
37091    sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
37092    sqlite3_mutex_leave(pcache1.mutex);
37093    sqlite3_free(p);
37094  }
37095  return nFreed;
37096}
37097
37098#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
37099/*
37100** Return the size of a pcache allocation
37101*/
37102static int pcache1MemSize(void *p){
37103  if( p>=pcache1.pStart && p<pcache1.pEnd ){
37104    return pcache1.szSlot;
37105  }else{
37106    int iSize;
37107    assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
37108    sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
37109    iSize = sqlite3MallocSize(p);
37110    sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
37111    return iSize;
37112  }
37113}
37114#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
37115
37116/*
37117** Allocate a new page object initially associated with cache pCache.
37118*/
37119static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
37120  PgHdr1 *p = 0;
37121  void *pPg;
37122
37123  /* The group mutex must be released before pcache1Alloc() is called. This
37124  ** is because it may call sqlite3_release_memory(), which assumes that
37125  ** this mutex is not held. */
37126  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37127  pcache1LeaveMutex(pCache->pGroup);
37128#ifdef SQLITE_PCACHE_SEPARATE_HEADER
37129  pPg = pcache1Alloc(pCache->szPage);
37130  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
37131  if( !pPg || !p ){
37132    pcache1Free(pPg);
37133    sqlite3_free(p);
37134    pPg = 0;
37135  }
37136#else
37137  pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
37138  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
37139#endif
37140  pcache1EnterMutex(pCache->pGroup);
37141
37142  if( pPg ){
37143    p->page.pBuf = pPg;
37144    p->page.pExtra = &p[1];
37145    if( pCache->bPurgeable ){
37146      pCache->pGroup->nCurrentPage++;
37147    }
37148    return p;
37149  }
37150  return 0;
37151}
37152
37153/*
37154** Free a page object allocated by pcache1AllocPage().
37155**
37156** The pointer is allowed to be NULL, which is prudent.  But it turns out
37157** that the current implementation happens to never call this routine
37158** with a NULL pointer, so we mark the NULL test with ALWAYS().
37159*/
37160static void pcache1FreePage(PgHdr1 *p){
37161  if( ALWAYS(p) ){
37162    PCache1 *pCache = p->pCache;
37163    assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
37164    pcache1Free(p->page.pBuf);
37165#ifdef SQLITE_PCACHE_SEPARATE_HEADER
37166    sqlite3_free(p);
37167#endif
37168    if( pCache->bPurgeable ){
37169      pCache->pGroup->nCurrentPage--;
37170    }
37171  }
37172}
37173
37174/*
37175** Malloc function used by SQLite to obtain space from the buffer configured
37176** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
37177** exists, this function falls back to sqlite3Malloc().
37178*/
37179SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
37180  return pcache1Alloc(sz);
37181}
37182
37183/*
37184** Free an allocated buffer obtained from sqlite3PageMalloc().
37185*/
37186SQLITE_PRIVATE void sqlite3PageFree(void *p){
37187  pcache1Free(p);
37188}
37189
37190
37191/*
37192** Return true if it desirable to avoid allocating a new page cache
37193** entry.
37194**
37195** If memory was allocated specifically to the page cache using
37196** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
37197** it is desirable to avoid allocating a new page cache entry because
37198** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
37199** for all page cache needs and we should not need to spill the
37200** allocation onto the heap.
37201**
37202** Or, the heap is used for all page cache memory but the heap is
37203** under memory pressure, then again it is desirable to avoid
37204** allocating a new page cache entry in order to avoid stressing
37205** the heap even further.
37206*/
37207static int pcache1UnderMemoryPressure(PCache1 *pCache){
37208  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
37209    return pcache1.bUnderPressure;
37210  }else{
37211    return sqlite3HeapNearlyFull();
37212  }
37213}
37214
37215/******************************************************************************/
37216/******** General Implementation Functions ************************************/
37217
37218/*
37219** This function is used to resize the hash table used by the cache passed
37220** as the first argument.
37221**
37222** The PCache mutex must be held when this function is called.
37223*/
37224static int pcache1ResizeHash(PCache1 *p){
37225  PgHdr1 **apNew;
37226  unsigned int nNew;
37227  unsigned int i;
37228
37229  assert( sqlite3_mutex_held(p->pGroup->mutex) );
37230
37231  nNew = p->nHash*2;
37232  if( nNew<256 ){
37233    nNew = 256;
37234  }
37235
37236  pcache1LeaveMutex(p->pGroup);
37237  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
37238  apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
37239  if( p->nHash ){ sqlite3EndBenignMalloc(); }
37240  pcache1EnterMutex(p->pGroup);
37241  if( apNew ){
37242    memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
37243    for(i=0; i<p->nHash; i++){
37244      PgHdr1 *pPage;
37245      PgHdr1 *pNext = p->apHash[i];
37246      while( (pPage = pNext)!=0 ){
37247        unsigned int h = pPage->iKey % nNew;
37248        pNext = pPage->pNext;
37249        pPage->pNext = apNew[h];
37250        apNew[h] = pPage;
37251      }
37252    }
37253    sqlite3_free(p->apHash);
37254    p->apHash = apNew;
37255    p->nHash = nNew;
37256  }
37257
37258  return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
37259}
37260
37261/*
37262** This function is used internally to remove the page pPage from the
37263** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
37264** LRU list, then this function is a no-op.
37265**
37266** The PGroup mutex must be held when this function is called.
37267**
37268** If pPage is NULL then this routine is a no-op.
37269*/
37270static void pcache1PinPage(PgHdr1 *pPage){
37271  PCache1 *pCache;
37272  PGroup *pGroup;
37273
37274  if( pPage==0 ) return;
37275  pCache = pPage->pCache;
37276  pGroup = pCache->pGroup;
37277  assert( sqlite3_mutex_held(pGroup->mutex) );
37278  if( pPage->pLruNext || pPage==pGroup->pLruTail ){
37279    if( pPage->pLruPrev ){
37280      pPage->pLruPrev->pLruNext = pPage->pLruNext;
37281    }
37282    if( pPage->pLruNext ){
37283      pPage->pLruNext->pLruPrev = pPage->pLruPrev;
37284    }
37285    if( pGroup->pLruHead==pPage ){
37286      pGroup->pLruHead = pPage->pLruNext;
37287    }
37288    if( pGroup->pLruTail==pPage ){
37289      pGroup->pLruTail = pPage->pLruPrev;
37290    }
37291    pPage->pLruNext = 0;
37292    pPage->pLruPrev = 0;
37293    pPage->pCache->nRecyclable--;
37294  }
37295}
37296
37297
37298/*
37299** Remove the page supplied as an argument from the hash table
37300** (PCache1.apHash structure) that it is currently stored in.
37301**
37302** The PGroup mutex must be held when this function is called.
37303*/
37304static void pcache1RemoveFromHash(PgHdr1 *pPage){
37305  unsigned int h;
37306  PCache1 *pCache = pPage->pCache;
37307  PgHdr1 **pp;
37308
37309  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37310  h = pPage->iKey % pCache->nHash;
37311  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
37312  *pp = (*pp)->pNext;
37313
37314  pCache->nPage--;
37315}
37316
37317/*
37318** If there are currently more than nMaxPage pages allocated, try
37319** to recycle pages to reduce the number allocated to nMaxPage.
37320*/
37321static void pcache1EnforceMaxPage(PGroup *pGroup){
37322  assert( sqlite3_mutex_held(pGroup->mutex) );
37323  while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
37324    PgHdr1 *p = pGroup->pLruTail;
37325    assert( p->pCache->pGroup==pGroup );
37326    pcache1PinPage(p);
37327    pcache1RemoveFromHash(p);
37328    pcache1FreePage(p);
37329  }
37330}
37331
37332/*
37333** Discard all pages from cache pCache with a page number (key value)
37334** greater than or equal to iLimit. Any pinned pages that meet this
37335** criteria are unpinned before they are discarded.
37336**
37337** The PCache mutex must be held when this function is called.
37338*/
37339static void pcache1TruncateUnsafe(
37340  PCache1 *pCache,             /* The cache to truncate */
37341  unsigned int iLimit          /* Drop pages with this pgno or larger */
37342){
37343  TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
37344  unsigned int h;
37345  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37346  for(h=0; h<pCache->nHash; h++){
37347    PgHdr1 **pp = &pCache->apHash[h];
37348    PgHdr1 *pPage;
37349    while( (pPage = *pp)!=0 ){
37350      if( pPage->iKey>=iLimit ){
37351        pCache->nPage--;
37352        *pp = pPage->pNext;
37353        pcache1PinPage(pPage);
37354        pcache1FreePage(pPage);
37355      }else{
37356        pp = &pPage->pNext;
37357        TESTONLY( nPage++; )
37358      }
37359    }
37360  }
37361  assert( pCache->nPage==nPage );
37362}
37363
37364/******************************************************************************/
37365/******** sqlite3_pcache Methods **********************************************/
37366
37367/*
37368** Implementation of the sqlite3_pcache.xInit method.
37369*/
37370static int pcache1Init(void *NotUsed){
37371  UNUSED_PARAMETER(NotUsed);
37372  assert( pcache1.isInit==0 );
37373  memset(&pcache1, 0, sizeof(pcache1));
37374  if( sqlite3GlobalConfig.bCoreMutex ){
37375    pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
37376    pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
37377  }
37378  pcache1.grp.mxPinned = 10;
37379  pcache1.isInit = 1;
37380  return SQLITE_OK;
37381}
37382
37383/*
37384** Implementation of the sqlite3_pcache.xShutdown method.
37385** Note that the static mutex allocated in xInit does
37386** not need to be freed.
37387*/
37388static void pcache1Shutdown(void *NotUsed){
37389  UNUSED_PARAMETER(NotUsed);
37390  assert( pcache1.isInit!=0 );
37391  memset(&pcache1, 0, sizeof(pcache1));
37392}
37393
37394/*
37395** Implementation of the sqlite3_pcache.xCreate method.
37396**
37397** Allocate a new cache.
37398*/
37399static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
37400  PCache1 *pCache;      /* The newly created page cache */
37401  PGroup *pGroup;       /* The group the new page cache will belong to */
37402  int sz;               /* Bytes of memory required to allocate the new cache */
37403
37404  /*
37405  ** The seperateCache variable is true if each PCache has its own private
37406  ** PGroup.  In other words, separateCache is true for mode (1) where no
37407  ** mutexing is required.
37408  **
37409  **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
37410  **
37411  **   *  Always use a unified cache in single-threaded applications
37412  **
37413  **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
37414  **      use separate caches (mode-1)
37415  */
37416#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
37417  const int separateCache = 0;
37418#else
37419  int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
37420#endif
37421
37422  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
37423  assert( szExtra < 300 );
37424
37425  sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
37426  pCache = (PCache1 *)sqlite3_malloc(sz);
37427  if( pCache ){
37428    memset(pCache, 0, sz);
37429    if( separateCache ){
37430      pGroup = (PGroup*)&pCache[1];
37431      pGroup->mxPinned = 10;
37432    }else{
37433      pGroup = &pcache1.grp;
37434    }
37435    pCache->pGroup = pGroup;
37436    pCache->szPage = szPage;
37437    pCache->szExtra = szExtra;
37438    pCache->bPurgeable = (bPurgeable ? 1 : 0);
37439    if( bPurgeable ){
37440      pCache->nMin = 10;
37441      pcache1EnterMutex(pGroup);
37442      pGroup->nMinPage += pCache->nMin;
37443      pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37444      pcache1LeaveMutex(pGroup);
37445    }
37446  }
37447  return (sqlite3_pcache *)pCache;
37448}
37449
37450/*
37451** Implementation of the sqlite3_pcache.xCachesize method.
37452**
37453** Configure the cache_size limit for a cache.
37454*/
37455static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
37456  PCache1 *pCache = (PCache1 *)p;
37457  if( pCache->bPurgeable ){
37458    PGroup *pGroup = pCache->pGroup;
37459    pcache1EnterMutex(pGroup);
37460    pGroup->nMaxPage += (nMax - pCache->nMax);
37461    pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37462    pCache->nMax = nMax;
37463    pCache->n90pct = pCache->nMax*9/10;
37464    pcache1EnforceMaxPage(pGroup);
37465    pcache1LeaveMutex(pGroup);
37466  }
37467}
37468
37469/*
37470** Implementation of the sqlite3_pcache.xShrink method.
37471**
37472** Free up as much memory as possible.
37473*/
37474static void pcache1Shrink(sqlite3_pcache *p){
37475  PCache1 *pCache = (PCache1*)p;
37476  if( pCache->bPurgeable ){
37477    PGroup *pGroup = pCache->pGroup;
37478    int savedMaxPage;
37479    pcache1EnterMutex(pGroup);
37480    savedMaxPage = pGroup->nMaxPage;
37481    pGroup->nMaxPage = 0;
37482    pcache1EnforceMaxPage(pGroup);
37483    pGroup->nMaxPage = savedMaxPage;
37484    pcache1LeaveMutex(pGroup);
37485  }
37486}
37487
37488/*
37489** Implementation of the sqlite3_pcache.xPagecount method.
37490*/
37491static int pcache1Pagecount(sqlite3_pcache *p){
37492  int n;
37493  PCache1 *pCache = (PCache1*)p;
37494  pcache1EnterMutex(pCache->pGroup);
37495  n = pCache->nPage;
37496  pcache1LeaveMutex(pCache->pGroup);
37497  return n;
37498}
37499
37500/*
37501** Implementation of the sqlite3_pcache.xFetch method.
37502**
37503** Fetch a page by key value.
37504**
37505** Whether or not a new page may be allocated by this function depends on
37506** the value of the createFlag argument.  0 means do not allocate a new
37507** page.  1 means allocate a new page if space is easily available.  2
37508** means to try really hard to allocate a new page.
37509**
37510** For a non-purgeable cache (a cache used as the storage for an in-memory
37511** database) there is really no difference between createFlag 1 and 2.  So
37512** the calling function (pcache.c) will never have a createFlag of 1 on
37513** a non-purgeable cache.
37514**
37515** There are three different approaches to obtaining space for a page,
37516** depending on the value of parameter createFlag (which may be 0, 1 or 2).
37517**
37518**   1. Regardless of the value of createFlag, the cache is searched for a
37519**      copy of the requested page. If one is found, it is returned.
37520**
37521**   2. If createFlag==0 and the page is not already in the cache, NULL is
37522**      returned.
37523**
37524**   3. If createFlag is 1, and the page is not already in the cache, then
37525**      return NULL (do not allocate a new page) if any of the following
37526**      conditions are true:
37527**
37528**       (a) the number of pages pinned by the cache is greater than
37529**           PCache1.nMax, or
37530**
37531**       (b) the number of pages pinned by the cache is greater than
37532**           the sum of nMax for all purgeable caches, less the sum of
37533**           nMin for all other purgeable caches, or
37534**
37535**   4. If none of the first three conditions apply and the cache is marked
37536**      as purgeable, and if one of the following is true:
37537**
37538**       (a) The number of pages allocated for the cache is already
37539**           PCache1.nMax, or
37540**
37541**       (b) The number of pages allocated for all purgeable caches is
37542**           already equal to or greater than the sum of nMax for all
37543**           purgeable caches,
37544**
37545**       (c) The system is under memory pressure and wants to avoid
37546**           unnecessary pages cache entry allocations
37547**
37548**      then attempt to recycle a page from the LRU list. If it is the right
37549**      size, return the recycled buffer. Otherwise, free the buffer and
37550**      proceed to step 5.
37551**
37552**   5. Otherwise, allocate and return a new page buffer.
37553*/
37554static sqlite3_pcache_page *pcache1Fetch(
37555  sqlite3_pcache *p,
37556  unsigned int iKey,
37557  int createFlag
37558){
37559  unsigned int nPinned;
37560  PCache1 *pCache = (PCache1 *)p;
37561  PGroup *pGroup;
37562  PgHdr1 *pPage = 0;
37563
37564  assert( pCache->bPurgeable || createFlag!=1 );
37565  assert( pCache->bPurgeable || pCache->nMin==0 );
37566  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
37567  assert( pCache->nMin==0 || pCache->bPurgeable );
37568  pcache1EnterMutex(pGroup = pCache->pGroup);
37569
37570  /* Step 1: Search the hash table for an existing entry. */
37571  if( pCache->nHash>0 ){
37572    unsigned int h = iKey % pCache->nHash;
37573    for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
37574  }
37575
37576  /* Step 2: Abort if no existing page is found and createFlag is 0 */
37577  if( pPage || createFlag==0 ){
37578    pcache1PinPage(pPage);
37579    goto fetch_out;
37580  }
37581
37582  /* The pGroup local variable will normally be initialized by the
37583  ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
37584  ** then pcache1EnterMutex() is a no-op, so we have to initialize the
37585  ** local variable here.  Delaying the initialization of pGroup is an
37586  ** optimization:  The common case is to exit the module before reaching
37587  ** this point.
37588  */
37589#ifdef SQLITE_MUTEX_OMIT
37590  pGroup = pCache->pGroup;
37591#endif
37592
37593  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
37594  assert( pCache->nPage >= pCache->nRecyclable );
37595  nPinned = pCache->nPage - pCache->nRecyclable;
37596  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
37597  assert( pCache->n90pct == pCache->nMax*9/10 );
37598  if( createFlag==1 && (
37599        nPinned>=pGroup->mxPinned
37600     || nPinned>=pCache->n90pct
37601     || pcache1UnderMemoryPressure(pCache)
37602  )){
37603    goto fetch_out;
37604  }
37605
37606  if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
37607    goto fetch_out;
37608  }
37609
37610  /* Step 4. Try to recycle a page. */
37611  if( pCache->bPurgeable && pGroup->pLruTail && (
37612         (pCache->nPage+1>=pCache->nMax)
37613      || pGroup->nCurrentPage>=pGroup->nMaxPage
37614      || pcache1UnderMemoryPressure(pCache)
37615  )){
37616    PCache1 *pOther;
37617    pPage = pGroup->pLruTail;
37618    pcache1RemoveFromHash(pPage);
37619    pcache1PinPage(pPage);
37620    pOther = pPage->pCache;
37621
37622    /* We want to verify that szPage and szExtra are the same for pOther
37623    ** and pCache.  Assert that we can verify this by comparing sums. */
37624    assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
37625    assert( pCache->szExtra<512 );
37626    assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
37627    assert( pOther->szExtra<512 );
37628
37629    if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
37630      pcache1FreePage(pPage);
37631      pPage = 0;
37632    }else{
37633      pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
37634    }
37635  }
37636
37637  /* Step 5. If a usable page buffer has still not been found,
37638  ** attempt to allocate a new one.
37639  */
37640  if( !pPage ){
37641    if( createFlag==1 ) sqlite3BeginBenignMalloc();
37642    pPage = pcache1AllocPage(pCache);
37643    if( createFlag==1 ) sqlite3EndBenignMalloc();
37644  }
37645
37646  if( pPage ){
37647    unsigned int h = iKey % pCache->nHash;
37648    pCache->nPage++;
37649    pPage->iKey = iKey;
37650    pPage->pNext = pCache->apHash[h];
37651    pPage->pCache = pCache;
37652    pPage->pLruPrev = 0;
37653    pPage->pLruNext = 0;
37654    *(void **)pPage->page.pExtra = 0;
37655    pCache->apHash[h] = pPage;
37656  }
37657
37658fetch_out:
37659  if( pPage && iKey>pCache->iMaxKey ){
37660    pCache->iMaxKey = iKey;
37661  }
37662  pcache1LeaveMutex(pGroup);
37663  return &pPage->page;
37664}
37665
37666
37667/*
37668** Implementation of the sqlite3_pcache.xUnpin method.
37669**
37670** Mark a page as unpinned (eligible for asynchronous recycling).
37671*/
37672static void pcache1Unpin(
37673  sqlite3_pcache *p,
37674  sqlite3_pcache_page *pPg,
37675  int reuseUnlikely
37676){
37677  PCache1 *pCache = (PCache1 *)p;
37678  PgHdr1 *pPage = (PgHdr1 *)pPg;
37679  PGroup *pGroup = pCache->pGroup;
37680
37681  assert( pPage->pCache==pCache );
37682  pcache1EnterMutex(pGroup);
37683
37684  /* It is an error to call this function if the page is already
37685  ** part of the PGroup LRU list.
37686  */
37687  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
37688  assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
37689
37690  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
37691    pcache1RemoveFromHash(pPage);
37692    pcache1FreePage(pPage);
37693  }else{
37694    /* Add the page to the PGroup LRU list. */
37695    if( pGroup->pLruHead ){
37696      pGroup->pLruHead->pLruPrev = pPage;
37697      pPage->pLruNext = pGroup->pLruHead;
37698      pGroup->pLruHead = pPage;
37699    }else{
37700      pGroup->pLruTail = pPage;
37701      pGroup->pLruHead = pPage;
37702    }
37703    pCache->nRecyclable++;
37704  }
37705
37706  pcache1LeaveMutex(pCache->pGroup);
37707}
37708
37709/*
37710** Implementation of the sqlite3_pcache.xRekey method.
37711*/
37712static void pcache1Rekey(
37713  sqlite3_pcache *p,
37714  sqlite3_pcache_page *pPg,
37715  unsigned int iOld,
37716  unsigned int iNew
37717){
37718  PCache1 *pCache = (PCache1 *)p;
37719  PgHdr1 *pPage = (PgHdr1 *)pPg;
37720  PgHdr1 **pp;
37721  unsigned int h;
37722  assert( pPage->iKey==iOld );
37723  assert( pPage->pCache==pCache );
37724
37725  pcache1EnterMutex(pCache->pGroup);
37726
37727  h = iOld%pCache->nHash;
37728  pp = &pCache->apHash[h];
37729  while( (*pp)!=pPage ){
37730    pp = &(*pp)->pNext;
37731  }
37732  *pp = pPage->pNext;
37733
37734  h = iNew%pCache->nHash;
37735  pPage->iKey = iNew;
37736  pPage->pNext = pCache->apHash[h];
37737  pCache->apHash[h] = pPage;
37738  if( iNew>pCache->iMaxKey ){
37739    pCache->iMaxKey = iNew;
37740  }
37741
37742  pcache1LeaveMutex(pCache->pGroup);
37743}
37744
37745/*
37746** Implementation of the sqlite3_pcache.xTruncate method.
37747**
37748** Discard all unpinned pages in the cache with a page number equal to
37749** or greater than parameter iLimit. Any pinned pages with a page number
37750** equal to or greater than iLimit are implicitly unpinned.
37751*/
37752static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
37753  PCache1 *pCache = (PCache1 *)p;
37754  pcache1EnterMutex(pCache->pGroup);
37755  if( iLimit<=pCache->iMaxKey ){
37756    pcache1TruncateUnsafe(pCache, iLimit);
37757    pCache->iMaxKey = iLimit-1;
37758  }
37759  pcache1LeaveMutex(pCache->pGroup);
37760}
37761
37762/*
37763** Implementation of the sqlite3_pcache.xDestroy method.
37764**
37765** Destroy a cache allocated using pcache1Create().
37766*/
37767static void pcache1Destroy(sqlite3_pcache *p){
37768  PCache1 *pCache = (PCache1 *)p;
37769  PGroup *pGroup = pCache->pGroup;
37770  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
37771  pcache1EnterMutex(pGroup);
37772  pcache1TruncateUnsafe(pCache, 0);
37773  assert( pGroup->nMaxPage >= pCache->nMax );
37774  pGroup->nMaxPage -= pCache->nMax;
37775  assert( pGroup->nMinPage >= pCache->nMin );
37776  pGroup->nMinPage -= pCache->nMin;
37777  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37778  pcache1EnforceMaxPage(pGroup);
37779  pcache1LeaveMutex(pGroup);
37780  sqlite3_free(pCache->apHash);
37781  sqlite3_free(pCache);
37782}
37783
37784/*
37785** This function is called during initialization (sqlite3_initialize()) to
37786** install the default pluggable cache module, assuming the user has not
37787** already provided an alternative.
37788*/
37789SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
37790  static const sqlite3_pcache_methods2 defaultMethods = {
37791    1,                       /* iVersion */
37792    0,                       /* pArg */
37793    pcache1Init,             /* xInit */
37794    pcache1Shutdown,         /* xShutdown */
37795    pcache1Create,           /* xCreate */
37796    pcache1Cachesize,        /* xCachesize */
37797    pcache1Pagecount,        /* xPagecount */
37798    pcache1Fetch,            /* xFetch */
37799    pcache1Unpin,            /* xUnpin */
37800    pcache1Rekey,            /* xRekey */
37801    pcache1Truncate,         /* xTruncate */
37802    pcache1Destroy,          /* xDestroy */
37803    pcache1Shrink            /* xShrink */
37804  };
37805  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
37806}
37807
37808#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
37809/*
37810** This function is called to free superfluous dynamically allocated memory
37811** held by the pager system. Memory in use by any SQLite pager allocated
37812** by the current thread may be sqlite3_free()ed.
37813**
37814** nReq is the number of bytes of memory required. Once this much has
37815** been released, the function returns. The return value is the total number
37816** of bytes of memory released.
37817*/
37818SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
37819  int nFree = 0;
37820  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37821  assert( sqlite3_mutex_notheld(pcache1.mutex) );
37822  if( pcache1.pStart==0 ){
37823    PgHdr1 *p;
37824    pcache1EnterMutex(&pcache1.grp);
37825    while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
37826      nFree += pcache1MemSize(p->page.pBuf);
37827#ifdef SQLITE_PCACHE_SEPARATE_HEADER
37828      nFree += sqlite3MemSize(p);
37829#endif
37830      pcache1PinPage(p);
37831      pcache1RemoveFromHash(p);
37832      pcache1FreePage(p);
37833    }
37834    pcache1LeaveMutex(&pcache1.grp);
37835  }
37836  return nFree;
37837}
37838#endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
37839
37840#ifdef SQLITE_TEST
37841/*
37842** This function is used by test procedures to inspect the internal state
37843** of the global cache.
37844*/
37845SQLITE_PRIVATE void sqlite3PcacheStats(
37846  int *pnCurrent,      /* OUT: Total number of pages cached */
37847  int *pnMax,          /* OUT: Global maximum cache size */
37848  int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
37849  int *pnRecyclable    /* OUT: Total number of pages available for recycling */
37850){
37851  PgHdr1 *p;
37852  int nRecyclable = 0;
37853  for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
37854    nRecyclable++;
37855  }
37856  *pnCurrent = pcache1.grp.nCurrentPage;
37857  *pnMax = (int)pcache1.grp.nMaxPage;
37858  *pnMin = (int)pcache1.grp.nMinPage;
37859  *pnRecyclable = nRecyclable;
37860}
37861#endif
37862
37863/************** End of pcache1.c *********************************************/
37864/************** Begin file rowset.c ******************************************/
37865/*
37866** 2008 December 3
37867**
37868** The author disclaims copyright to this source code.  In place of
37869** a legal notice, here is a blessing:
37870**
37871**    May you do good and not evil.
37872**    May you find forgiveness for yourself and forgive others.
37873**    May you share freely, never taking more than you give.
37874**
37875*************************************************************************
37876**
37877** This module implements an object we call a "RowSet".
37878**
37879** The RowSet object is a collection of rowids.  Rowids
37880** are inserted into the RowSet in an arbitrary order.  Inserts
37881** can be intermixed with tests to see if a given rowid has been
37882** previously inserted into the RowSet.
37883**
37884** After all inserts are finished, it is possible to extract the
37885** elements of the RowSet in sorted order.  Once this extraction
37886** process has started, no new elements may be inserted.
37887**
37888** Hence, the primitive operations for a RowSet are:
37889**
37890**    CREATE
37891**    INSERT
37892**    TEST
37893**    SMALLEST
37894**    DESTROY
37895**
37896** The CREATE and DESTROY primitives are the constructor and destructor,
37897** obviously.  The INSERT primitive adds a new element to the RowSet.
37898** TEST checks to see if an element is already in the RowSet.  SMALLEST
37899** extracts the least value from the RowSet.
37900**
37901** The INSERT primitive might allocate additional memory.  Memory is
37902** allocated in chunks so most INSERTs do no allocation.  There is an
37903** upper bound on the size of allocated memory.  No memory is freed
37904** until DESTROY.
37905**
37906** The TEST primitive includes a "batch" number.  The TEST primitive
37907** will only see elements that were inserted before the last change
37908** in the batch number.  In other words, if an INSERT occurs between
37909** two TESTs where the TESTs have the same batch nubmer, then the
37910** value added by the INSERT will not be visible to the second TEST.
37911** The initial batch number is zero, so if the very first TEST contains
37912** a non-zero batch number, it will see all prior INSERTs.
37913**
37914** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
37915** that is attempted.
37916**
37917** The cost of an INSERT is roughly constant.  (Sometime new memory
37918** has to be allocated on an INSERT.)  The cost of a TEST with a new
37919** batch number is O(NlogN) where N is the number of elements in the RowSet.
37920** The cost of a TEST using the same batch number is O(logN).  The cost
37921** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
37922** primitives are constant time.  The cost of DESTROY is O(N).
37923**
37924** There is an added cost of O(N) when switching between TEST and
37925** SMALLEST primitives.
37926*/
37927
37928
37929/*
37930** Target size for allocation chunks.
37931*/
37932#define ROWSET_ALLOCATION_SIZE 1024
37933
37934/*
37935** The number of rowset entries per allocation chunk.
37936*/
37937#define ROWSET_ENTRY_PER_CHUNK  \
37938                       ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
37939
37940/*
37941** Each entry in a RowSet is an instance of the following object.
37942*/
37943struct RowSetEntry {
37944  i64 v;                        /* ROWID value for this entry */
37945  struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
37946  struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
37947};
37948
37949/*
37950** RowSetEntry objects are allocated in large chunks (instances of the
37951** following structure) to reduce memory allocation overhead.  The
37952** chunks are kept on a linked list so that they can be deallocated
37953** when the RowSet is destroyed.
37954*/
37955struct RowSetChunk {
37956  struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
37957  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
37958};
37959
37960/*
37961** A RowSet in an instance of the following structure.
37962**
37963** A typedef of this structure if found in sqliteInt.h.
37964*/
37965struct RowSet {
37966  struct RowSetChunk *pChunk;    /* List of all chunk allocations */
37967  sqlite3 *db;                   /* The database connection */
37968  struct RowSetEntry *pEntry;    /* List of entries using pRight */
37969  struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
37970  struct RowSetEntry *pFresh;    /* Source of new entry objects */
37971  struct RowSetEntry *pTree;     /* Binary tree of entries */
37972  u16 nFresh;                    /* Number of objects on pFresh */
37973  u8 isSorted;                   /* True if pEntry is sorted */
37974  u8 iBatch;                     /* Current insert batch */
37975};
37976
37977/*
37978** Turn bulk memory into a RowSet object.  N bytes of memory
37979** are available at pSpace.  The db pointer is used as a memory context
37980** for any subsequent allocations that need to occur.
37981** Return a pointer to the new RowSet object.
37982**
37983** It must be the case that N is sufficient to make a Rowset.  If not
37984** an assertion fault occurs.
37985**
37986** If N is larger than the minimum, use the surplus as an initial
37987** allocation of entries available to be filled.
37988*/
37989SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
37990  RowSet *p;
37991  assert( N >= ROUND8(sizeof(*p)) );
37992  p = pSpace;
37993  p->pChunk = 0;
37994  p->db = db;
37995  p->pEntry = 0;
37996  p->pLast = 0;
37997  p->pTree = 0;
37998  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
37999  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
38000  p->isSorted = 1;
38001  p->iBatch = 0;
38002  return p;
38003}
38004
38005/*
38006** Deallocate all chunks from a RowSet.  This frees all memory that
38007** the RowSet has allocated over its lifetime.  This routine is
38008** the destructor for the RowSet.
38009*/
38010SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
38011  struct RowSetChunk *pChunk, *pNextChunk;
38012  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
38013    pNextChunk = pChunk->pNextChunk;
38014    sqlite3DbFree(p->db, pChunk);
38015  }
38016  p->pChunk = 0;
38017  p->nFresh = 0;
38018  p->pEntry = 0;
38019  p->pLast = 0;
38020  p->pTree = 0;
38021  p->isSorted = 1;
38022}
38023
38024/*
38025** Insert a new value into a RowSet.
38026**
38027** The mallocFailed flag of the database connection is set if a
38028** memory allocation fails.
38029*/
38030SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
38031  struct RowSetEntry *pEntry;  /* The new entry */
38032  struct RowSetEntry *pLast;   /* The last prior entry */
38033  assert( p!=0 );
38034  if( p->nFresh==0 ){
38035    struct RowSetChunk *pNew;
38036    pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
38037    if( pNew==0 ){
38038      return;
38039    }
38040    pNew->pNextChunk = p->pChunk;
38041    p->pChunk = pNew;
38042    p->pFresh = pNew->aEntry;
38043    p->nFresh = ROWSET_ENTRY_PER_CHUNK;
38044  }
38045  pEntry = p->pFresh++;
38046  p->nFresh--;
38047  pEntry->v = rowid;
38048  pEntry->pRight = 0;
38049  pLast = p->pLast;
38050  if( pLast ){
38051    if( p->isSorted && rowid<=pLast->v ){
38052      p->isSorted = 0;
38053    }
38054    pLast->pRight = pEntry;
38055  }else{
38056    assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
38057    p->pEntry = pEntry;
38058  }
38059  p->pLast = pEntry;
38060}
38061
38062/*
38063** Merge two lists of RowSetEntry objects.  Remove duplicates.
38064**
38065** The input lists are connected via pRight pointers and are
38066** assumed to each already be in sorted order.
38067*/
38068static struct RowSetEntry *rowSetMerge(
38069  struct RowSetEntry *pA,    /* First sorted list to be merged */
38070  struct RowSetEntry *pB     /* Second sorted list to be merged */
38071){
38072  struct RowSetEntry head;
38073  struct RowSetEntry *pTail;
38074
38075  pTail = &head;
38076  while( pA && pB ){
38077    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
38078    assert( pB->pRight==0 || pB->v<=pB->pRight->v );
38079    if( pA->v<pB->v ){
38080      pTail->pRight = pA;
38081      pA = pA->pRight;
38082      pTail = pTail->pRight;
38083    }else if( pB->v<pA->v ){
38084      pTail->pRight = pB;
38085      pB = pB->pRight;
38086      pTail = pTail->pRight;
38087    }else{
38088      pA = pA->pRight;
38089    }
38090  }
38091  if( pA ){
38092    assert( pA->pRight==0 || pA->v<=pA->pRight->v );
38093    pTail->pRight = pA;
38094  }else{
38095    assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
38096    pTail->pRight = pB;
38097  }
38098  return head.pRight;
38099}
38100
38101/*
38102** Sort all elements on the pEntry list of the RowSet into ascending order.
38103*/
38104static void rowSetSort(RowSet *p){
38105  unsigned int i;
38106  struct RowSetEntry *pEntry;
38107  struct RowSetEntry *aBucket[40];
38108
38109  assert( p->isSorted==0 );
38110  memset(aBucket, 0, sizeof(aBucket));
38111  while( p->pEntry ){
38112    pEntry = p->pEntry;
38113    p->pEntry = pEntry->pRight;
38114    pEntry->pRight = 0;
38115    for(i=0; aBucket[i]; i++){
38116      pEntry = rowSetMerge(aBucket[i], pEntry);
38117      aBucket[i] = 0;
38118    }
38119    aBucket[i] = pEntry;
38120  }
38121  pEntry = 0;
38122  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
38123    pEntry = rowSetMerge(pEntry, aBucket[i]);
38124  }
38125  p->pEntry = pEntry;
38126  p->pLast = 0;
38127  p->isSorted = 1;
38128}
38129
38130
38131/*
38132** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
38133** Convert this tree into a linked list connected by the pRight pointers
38134** and return pointers to the first and last elements of the new list.
38135*/
38136static void rowSetTreeToList(
38137  struct RowSetEntry *pIn,         /* Root of the input tree */
38138  struct RowSetEntry **ppFirst,    /* Write head of the output list here */
38139  struct RowSetEntry **ppLast      /* Write tail of the output list here */
38140){
38141  assert( pIn!=0 );
38142  if( pIn->pLeft ){
38143    struct RowSetEntry *p;
38144    rowSetTreeToList(pIn->pLeft, ppFirst, &p);
38145    p->pRight = pIn;
38146  }else{
38147    *ppFirst = pIn;
38148  }
38149  if( pIn->pRight ){
38150    rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
38151  }else{
38152    *ppLast = pIn;
38153  }
38154  assert( (*ppLast)->pRight==0 );
38155}
38156
38157
38158/*
38159** Convert a sorted list of elements (connected by pRight) into a binary
38160** tree with depth of iDepth.  A depth of 1 means the tree contains a single
38161** node taken from the head of *ppList.  A depth of 2 means a tree with
38162** three nodes.  And so forth.
38163**
38164** Use as many entries from the input list as required and update the
38165** *ppList to point to the unused elements of the list.  If the input
38166** list contains too few elements, then construct an incomplete tree
38167** and leave *ppList set to NULL.
38168**
38169** Return a pointer to the root of the constructed binary tree.
38170*/
38171static struct RowSetEntry *rowSetNDeepTree(
38172  struct RowSetEntry **ppList,
38173  int iDepth
38174){
38175  struct RowSetEntry *p;         /* Root of the new tree */
38176  struct RowSetEntry *pLeft;     /* Left subtree */
38177  if( *ppList==0 ){
38178    return 0;
38179  }
38180  if( iDepth==1 ){
38181    p = *ppList;
38182    *ppList = p->pRight;
38183    p->pLeft = p->pRight = 0;
38184    return p;
38185  }
38186  pLeft = rowSetNDeepTree(ppList, iDepth-1);
38187  p = *ppList;
38188  if( p==0 ){
38189    return pLeft;
38190  }
38191  p->pLeft = pLeft;
38192  *ppList = p->pRight;
38193  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
38194  return p;
38195}
38196
38197/*
38198** Convert a sorted list of elements into a binary tree. Make the tree
38199** as deep as it needs to be in order to contain the entire list.
38200*/
38201static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
38202  int iDepth;           /* Depth of the tree so far */
38203  struct RowSetEntry *p;       /* Current tree root */
38204  struct RowSetEntry *pLeft;   /* Left subtree */
38205
38206  assert( pList!=0 );
38207  p = pList;
38208  pList = p->pRight;
38209  p->pLeft = p->pRight = 0;
38210  for(iDepth=1; pList; iDepth++){
38211    pLeft = p;
38212    p = pList;
38213    pList = p->pRight;
38214    p->pLeft = pLeft;
38215    p->pRight = rowSetNDeepTree(&pList, iDepth);
38216  }
38217  return p;
38218}
38219
38220/*
38221** Convert the list in p->pEntry into a sorted list if it is not
38222** sorted already.  If there is a binary tree on p->pTree, then
38223** convert it into a list too and merge it into the p->pEntry list.
38224*/
38225static void rowSetToList(RowSet *p){
38226  if( !p->isSorted ){
38227    rowSetSort(p);
38228  }
38229  if( p->pTree ){
38230    struct RowSetEntry *pHead, *pTail;
38231    rowSetTreeToList(p->pTree, &pHead, &pTail);
38232    p->pTree = 0;
38233    p->pEntry = rowSetMerge(p->pEntry, pHead);
38234  }
38235}
38236
38237/*
38238** Extract the smallest element from the RowSet.
38239** Write the element into *pRowid.  Return 1 on success.  Return
38240** 0 if the RowSet is already empty.
38241**
38242** After this routine has been called, the sqlite3RowSetInsert()
38243** routine may not be called again.
38244*/
38245SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
38246  rowSetToList(p);
38247  if( p->pEntry ){
38248    *pRowid = p->pEntry->v;
38249    p->pEntry = p->pEntry->pRight;
38250    if( p->pEntry==0 ){
38251      sqlite3RowSetClear(p);
38252    }
38253    return 1;
38254  }else{
38255    return 0;
38256  }
38257}
38258
38259/*
38260** Check to see if element iRowid was inserted into the the rowset as
38261** part of any insert batch prior to iBatch.  Return 1 or 0.
38262*/
38263SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
38264  struct RowSetEntry *p;
38265  if( iBatch!=pRowSet->iBatch ){
38266    if( pRowSet->pEntry ){
38267      rowSetToList(pRowSet);
38268      pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
38269      pRowSet->pEntry = 0;
38270      pRowSet->pLast = 0;
38271    }
38272    pRowSet->iBatch = iBatch;
38273  }
38274  p = pRowSet->pTree;
38275  while( p ){
38276    if( p->v<iRowid ){
38277      p = p->pRight;
38278    }else if( p->v>iRowid ){
38279      p = p->pLeft;
38280    }else{
38281      return 1;
38282    }
38283  }
38284  return 0;
38285}
38286
38287/************** End of rowset.c **********************************************/
38288/************** Begin file pager.c *******************************************/
38289/*
38290** 2001 September 15
38291**
38292** The author disclaims copyright to this source code.  In place of
38293** a legal notice, here is a blessing:
38294**
38295**    May you do good and not evil.
38296**    May you find forgiveness for yourself and forgive others.
38297**    May you share freely, never taking more than you give.
38298**
38299*************************************************************************
38300** This is the implementation of the page cache subsystem or "pager".
38301**
38302** The pager is used to access a database disk file.  It implements
38303** atomic commit and rollback through the use of a journal file that
38304** is separate from the database file.  The pager also implements file
38305** locking to prevent two processes from writing the same database
38306** file simultaneously, or one process from reading the database while
38307** another is writing.
38308*/
38309#ifndef SQLITE_OMIT_DISKIO
38310/************** Include wal.h in the middle of pager.c ***********************/
38311/************** Begin file wal.h *********************************************/
38312/*
38313** 2010 February 1
38314**
38315** The author disclaims copyright to this source code.  In place of
38316** a legal notice, here is a blessing:
38317**
38318**    May you do good and not evil.
38319**    May you find forgiveness for yourself and forgive others.
38320**    May you share freely, never taking more than you give.
38321**
38322*************************************************************************
38323** This header file defines the interface to the write-ahead logging
38324** system. Refer to the comments below and the header comment attached to
38325** the implementation of each function in log.c for further details.
38326*/
38327
38328#ifndef _WAL_H_
38329#define _WAL_H_
38330
38331
38332/* Additional values that can be added to the sync_flags argument of
38333** sqlite3WalFrames():
38334*/
38335#define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
38336#define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
38337
38338#ifdef SQLITE_OMIT_WAL
38339# define sqlite3WalOpen(x,y,z)                   0
38340# define sqlite3WalLimit(x,y)
38341# define sqlite3WalClose(w,x,y,z)                0
38342# define sqlite3WalBeginReadTransaction(y,z)     0
38343# define sqlite3WalEndReadTransaction(z)
38344# define sqlite3WalRead(v,w,x,y,z)               0
38345# define sqlite3WalDbsize(y)                     0
38346# define sqlite3WalBeginWriteTransaction(y)      0
38347# define sqlite3WalEndWriteTransaction(x)        0
38348# define sqlite3WalUndo(x,y,z)                   0
38349# define sqlite3WalSavepoint(y,z)
38350# define sqlite3WalSavepointUndo(y,z)            0
38351# define sqlite3WalFrames(u,v,w,x,y,z)           0
38352# define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
38353# define sqlite3WalCallback(z)                   0
38354# define sqlite3WalExclusiveMode(y,z)            0
38355# define sqlite3WalHeapMemory(z)                 0
38356# define sqlite3WalFramesize(z)                  0
38357#else
38358
38359#define WAL_SAVEPOINT_NDATA 4
38360
38361/* Connection to a write-ahead log (WAL) file.
38362** There is one object of this type for each pager.
38363*/
38364typedef struct Wal Wal;
38365
38366/* Open and close a connection to a write-ahead log. */
38367SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
38368SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
38369
38370/* Set the limiting size of a WAL file. */
38371SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
38372
38373/* Used by readers to open (lock) and close (unlock) a snapshot.  A
38374** snapshot is like a read-transaction.  It is the state of the database
38375** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
38376** preserves the current state even if the other threads or processes
38377** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
38378** transaction and releases the lock.
38379*/
38380SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
38381SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
38382
38383/* Read a page from the write-ahead log, if it is present. */
38384SQLITE_PRIVATE int sqlite3WalRead(Wal *pWal, Pgno pgno, int *pInWal, int nOut, u8 *pOut);
38385
38386/* If the WAL is not empty, return the size of the database. */
38387SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
38388
38389/* Obtain or release the WRITER lock. */
38390SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
38391SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
38392
38393/* Undo any frames written (but not committed) to the log */
38394SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
38395
38396/* Return an integer that records the current (uncommitted) write
38397** position in the WAL */
38398SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
38399
38400/* Move the write position of the WAL back to iFrame.  Called in
38401** response to a ROLLBACK TO command. */
38402SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
38403
38404/* Write a frame or frames to the log. */
38405SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
38406
38407/* Copy pages from the log to the database file */
38408SQLITE_PRIVATE int sqlite3WalCheckpoint(
38409  Wal *pWal,                      /* Write-ahead log connection */
38410  int eMode,                      /* One of PASSIVE, FULL and RESTART */
38411  int (*xBusy)(void*),            /* Function to call when busy */
38412  void *pBusyArg,                 /* Context argument for xBusyHandler */
38413  int sync_flags,                 /* Flags to sync db file with (or 0) */
38414  int nBuf,                       /* Size of buffer nBuf */
38415  u8 *zBuf,                       /* Temporary buffer to use */
38416  int *pnLog,                     /* OUT: Number of frames in WAL */
38417  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
38418);
38419
38420/* Return the value to pass to a sqlite3_wal_hook callback, the
38421** number of frames in the WAL at the point of the last commit since
38422** sqlite3WalCallback() was called.  If no commits have occurred since
38423** the last call, then return 0.
38424*/
38425SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
38426
38427/* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
38428** by the pager layer on the database file.
38429*/
38430SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
38431
38432/* Return true if the argument is non-NULL and the WAL module is using
38433** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
38434** WAL module is using shared-memory, return false.
38435*/
38436SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
38437
38438#ifdef SQLITE_ENABLE_ZIPVFS
38439/* If the WAL file is not empty, return the number of bytes of content
38440** stored in each frame (i.e. the db page-size when the WAL was created).
38441*/
38442SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
38443#endif
38444
38445#endif /* ifndef SQLITE_OMIT_WAL */
38446#endif /* _WAL_H_ */
38447
38448/************** End of wal.h *************************************************/
38449/************** Continuing where we left off in pager.c **********************/
38450
38451
38452/******************* NOTES ON THE DESIGN OF THE PAGER ************************
38453**
38454** This comment block describes invariants that hold when using a rollback
38455** journal.  These invariants do not apply for journal_mode=WAL,
38456** journal_mode=MEMORY, or journal_mode=OFF.
38457**
38458** Within this comment block, a page is deemed to have been synced
38459** automatically as soon as it is written when PRAGMA synchronous=OFF.
38460** Otherwise, the page is not synced until the xSync method of the VFS
38461** is called successfully on the file containing the page.
38462**
38463** Definition:  A page of the database file is said to be "overwriteable" if
38464** one or more of the following are true about the page:
38465**
38466**     (a)  The original content of the page as it was at the beginning of
38467**          the transaction has been written into the rollback journal and
38468**          synced.
38469**
38470**     (b)  The page was a freelist leaf page at the start of the transaction.
38471**
38472**     (c)  The page number is greater than the largest page that existed in
38473**          the database file at the start of the transaction.
38474**
38475** (1) A page of the database file is never overwritten unless one of the
38476**     following are true:
38477**
38478**     (a) The page and all other pages on the same sector are overwriteable.
38479**
38480**     (b) The atomic page write optimization is enabled, and the entire
38481**         transaction other than the update of the transaction sequence
38482**         number consists of a single page change.
38483**
38484** (2) The content of a page written into the rollback journal exactly matches
38485**     both the content in the database when the rollback journal was written
38486**     and the content in the database at the beginning of the current
38487**     transaction.
38488**
38489** (3) Writes to the database file are an integer multiple of the page size
38490**     in length and are aligned on a page boundary.
38491**
38492** (4) Reads from the database file are either aligned on a page boundary and
38493**     an integer multiple of the page size in length or are taken from the
38494**     first 100 bytes of the database file.
38495**
38496** (5) All writes to the database file are synced prior to the rollback journal
38497**     being deleted, truncated, or zeroed.
38498**
38499** (6) If a master journal file is used, then all writes to the database file
38500**     are synced prior to the master journal being deleted.
38501**
38502** Definition: Two databases (or the same database at two points it time)
38503** are said to be "logically equivalent" if they give the same answer to
38504** all queries.  Note in particular the the content of freelist leaf
38505** pages can be changed arbitarily without effecting the logical equivalence
38506** of the database.
38507**
38508** (7) At any time, if any subset, including the empty set and the total set,
38509**     of the unsynced changes to a rollback journal are removed and the
38510**     journal is rolled back, the resulting database file will be logical
38511**     equivalent to the database file at the beginning of the transaction.
38512**
38513** (8) When a transaction is rolled back, the xTruncate method of the VFS
38514**     is called to restore the database file to the same size it was at
38515**     the beginning of the transaction.  (In some VFSes, the xTruncate
38516**     method is a no-op, but that does not change the fact the SQLite will
38517**     invoke it.)
38518**
38519** (9) Whenever the database file is modified, at least one bit in the range
38520**     of bytes from 24 through 39 inclusive will be changed prior to releasing
38521**     the EXCLUSIVE lock, thus signaling other connections on the same
38522**     database to flush their caches.
38523**
38524** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
38525**      than one billion transactions.
38526**
38527** (11) A database file is well-formed at the beginning and at the conclusion
38528**      of every transaction.
38529**
38530** (12) An EXCLUSIVE lock is held on the database file when writing to
38531**      the database file.
38532**
38533** (13) A SHARED lock is held on the database file while reading any
38534**      content out of the database file.
38535**
38536******************************************************************************/
38537
38538/*
38539** Macros for troubleshooting.  Normally turned off
38540*/
38541#if 0
38542int sqlite3PagerTrace=1;  /* True to enable tracing */
38543#define sqlite3DebugPrintf printf
38544#define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
38545#else
38546#define PAGERTRACE(X)
38547#endif
38548
38549/*
38550** The following two macros are used within the PAGERTRACE() macros above
38551** to print out file-descriptors.
38552**
38553** PAGERID() takes a pointer to a Pager struct as its argument. The
38554** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
38555** struct as its argument.
38556*/
38557#define PAGERID(p) ((int)(p->fd))
38558#define FILEHANDLEID(fd) ((int)fd)
38559
38560/*
38561** The Pager.eState variable stores the current 'state' of a pager. A
38562** pager may be in any one of the seven states shown in the following
38563** state diagram.
38564**
38565**                            OPEN <------+------+
38566**                              |         |      |
38567**                              V         |      |
38568**               +---------> READER-------+      |
38569**               |              |                |
38570**               |              V                |
38571**               |<-------WRITER_LOCKED------> ERROR
38572**               |              |                ^
38573**               |              V                |
38574**               |<------WRITER_CACHEMOD-------->|
38575**               |              |                |
38576**               |              V                |
38577**               |<-------WRITER_DBMOD---------->|
38578**               |              |                |
38579**               |              V                |
38580**               +<------WRITER_FINISHED-------->+
38581**
38582**
38583** List of state transitions and the C [function] that performs each:
38584**
38585**   OPEN              -> READER              [sqlite3PagerSharedLock]
38586**   READER            -> OPEN                [pager_unlock]
38587**
38588**   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
38589**   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
38590**   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
38591**   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
38592**   WRITER_***        -> READER              [pager_end_transaction]
38593**
38594**   WRITER_***        -> ERROR               [pager_error]
38595**   ERROR             -> OPEN                [pager_unlock]
38596**
38597**
38598**  OPEN:
38599**
38600**    The pager starts up in this state. Nothing is guaranteed in this
38601**    state - the file may or may not be locked and the database size is
38602**    unknown. The database may not be read or written.
38603**
38604**    * No read or write transaction is active.
38605**    * Any lock, or no lock at all, may be held on the database file.
38606**    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
38607**
38608**  READER:
38609**
38610**    In this state all the requirements for reading the database in
38611**    rollback (non-WAL) mode are met. Unless the pager is (or recently
38612**    was) in exclusive-locking mode, a user-level read transaction is
38613**    open. The database size is known in this state.
38614**
38615**    A connection running with locking_mode=normal enters this state when
38616**    it opens a read-transaction on the database and returns to state
38617**    OPEN after the read-transaction is completed. However a connection
38618**    running in locking_mode=exclusive (including temp databases) remains in
38619**    this state even after the read-transaction is closed. The only way
38620**    a locking_mode=exclusive connection can transition from READER to OPEN
38621**    is via the ERROR state (see below).
38622**
38623**    * A read transaction may be active (but a write-transaction cannot).
38624**    * A SHARED or greater lock is held on the database file.
38625**    * The dbSize variable may be trusted (even if a user-level read
38626**      transaction is not active). The dbOrigSize and dbFileSize variables
38627**      may not be trusted at this point.
38628**    * If the database is a WAL database, then the WAL connection is open.
38629**    * Even if a read-transaction is not open, it is guaranteed that
38630**      there is no hot-journal in the file-system.
38631**
38632**  WRITER_LOCKED:
38633**
38634**    The pager moves to this state from READER when a write-transaction
38635**    is first opened on the database. In WRITER_LOCKED state, all locks
38636**    required to start a write-transaction are held, but no actual
38637**    modifications to the cache or database have taken place.
38638**
38639**    In rollback mode, a RESERVED or (if the transaction was opened with
38640**    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
38641**    moving to this state, but the journal file is not written to or opened
38642**    to in this state. If the transaction is committed or rolled back while
38643**    in WRITER_LOCKED state, all that is required is to unlock the database
38644**    file.
38645**
38646**    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
38647**    If the connection is running with locking_mode=exclusive, an attempt
38648**    is made to obtain an EXCLUSIVE lock on the database file.
38649**
38650**    * A write transaction is active.
38651**    * If the connection is open in rollback-mode, a RESERVED or greater
38652**      lock is held on the database file.
38653**    * If the connection is open in WAL-mode, a WAL write transaction
38654**      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
38655**      called).
38656**    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
38657**    * The contents of the pager cache have not been modified.
38658**    * The journal file may or may not be open.
38659**    * Nothing (not even the first header) has been written to the journal.
38660**
38661**  WRITER_CACHEMOD:
38662**
38663**    A pager moves from WRITER_LOCKED state to this state when a page is
38664**    first modified by the upper layer. In rollback mode the journal file
38665**    is opened (if it is not already open) and a header written to the
38666**    start of it. The database file on disk has not been modified.
38667**
38668**    * A write transaction is active.
38669**    * A RESERVED or greater lock is held on the database file.
38670**    * The journal file is open and the first header has been written
38671**      to it, but the header has not been synced to disk.
38672**    * The contents of the page cache have been modified.
38673**
38674**  WRITER_DBMOD:
38675**
38676**    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
38677**    when it modifies the contents of the database file. WAL connections
38678**    never enter this state (since they do not modify the database file,
38679**    just the log file).
38680**
38681**    * A write transaction is active.
38682**    * An EXCLUSIVE or greater lock is held on the database file.
38683**    * The journal file is open and the first header has been written
38684**      and synced to disk.
38685**    * The contents of the page cache have been modified (and possibly
38686**      written to disk).
38687**
38688**  WRITER_FINISHED:
38689**
38690**    It is not possible for a WAL connection to enter this state.
38691**
38692**    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
38693**    state after the entire transaction has been successfully written into the
38694**    database file. In this state the transaction may be committed simply
38695**    by finalizing the journal file. Once in WRITER_FINISHED state, it is
38696**    not possible to modify the database further. At this point, the upper
38697**    layer must either commit or rollback the transaction.
38698**
38699**    * A write transaction is active.
38700**    * An EXCLUSIVE or greater lock is held on the database file.
38701**    * All writing and syncing of journal and database data has finished.
38702**      If no error occured, all that remains is to finalize the journal to
38703**      commit the transaction. If an error did occur, the caller will need
38704**      to rollback the transaction.
38705**
38706**  ERROR:
38707**
38708**    The ERROR state is entered when an IO or disk-full error (including
38709**    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
38710**    difficult to be sure that the in-memory pager state (cache contents,
38711**    db size etc.) are consistent with the contents of the file-system.
38712**
38713**    Temporary pager files may enter the ERROR state, but in-memory pagers
38714**    cannot.
38715**
38716**    For example, if an IO error occurs while performing a rollback,
38717**    the contents of the page-cache may be left in an inconsistent state.
38718**    At this point it would be dangerous to change back to READER state
38719**    (as usually happens after a rollback). Any subsequent readers might
38720**    report database corruption (due to the inconsistent cache), and if
38721**    they upgrade to writers, they may inadvertently corrupt the database
38722**    file. To avoid this hazard, the pager switches into the ERROR state
38723**    instead of READER following such an error.
38724**
38725**    Once it has entered the ERROR state, any attempt to use the pager
38726**    to read or write data returns an error. Eventually, once all
38727**    outstanding transactions have been abandoned, the pager is able to
38728**    transition back to OPEN state, discarding the contents of the
38729**    page-cache and any other in-memory state at the same time. Everything
38730**    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
38731**    when a read-transaction is next opened on the pager (transitioning
38732**    the pager into READER state). At that point the system has recovered
38733**    from the error.
38734**
38735**    Specifically, the pager jumps into the ERROR state if:
38736**
38737**      1. An error occurs while attempting a rollback. This happens in
38738**         function sqlite3PagerRollback().
38739**
38740**      2. An error occurs while attempting to finalize a journal file
38741**         following a commit in function sqlite3PagerCommitPhaseTwo().
38742**
38743**      3. An error occurs while attempting to write to the journal or
38744**         database file in function pagerStress() in order to free up
38745**         memory.
38746**
38747**    In other cases, the error is returned to the b-tree layer. The b-tree
38748**    layer then attempts a rollback operation. If the error condition
38749**    persists, the pager enters the ERROR state via condition (1) above.
38750**
38751**    Condition (3) is necessary because it can be triggered by a read-only
38752**    statement executed within a transaction. In this case, if the error
38753**    code were simply returned to the user, the b-tree layer would not
38754**    automatically attempt a rollback, as it assumes that an error in a
38755**    read-only statement cannot leave the pager in an internally inconsistent
38756**    state.
38757**
38758**    * The Pager.errCode variable is set to something other than SQLITE_OK.
38759**    * There are one or more outstanding references to pages (after the
38760**      last reference is dropped the pager should move back to OPEN state).
38761**    * The pager is not an in-memory pager.
38762**
38763**
38764** Notes:
38765**
38766**   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
38767**     connection is open in WAL mode. A WAL connection is always in one
38768**     of the first four states.
38769**
38770**   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
38771**     state. There are two exceptions: immediately after exclusive-mode has
38772**     been turned on (and before any read or write transactions are
38773**     executed), and when the pager is leaving the "error state".
38774**
38775**   * See also: assert_pager_state().
38776*/
38777#define PAGER_OPEN                  0
38778#define PAGER_READER                1
38779#define PAGER_WRITER_LOCKED         2
38780#define PAGER_WRITER_CACHEMOD       3
38781#define PAGER_WRITER_DBMOD          4
38782#define PAGER_WRITER_FINISHED       5
38783#define PAGER_ERROR                 6
38784
38785/*
38786** The Pager.eLock variable is almost always set to one of the
38787** following locking-states, according to the lock currently held on
38788** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38789** This variable is kept up to date as locks are taken and released by
38790** the pagerLockDb() and pagerUnlockDb() wrappers.
38791**
38792** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
38793** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
38794** the operation was successful. In these circumstances pagerLockDb() and
38795** pagerUnlockDb() take a conservative approach - eLock is always updated
38796** when unlocking the file, and only updated when locking the file if the
38797** VFS call is successful. This way, the Pager.eLock variable may be set
38798** to a less exclusive (lower) value than the lock that is actually held
38799** at the system level, but it is never set to a more exclusive value.
38800**
38801** This is usually safe. If an xUnlock fails or appears to fail, there may
38802** be a few redundant xLock() calls or a lock may be held for longer than
38803** required, but nothing really goes wrong.
38804**
38805** The exception is when the database file is unlocked as the pager moves
38806** from ERROR to OPEN state. At this point there may be a hot-journal file
38807** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
38808** transition, by the same pager or any other). If the call to xUnlock()
38809** fails at this point and the pager is left holding an EXCLUSIVE lock, this
38810** can confuse the call to xCheckReservedLock() call made later as part
38811** of hot-journal detection.
38812**
38813** xCheckReservedLock() is defined as returning true "if there is a RESERVED
38814** lock held by this process or any others". So xCheckReservedLock may
38815** return true because the caller itself is holding an EXCLUSIVE lock (but
38816** doesn't know it because of a previous error in xUnlock). If this happens
38817** a hot-journal may be mistaken for a journal being created by an active
38818** transaction in another process, causing SQLite to read from the database
38819** without rolling it back.
38820**
38821** To work around this, if a call to xUnlock() fails when unlocking the
38822** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
38823** is only changed back to a real locking state after a successful call
38824** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
38825** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
38826** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
38827** lock on the database file before attempting to roll it back. See function
38828** PagerSharedLock() for more detail.
38829**
38830** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
38831** PAGER_OPEN state.
38832*/
38833#define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
38834
38835/*
38836** A macro used for invoking the codec if there is one
38837*/
38838#ifdef SQLITE_HAS_CODEC
38839# define CODEC1(P,D,N,X,E) \
38840    if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
38841# define CODEC2(P,D,N,X,E,O) \
38842    if( P->xCodec==0 ){ O=(char*)D; }else \
38843    if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
38844#else
38845# define CODEC1(P,D,N,X,E)   /* NO-OP */
38846# define CODEC2(P,D,N,X,E,O) O=(char*)D
38847#endif
38848
38849/*
38850** The maximum allowed sector size. 64KiB. If the xSectorsize() method
38851** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
38852** This could conceivably cause corruption following a power failure on
38853** such a system. This is currently an undocumented limit.
38854*/
38855#define MAX_SECTOR_SIZE 0x10000
38856
38857/*
38858** An instance of the following structure is allocated for each active
38859** savepoint and statement transaction in the system. All such structures
38860** are stored in the Pager.aSavepoint[] array, which is allocated and
38861** resized using sqlite3Realloc().
38862**
38863** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
38864** set to 0. If a journal-header is written into the main journal while
38865** the savepoint is active, then iHdrOffset is set to the byte offset
38866** immediately following the last journal record written into the main
38867** journal before the journal-header. This is required during savepoint
38868** rollback (see pagerPlaybackSavepoint()).
38869*/
38870typedef struct PagerSavepoint PagerSavepoint;
38871struct PagerSavepoint {
38872  i64 iOffset;                 /* Starting offset in main journal */
38873  i64 iHdrOffset;              /* See above */
38874  Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
38875  Pgno nOrig;                  /* Original number of pages in file */
38876  Pgno iSubRec;                /* Index of first record in sub-journal */
38877#ifndef SQLITE_OMIT_WAL
38878  u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
38879#endif
38880};
38881
38882/*
38883** A open page cache is an instance of struct Pager. A description of
38884** some of the more important member variables follows:
38885**
38886** eState
38887**
38888**   The current 'state' of the pager object. See the comment and state
38889**   diagram above for a description of the pager state.
38890**
38891** eLock
38892**
38893**   For a real on-disk database, the current lock held on the database file -
38894**   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38895**
38896**   For a temporary or in-memory database (neither of which require any
38897**   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
38898**   databases always have Pager.exclusiveMode==1, this tricks the pager
38899**   logic into thinking that it already has all the locks it will ever
38900**   need (and no reason to release them).
38901**
38902**   In some (obscure) circumstances, this variable may also be set to
38903**   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
38904**   details.
38905**
38906** changeCountDone
38907**
38908**   This boolean variable is used to make sure that the change-counter
38909**   (the 4-byte header field at byte offset 24 of the database file) is
38910**   not updated more often than necessary.
38911**
38912**   It is set to true when the change-counter field is updated, which
38913**   can only happen if an exclusive lock is held on the database file.
38914**   It is cleared (set to false) whenever an exclusive lock is
38915**   relinquished on the database file. Each time a transaction is committed,
38916**   The changeCountDone flag is inspected. If it is true, the work of
38917**   updating the change-counter is omitted for the current transaction.
38918**
38919**   This mechanism means that when running in exclusive mode, a connection
38920**   need only update the change-counter once, for the first transaction
38921**   committed.
38922**
38923** setMaster
38924**
38925**   When PagerCommitPhaseOne() is called to commit a transaction, it may
38926**   (or may not) specify a master-journal name to be written into the
38927**   journal file before it is synced to disk.
38928**
38929**   Whether or not a journal file contains a master-journal pointer affects
38930**   the way in which the journal file is finalized after the transaction is
38931**   committed or rolled back when running in "journal_mode=PERSIST" mode.
38932**   If a journal file does not contain a master-journal pointer, it is
38933**   finalized by overwriting the first journal header with zeroes. If
38934**   it does contain a master-journal pointer the journal file is finalized
38935**   by truncating it to zero bytes, just as if the connection were
38936**   running in "journal_mode=truncate" mode.
38937**
38938**   Journal files that contain master journal pointers cannot be finalized
38939**   simply by overwriting the first journal-header with zeroes, as the
38940**   master journal pointer could interfere with hot-journal rollback of any
38941**   subsequently interrupted transaction that reuses the journal file.
38942**
38943**   The flag is cleared as soon as the journal file is finalized (either
38944**   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
38945**   journal file from being successfully finalized, the setMaster flag
38946**   is cleared anyway (and the pager will move to ERROR state).
38947**
38948** doNotSpill, doNotSyncSpill
38949**
38950**   These two boolean variables control the behaviour of cache-spills
38951**   (calls made by the pcache module to the pagerStress() routine to
38952**   write cached data to the file-system in order to free up memory).
38953**
38954**   When doNotSpill is non-zero, writing to the database from pagerStress()
38955**   is disabled altogether. This is done in a very obscure case that
38956**   comes up during savepoint rollback that requires the pcache module
38957**   to allocate a new page to prevent the journal file from being written
38958**   while it is being traversed by code in pager_playback().
38959**
38960**   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
38961**   is permitted, but syncing the journal file is not. This flag is set
38962**   by sqlite3PagerWrite() when the file-system sector-size is larger than
38963**   the database page-size in order to prevent a journal sync from happening
38964**   in between the journalling of two pages on the same sector.
38965**
38966** subjInMemory
38967**
38968**   This is a boolean variable. If true, then any required sub-journal
38969**   is opened as an in-memory journal file. If false, then in-memory
38970**   sub-journals are only used for in-memory pager files.
38971**
38972**   This variable is updated by the upper layer each time a new
38973**   write-transaction is opened.
38974**
38975** dbSize, dbOrigSize, dbFileSize
38976**
38977**   Variable dbSize is set to the number of pages in the database file.
38978**   It is valid in PAGER_READER and higher states (all states except for
38979**   OPEN and ERROR).
38980**
38981**   dbSize is set based on the size of the database file, which may be
38982**   larger than the size of the database (the value stored at offset
38983**   28 of the database header by the btree). If the size of the file
38984**   is not an integer multiple of the page-size, the value stored in
38985**   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
38986**   Except, any file that is greater than 0 bytes in size is considered
38987**   to have at least one page. (i.e. a 1KB file with 2K page-size leads
38988**   to dbSize==1).
38989**
38990**   During a write-transaction, if pages with page-numbers greater than
38991**   dbSize are modified in the cache, dbSize is updated accordingly.
38992**   Similarly, if the database is truncated using PagerTruncateImage(),
38993**   dbSize is updated.
38994**
38995**   Variables dbOrigSize and dbFileSize are valid in states
38996**   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
38997**   variable at the start of the transaction. It is used during rollback,
38998**   and to determine whether or not pages need to be journalled before
38999**   being modified.
39000**
39001**   Throughout a write-transaction, dbFileSize contains the size of
39002**   the file on disk in pages. It is set to a copy of dbSize when the
39003**   write-transaction is first opened, and updated when VFS calls are made
39004**   to write or truncate the database file on disk.
39005**
39006**   The only reason the dbFileSize variable is required is to suppress
39007**   unnecessary calls to xTruncate() after committing a transaction. If,
39008**   when a transaction is committed, the dbFileSize variable indicates
39009**   that the database file is larger than the database image (Pager.dbSize),
39010**   pager_truncate() is called. The pager_truncate() call uses xFilesize()
39011**   to measure the database file on disk, and then truncates it if required.
39012**   dbFileSize is not used when rolling back a transaction. In this case
39013**   pager_truncate() is called unconditionally (which means there may be
39014**   a call to xFilesize() that is not strictly required). In either case,
39015**   pager_truncate() may cause the file to become smaller or larger.
39016**
39017** dbHintSize
39018**
39019**   The dbHintSize variable is used to limit the number of calls made to
39020**   the VFS xFileControl(FCNTL_SIZE_HINT) method.
39021**
39022**   dbHintSize is set to a copy of the dbSize variable when a
39023**   write-transaction is opened (at the same time as dbFileSize and
39024**   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
39025**   dbHintSize is increased to the number of pages that correspond to the
39026**   size-hint passed to the method call. See pager_write_pagelist() for
39027**   details.
39028**
39029** errCode
39030**
39031**   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
39032**   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
39033**   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
39034**   sub-codes.
39035*/
39036struct Pager {
39037  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
39038  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
39039  u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
39040  u8 useJournal;              /* Use a rollback journal on this file */
39041  u8 noSync;                  /* Do not sync the journal if true */
39042  u8 fullSync;                /* Do extra syncs of the journal for robustness */
39043  u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
39044  u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
39045  u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
39046  u8 tempFile;                /* zFilename is a temporary file */
39047  u8 readOnly;                /* True for a read-only database */
39048  u8 memDb;                   /* True to inhibit all file I/O */
39049
39050  /**************************************************************************
39051  ** The following block contains those class members that change during
39052  ** routine opertion.  Class members not in this block are either fixed
39053  ** when the pager is first created or else only change when there is a
39054  ** significant mode change (such as changing the page_size, locking_mode,
39055  ** or the journal_mode).  From another view, these class members describe
39056  ** the "state" of the pager, while other class members describe the
39057  ** "configuration" of the pager.
39058  */
39059  u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
39060  u8 eLock;                   /* Current lock held on database file */
39061  u8 changeCountDone;         /* Set after incrementing the change-counter */
39062  u8 setMaster;               /* True if a m-j name has been written to jrnl */
39063  u8 doNotSpill;              /* Do not spill the cache when non-zero */
39064  u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
39065  u8 subjInMemory;            /* True to use in-memory sub-journals */
39066  Pgno dbSize;                /* Number of pages in the database */
39067  Pgno dbOrigSize;            /* dbSize before the current transaction */
39068  Pgno dbFileSize;            /* Number of pages in the database file */
39069  Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
39070  int errCode;                /* One of several kinds of errors */
39071  int nRec;                   /* Pages journalled since last j-header written */
39072  u32 cksumInit;              /* Quasi-random value added to every checksum */
39073  u32 nSubRec;                /* Number of records written to sub-journal */
39074  Bitvec *pInJournal;         /* One bit for each page in the database file */
39075  sqlite3_file *fd;           /* File descriptor for database */
39076  sqlite3_file *jfd;          /* File descriptor for main journal */
39077  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
39078  i64 journalOff;             /* Current write offset in the journal file */
39079  i64 journalHdr;             /* Byte offset to previous journal header */
39080  sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
39081  PagerSavepoint *aSavepoint; /* Array of active savepoints */
39082  int nSavepoint;             /* Number of elements in aSavepoint[] */
39083  char dbFileVers[16];        /* Changes whenever database file changes */
39084  /*
39085  ** End of the routinely-changing class members
39086  ***************************************************************************/
39087
39088  u16 nExtra;                 /* Add this many bytes to each in-memory page */
39089  i16 nReserve;               /* Number of unused bytes at end of each page */
39090  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
39091  u32 sectorSize;             /* Assumed sector size during rollback */
39092  int pageSize;               /* Number of bytes in a page */
39093  Pgno mxPgno;                /* Maximum allowed size of the database */
39094  i64 journalSizeLimit;       /* Size limit for persistent journal files */
39095  char *zFilename;            /* Name of the database file */
39096  char *zJournal;             /* Name of the journal file */
39097  int (*xBusyHandler)(void*); /* Function to call when busy */
39098  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
39099  int nHit, nMiss;            /* Total cache hits and misses */
39100#ifdef SQLITE_TEST
39101  int nRead, nWrite;          /* Database pages read/written */
39102#endif
39103  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
39104#ifdef SQLITE_HAS_CODEC
39105  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
39106  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
39107  void (*xCodecFree)(void*);             /* Destructor for the codec */
39108  void *pCodec;               /* First argument to xCodec... methods */
39109#endif
39110  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
39111  PCache *pPCache;            /* Pointer to page cache object */
39112#ifndef SQLITE_OMIT_WAL
39113  Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
39114  char *zWal;                 /* File name for write-ahead log */
39115#endif
39116};
39117
39118/*
39119** The following global variables hold counters used for
39120** testing purposes only.  These variables do not exist in
39121** a non-testing build.  These variables are not thread-safe.
39122*/
39123#ifdef SQLITE_TEST
39124SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
39125SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
39126SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
39127# define PAGER_INCR(v)  v++
39128#else
39129# define PAGER_INCR(v)
39130#endif
39131
39132
39133
39134/*
39135** Journal files begin with the following magic string.  The data
39136** was obtained from /dev/random.  It is used only as a sanity check.
39137**
39138** Since version 2.8.0, the journal format contains additional sanity
39139** checking information.  If the power fails while the journal is being
39140** written, semi-random garbage data might appear in the journal
39141** file after power is restored.  If an attempt is then made
39142** to roll the journal back, the database could be corrupted.  The additional
39143** sanity checking data is an attempt to discover the garbage in the
39144** journal and ignore it.
39145**
39146** The sanity checking information for the new journal format consists
39147** of a 32-bit checksum on each page of data.  The checksum covers both
39148** the page number and the pPager->pageSize bytes of data for the page.
39149** This cksum is initialized to a 32-bit random value that appears in the
39150** journal file right after the header.  The random initializer is important,
39151** because garbage data that appears at the end of a journal is likely
39152** data that was once in other files that have now been deleted.  If the
39153** garbage data came from an obsolete journal file, the checksums might
39154** be correct.  But by initializing the checksum to random value which
39155** is different for every journal, we minimize that risk.
39156*/
39157static const unsigned char aJournalMagic[] = {
39158  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
39159};
39160
39161/*
39162** The size of the of each page record in the journal is given by
39163** the following macro.
39164*/
39165#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
39166
39167/*
39168** The journal header size for this pager. This is usually the same
39169** size as a single disk sector. See also setSectorSize().
39170*/
39171#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
39172
39173/*
39174** The macro MEMDB is true if we are dealing with an in-memory database.
39175** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
39176** the value of MEMDB will be a constant and the compiler will optimize
39177** out code that would never execute.
39178*/
39179#ifdef SQLITE_OMIT_MEMORYDB
39180# define MEMDB 0
39181#else
39182# define MEMDB pPager->memDb
39183#endif
39184
39185/*
39186** The maximum legal page number is (2^31 - 1).
39187*/
39188#define PAGER_MAX_PGNO 2147483647
39189
39190/*
39191** The argument to this macro is a file descriptor (type sqlite3_file*).
39192** Return 0 if it is not open, or non-zero (but not 1) if it is.
39193**
39194** This is so that expressions can be written as:
39195**
39196**   if( isOpen(pPager->jfd) ){ ...
39197**
39198** instead of
39199**
39200**   if( pPager->jfd->pMethods ){ ...
39201*/
39202#define isOpen(pFd) ((pFd)->pMethods)
39203
39204/*
39205** Return true if this pager uses a write-ahead log instead of the usual
39206** rollback journal. Otherwise false.
39207*/
39208#ifndef SQLITE_OMIT_WAL
39209static int pagerUseWal(Pager *pPager){
39210  return (pPager->pWal!=0);
39211}
39212#else
39213# define pagerUseWal(x) 0
39214# define pagerRollbackWal(x) 0
39215# define pagerWalFrames(v,w,x,y) 0
39216# define pagerOpenWalIfPresent(z) SQLITE_OK
39217# define pagerBeginReadTransaction(z) SQLITE_OK
39218#endif
39219
39220#ifndef NDEBUG
39221/*
39222** Usage:
39223**
39224**   assert( assert_pager_state(pPager) );
39225**
39226** This function runs many asserts to try to find inconsistencies in
39227** the internal state of the Pager object.
39228*/
39229static int assert_pager_state(Pager *p){
39230  Pager *pPager = p;
39231
39232  /* State must be valid. */
39233  assert( p->eState==PAGER_OPEN
39234       || p->eState==PAGER_READER
39235       || p->eState==PAGER_WRITER_LOCKED
39236       || p->eState==PAGER_WRITER_CACHEMOD
39237       || p->eState==PAGER_WRITER_DBMOD
39238       || p->eState==PAGER_WRITER_FINISHED
39239       || p->eState==PAGER_ERROR
39240  );
39241
39242  /* Regardless of the current state, a temp-file connection always behaves
39243  ** as if it has an exclusive lock on the database file. It never updates
39244  ** the change-counter field, so the changeCountDone flag is always set.
39245  */
39246  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
39247  assert( p->tempFile==0 || pPager->changeCountDone );
39248
39249  /* If the useJournal flag is clear, the journal-mode must be "OFF".
39250  ** And if the journal-mode is "OFF", the journal file must not be open.
39251  */
39252  assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
39253  assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
39254
39255  /* Check that MEMDB implies noSync. And an in-memory journal. Since
39256  ** this means an in-memory pager performs no IO at all, it cannot encounter
39257  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
39258  ** a journal file. (although the in-memory journal implementation may
39259  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
39260  ** is therefore not possible for an in-memory pager to enter the ERROR
39261  ** state.
39262  */
39263  if( MEMDB ){
39264    assert( p->noSync );
39265    assert( p->journalMode==PAGER_JOURNALMODE_OFF
39266         || p->journalMode==PAGER_JOURNALMODE_MEMORY
39267    );
39268    assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
39269    assert( pagerUseWal(p)==0 );
39270  }
39271
39272  /* If changeCountDone is set, a RESERVED lock or greater must be held
39273  ** on the file.
39274  */
39275  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
39276  assert( p->eLock!=PENDING_LOCK );
39277
39278  switch( p->eState ){
39279    case PAGER_OPEN:
39280      assert( !MEMDB );
39281      assert( pPager->errCode==SQLITE_OK );
39282      assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
39283      break;
39284
39285    case PAGER_READER:
39286      assert( pPager->errCode==SQLITE_OK );
39287      assert( p->eLock!=UNKNOWN_LOCK );
39288      assert( p->eLock>=SHARED_LOCK );
39289      break;
39290
39291    case PAGER_WRITER_LOCKED:
39292      assert( p->eLock!=UNKNOWN_LOCK );
39293      assert( pPager->errCode==SQLITE_OK );
39294      if( !pagerUseWal(pPager) ){
39295        assert( p->eLock>=RESERVED_LOCK );
39296      }
39297      assert( pPager->dbSize==pPager->dbOrigSize );
39298      assert( pPager->dbOrigSize==pPager->dbFileSize );
39299      assert( pPager->dbOrigSize==pPager->dbHintSize );
39300      assert( pPager->setMaster==0 );
39301      break;
39302
39303    case PAGER_WRITER_CACHEMOD:
39304      assert( p->eLock!=UNKNOWN_LOCK );
39305      assert( pPager->errCode==SQLITE_OK );
39306      if( !pagerUseWal(pPager) ){
39307        /* It is possible that if journal_mode=wal here that neither the
39308        ** journal file nor the WAL file are open. This happens during
39309        ** a rollback transaction that switches from journal_mode=off
39310        ** to journal_mode=wal.
39311        */
39312        assert( p->eLock>=RESERVED_LOCK );
39313        assert( isOpen(p->jfd)
39314             || p->journalMode==PAGER_JOURNALMODE_OFF
39315             || p->journalMode==PAGER_JOURNALMODE_WAL
39316        );
39317      }
39318      assert( pPager->dbOrigSize==pPager->dbFileSize );
39319      assert( pPager->dbOrigSize==pPager->dbHintSize );
39320      break;
39321
39322    case PAGER_WRITER_DBMOD:
39323      assert( p->eLock==EXCLUSIVE_LOCK );
39324      assert( pPager->errCode==SQLITE_OK );
39325      assert( !pagerUseWal(pPager) );
39326      assert( p->eLock>=EXCLUSIVE_LOCK );
39327      assert( isOpen(p->jfd)
39328           || p->journalMode==PAGER_JOURNALMODE_OFF
39329           || p->journalMode==PAGER_JOURNALMODE_WAL
39330      );
39331      assert( pPager->dbOrigSize<=pPager->dbHintSize );
39332      break;
39333
39334    case PAGER_WRITER_FINISHED:
39335      assert( p->eLock==EXCLUSIVE_LOCK );
39336      assert( pPager->errCode==SQLITE_OK );
39337      assert( !pagerUseWal(pPager) );
39338      assert( isOpen(p->jfd)
39339           || p->journalMode==PAGER_JOURNALMODE_OFF
39340           || p->journalMode==PAGER_JOURNALMODE_WAL
39341      );
39342      break;
39343
39344    case PAGER_ERROR:
39345      /* There must be at least one outstanding reference to the pager if
39346      ** in ERROR state. Otherwise the pager should have already dropped
39347      ** back to OPEN state.
39348      */
39349      assert( pPager->errCode!=SQLITE_OK );
39350      assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
39351      break;
39352  }
39353
39354  return 1;
39355}
39356#endif /* ifndef NDEBUG */
39357
39358#ifdef SQLITE_DEBUG
39359/*
39360** Return a pointer to a human readable string in a static buffer
39361** containing the state of the Pager object passed as an argument. This
39362** is intended to be used within debuggers. For example, as an alternative
39363** to "print *pPager" in gdb:
39364**
39365** (gdb) printf "%s", print_pager_state(pPager)
39366*/
39367static char *print_pager_state(Pager *p){
39368  static char zRet[1024];
39369
39370  sqlite3_snprintf(1024, zRet,
39371      "Filename:      %s\n"
39372      "State:         %s errCode=%d\n"
39373      "Lock:          %s\n"
39374      "Locking mode:  locking_mode=%s\n"
39375      "Journal mode:  journal_mode=%s\n"
39376      "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
39377      "Journal:       journalOff=%lld journalHdr=%lld\n"
39378      "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
39379      , p->zFilename
39380      , p->eState==PAGER_OPEN            ? "OPEN" :
39381        p->eState==PAGER_READER          ? "READER" :
39382        p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
39383        p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
39384        p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
39385        p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
39386        p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
39387      , (int)p->errCode
39388      , p->eLock==NO_LOCK         ? "NO_LOCK" :
39389        p->eLock==RESERVED_LOCK   ? "RESERVED" :
39390        p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
39391        p->eLock==SHARED_LOCK     ? "SHARED" :
39392        p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
39393      , p->exclusiveMode ? "exclusive" : "normal"
39394      , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
39395        p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
39396        p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
39397        p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
39398        p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
39399        p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
39400      , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
39401      , p->journalOff, p->journalHdr
39402      , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
39403  );
39404
39405  return zRet;
39406}
39407#endif
39408
39409/*
39410** Return true if it is necessary to write page *pPg into the sub-journal.
39411** A page needs to be written into the sub-journal if there exists one
39412** or more open savepoints for which:
39413**
39414**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
39415**   * The bit corresponding to the page-number is not set in
39416**     PagerSavepoint.pInSavepoint.
39417*/
39418static int subjRequiresPage(PgHdr *pPg){
39419  Pgno pgno = pPg->pgno;
39420  Pager *pPager = pPg->pPager;
39421  int i;
39422  for(i=0; i<pPager->nSavepoint; i++){
39423    PagerSavepoint *p = &pPager->aSavepoint[i];
39424    if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
39425      return 1;
39426    }
39427  }
39428  return 0;
39429}
39430
39431/*
39432** Return true if the page is already in the journal file.
39433*/
39434static int pageInJournal(PgHdr *pPg){
39435  return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
39436}
39437
39438/*
39439** Read a 32-bit integer from the given file descriptor.  Store the integer
39440** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
39441** error code is something goes wrong.
39442**
39443** All values are stored on disk as big-endian.
39444*/
39445static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
39446  unsigned char ac[4];
39447  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
39448  if( rc==SQLITE_OK ){
39449    *pRes = sqlite3Get4byte(ac);
39450  }
39451  return rc;
39452}
39453
39454/*
39455** Write a 32-bit integer into a string buffer in big-endian byte order.
39456*/
39457#define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
39458
39459
39460/*
39461** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
39462** on success or an error code is something goes wrong.
39463*/
39464static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
39465  char ac[4];
39466  put32bits(ac, val);
39467  return sqlite3OsWrite(fd, ac, 4, offset);
39468}
39469
39470/*
39471** Unlock the database file to level eLock, which must be either NO_LOCK
39472** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
39473** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
39474**
39475** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
39476** called, do not modify it. See the comment above the #define of
39477** UNKNOWN_LOCK for an explanation of this.
39478*/
39479static int pagerUnlockDb(Pager *pPager, int eLock){
39480  int rc = SQLITE_OK;
39481
39482  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
39483  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
39484  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
39485  if( isOpen(pPager->fd) ){
39486    assert( pPager->eLock>=eLock );
39487    rc = sqlite3OsUnlock(pPager->fd, eLock);
39488    if( pPager->eLock!=UNKNOWN_LOCK ){
39489      pPager->eLock = (u8)eLock;
39490    }
39491    IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
39492  }
39493  return rc;
39494}
39495
39496/*
39497** Lock the database file to level eLock, which must be either SHARED_LOCK,
39498** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
39499** Pager.eLock variable to the new locking state.
39500**
39501** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
39502** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
39503** See the comment above the #define of UNKNOWN_LOCK for an explanation
39504** of this.
39505*/
39506static int pagerLockDb(Pager *pPager, int eLock){
39507  int rc = SQLITE_OK;
39508
39509  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
39510  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
39511    rc = sqlite3OsLock(pPager->fd, eLock);
39512    if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
39513      pPager->eLock = (u8)eLock;
39514      IOTRACE(("LOCK %p %d\n", pPager, eLock))
39515    }
39516  }
39517  return rc;
39518}
39519
39520/*
39521** This function determines whether or not the atomic-write optimization
39522** can be used with this pager. The optimization can be used if:
39523**
39524**  (a) the value returned by OsDeviceCharacteristics() indicates that
39525**      a database page may be written atomically, and
39526**  (b) the value returned by OsSectorSize() is less than or equal
39527**      to the page size.
39528**
39529** The optimization is also always enabled for temporary files. It is
39530** an error to call this function if pPager is opened on an in-memory
39531** database.
39532**
39533** If the optimization cannot be used, 0 is returned. If it can be used,
39534** then the value returned is the size of the journal file when it
39535** contains rollback data for exactly one page.
39536*/
39537#ifdef SQLITE_ENABLE_ATOMIC_WRITE
39538static int jrnlBufferSize(Pager *pPager){
39539  assert( !MEMDB );
39540  if( !pPager->tempFile ){
39541    int dc;                           /* Device characteristics */
39542    int nSector;                      /* Sector size */
39543    int szPage;                       /* Page size */
39544
39545    assert( isOpen(pPager->fd) );
39546    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
39547    nSector = pPager->sectorSize;
39548    szPage = pPager->pageSize;
39549
39550    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
39551    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
39552    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
39553      return 0;
39554    }
39555  }
39556
39557  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
39558}
39559#endif
39560
39561/*
39562** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
39563** on the cache using a hash function.  This is used for testing
39564** and debugging only.
39565*/
39566#ifdef SQLITE_CHECK_PAGES
39567/*
39568** Return a 32-bit hash of the page data for pPage.
39569*/
39570static u32 pager_datahash(int nByte, unsigned char *pData){
39571  u32 hash = 0;
39572  int i;
39573  for(i=0; i<nByte; i++){
39574    hash = (hash*1039) + pData[i];
39575  }
39576  return hash;
39577}
39578static u32 pager_pagehash(PgHdr *pPage){
39579  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
39580}
39581static void pager_set_pagehash(PgHdr *pPage){
39582  pPage->pageHash = pager_pagehash(pPage);
39583}
39584
39585/*
39586** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
39587** is defined, and NDEBUG is not defined, an assert() statement checks
39588** that the page is either dirty or still matches the calculated page-hash.
39589*/
39590#define CHECK_PAGE(x) checkPage(x)
39591static void checkPage(PgHdr *pPg){
39592  Pager *pPager = pPg->pPager;
39593  assert( pPager->eState!=PAGER_ERROR );
39594  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
39595}
39596
39597#else
39598#define pager_datahash(X,Y)  0
39599#define pager_pagehash(X)  0
39600#define pager_set_pagehash(X)
39601#define CHECK_PAGE(x)
39602#endif  /* SQLITE_CHECK_PAGES */
39603
39604/*
39605** When this is called the journal file for pager pPager must be open.
39606** This function attempts to read a master journal file name from the
39607** end of the file and, if successful, copies it into memory supplied
39608** by the caller. See comments above writeMasterJournal() for the format
39609** used to store a master journal file name at the end of a journal file.
39610**
39611** zMaster must point to a buffer of at least nMaster bytes allocated by
39612** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
39613** enough space to write the master journal name). If the master journal
39614** name in the journal is longer than nMaster bytes (including a
39615** nul-terminator), then this is handled as if no master journal name
39616** were present in the journal.
39617**
39618** If a master journal file name is present at the end of the journal
39619** file, then it is copied into the buffer pointed to by zMaster. A
39620** nul-terminator byte is appended to the buffer following the master
39621** journal file name.
39622**
39623** If it is determined that no master journal file name is present
39624** zMaster[0] is set to 0 and SQLITE_OK returned.
39625**
39626** If an error occurs while reading from the journal file, an SQLite
39627** error code is returned.
39628*/
39629static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
39630  int rc;                    /* Return code */
39631  u32 len;                   /* Length in bytes of master journal name */
39632  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
39633  u32 cksum;                 /* MJ checksum value read from journal */
39634  u32 u;                     /* Unsigned loop counter */
39635  unsigned char aMagic[8];   /* A buffer to hold the magic header */
39636  zMaster[0] = '\0';
39637
39638  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
39639   || szJ<16
39640   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
39641   || len>=nMaster
39642   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
39643   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
39644   || memcmp(aMagic, aJournalMagic, 8)
39645   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
39646  ){
39647    return rc;
39648  }
39649
39650  /* See if the checksum matches the master journal name */
39651  for(u=0; u<len; u++){
39652    cksum -= zMaster[u];
39653  }
39654  if( cksum ){
39655    /* If the checksum doesn't add up, then one or more of the disk sectors
39656    ** containing the master journal filename is corrupted. This means
39657    ** definitely roll back, so just return SQLITE_OK and report a (nul)
39658    ** master-journal filename.
39659    */
39660    len = 0;
39661  }
39662  zMaster[len] = '\0';
39663
39664  return SQLITE_OK;
39665}
39666
39667/*
39668** Return the offset of the sector boundary at or immediately
39669** following the value in pPager->journalOff, assuming a sector
39670** size of pPager->sectorSize bytes.
39671**
39672** i.e for a sector size of 512:
39673**
39674**   Pager.journalOff          Return value
39675**   ---------------------------------------
39676**   0                         0
39677**   512                       512
39678**   100                       512
39679**   2000                      2048
39680**
39681*/
39682static i64 journalHdrOffset(Pager *pPager){
39683  i64 offset = 0;
39684  i64 c = pPager->journalOff;
39685  if( c ){
39686    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
39687  }
39688  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
39689  assert( offset>=c );
39690  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
39691  return offset;
39692}
39693
39694/*
39695** The journal file must be open when this function is called.
39696**
39697** This function is a no-op if the journal file has not been written to
39698** within the current transaction (i.e. if Pager.journalOff==0).
39699**
39700** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
39701** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
39702** zero the 28-byte header at the start of the journal file. In either case,
39703** if the pager is not in no-sync mode, sync the journal file immediately
39704** after writing or truncating it.
39705**
39706** If Pager.journalSizeLimit is set to a positive, non-zero value, and
39707** following the truncation or zeroing described above the size of the
39708** journal file in bytes is larger than this value, then truncate the
39709** journal file to Pager.journalSizeLimit bytes. The journal file does
39710** not need to be synced following this operation.
39711**
39712** If an IO error occurs, abandon processing and return the IO error code.
39713** Otherwise, return SQLITE_OK.
39714*/
39715static int zeroJournalHdr(Pager *pPager, int doTruncate){
39716  int rc = SQLITE_OK;                               /* Return code */
39717  assert( isOpen(pPager->jfd) );
39718  if( pPager->journalOff ){
39719    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
39720
39721    IOTRACE(("JZEROHDR %p\n", pPager))
39722    if( doTruncate || iLimit==0 ){
39723      rc = sqlite3OsTruncate(pPager->jfd, 0);
39724    }else{
39725      static const char zeroHdr[28] = {0};
39726      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
39727    }
39728    if( rc==SQLITE_OK && !pPager->noSync ){
39729      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
39730    }
39731
39732    /* At this point the transaction is committed but the write lock
39733    ** is still held on the file. If there is a size limit configured for
39734    ** the persistent journal and the journal file currently consumes more
39735    ** space than that limit allows for, truncate it now. There is no need
39736    ** to sync the file following this operation.
39737    */
39738    if( rc==SQLITE_OK && iLimit>0 ){
39739      i64 sz;
39740      rc = sqlite3OsFileSize(pPager->jfd, &sz);
39741      if( rc==SQLITE_OK && sz>iLimit ){
39742        rc = sqlite3OsTruncate(pPager->jfd, iLimit);
39743      }
39744    }
39745  }
39746  return rc;
39747}
39748
39749/*
39750** The journal file must be open when this routine is called. A journal
39751** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
39752** current location.
39753**
39754** The format for the journal header is as follows:
39755** - 8 bytes: Magic identifying journal format.
39756** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
39757** - 4 bytes: Random number used for page hash.
39758** - 4 bytes: Initial database page count.
39759** - 4 bytes: Sector size used by the process that wrote this journal.
39760** - 4 bytes: Database page size.
39761**
39762** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
39763*/
39764static int writeJournalHdr(Pager *pPager){
39765  int rc = SQLITE_OK;                 /* Return code */
39766  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
39767  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
39768  u32 nWrite;                         /* Bytes of header sector written */
39769  int ii;                             /* Loop counter */
39770
39771  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
39772
39773  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
39774    nHeader = JOURNAL_HDR_SZ(pPager);
39775  }
39776
39777  /* If there are active savepoints and any of them were created
39778  ** since the most recent journal header was written, update the
39779  ** PagerSavepoint.iHdrOffset fields now.
39780  */
39781  for(ii=0; ii<pPager->nSavepoint; ii++){
39782    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
39783      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
39784    }
39785  }
39786
39787  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
39788
39789  /*
39790  ** Write the nRec Field - the number of page records that follow this
39791  ** journal header. Normally, zero is written to this value at this time.
39792  ** After the records are added to the journal (and the journal synced,
39793  ** if in full-sync mode), the zero is overwritten with the true number
39794  ** of records (see syncJournal()).
39795  **
39796  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
39797  ** reading the journal this value tells SQLite to assume that the
39798  ** rest of the journal file contains valid page records. This assumption
39799  ** is dangerous, as if a failure occurred whilst writing to the journal
39800  ** file it may contain some garbage data. There are two scenarios
39801  ** where this risk can be ignored:
39802  **
39803  **   * When the pager is in no-sync mode. Corruption can follow a
39804  **     power failure in this case anyway.
39805  **
39806  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
39807  **     that garbage data is never appended to the journal file.
39808  */
39809  assert( isOpen(pPager->fd) || pPager->noSync );
39810  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
39811   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
39812  ){
39813    memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
39814    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
39815  }else{
39816    memset(zHeader, 0, sizeof(aJournalMagic)+4);
39817  }
39818
39819  /* The random check-hash initialiser */
39820  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
39821  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
39822  /* The initial database size */
39823  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
39824  /* The assumed sector size for this process */
39825  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
39826
39827  /* The page size */
39828  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
39829
39830  /* Initializing the tail of the buffer is not necessary.  Everything
39831  ** works find if the following memset() is omitted.  But initializing
39832  ** the memory prevents valgrind from complaining, so we are willing to
39833  ** take the performance hit.
39834  */
39835  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
39836         nHeader-(sizeof(aJournalMagic)+20));
39837
39838  /* In theory, it is only necessary to write the 28 bytes that the
39839  ** journal header consumes to the journal file here. Then increment the
39840  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
39841  ** record is written to the following sector (leaving a gap in the file
39842  ** that will be implicitly filled in by the OS).
39843  **
39844  ** However it has been discovered that on some systems this pattern can
39845  ** be significantly slower than contiguously writing data to the file,
39846  ** even if that means explicitly writing data to the block of
39847  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
39848  ** is done.
39849  **
39850  ** The loop is required here in case the sector-size is larger than the
39851  ** database page size. Since the zHeader buffer is only Pager.pageSize
39852  ** bytes in size, more than one call to sqlite3OsWrite() may be required
39853  ** to populate the entire journal header sector.
39854  */
39855  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
39856    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
39857    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
39858    assert( pPager->journalHdr <= pPager->journalOff );
39859    pPager->journalOff += nHeader;
39860  }
39861
39862  return rc;
39863}
39864
39865/*
39866** The journal file must be open when this is called. A journal header file
39867** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
39868** file. The current location in the journal file is given by
39869** pPager->journalOff. See comments above function writeJournalHdr() for
39870** a description of the journal header format.
39871**
39872** If the header is read successfully, *pNRec is set to the number of
39873** page records following this header and *pDbSize is set to the size of the
39874** database before the transaction began, in pages. Also, pPager->cksumInit
39875** is set to the value read from the journal header. SQLITE_OK is returned
39876** in this case.
39877**
39878** If the journal header file appears to be corrupted, SQLITE_DONE is
39879** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
39880** cannot be read from the journal file an error code is returned.
39881*/
39882static int readJournalHdr(
39883  Pager *pPager,               /* Pager object */
39884  int isHot,
39885  i64 journalSize,             /* Size of the open journal file in bytes */
39886  u32 *pNRec,                  /* OUT: Value read from the nRec field */
39887  u32 *pDbSize                 /* OUT: Value of original database size field */
39888){
39889  int rc;                      /* Return code */
39890  unsigned char aMagic[8];     /* A buffer to hold the magic header */
39891  i64 iHdrOff;                 /* Offset of journal header being read */
39892
39893  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
39894
39895  /* Advance Pager.journalOff to the start of the next sector. If the
39896  ** journal file is too small for there to be a header stored at this
39897  ** point, return SQLITE_DONE.
39898  */
39899  pPager->journalOff = journalHdrOffset(pPager);
39900  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
39901    return SQLITE_DONE;
39902  }
39903  iHdrOff = pPager->journalOff;
39904
39905  /* Read in the first 8 bytes of the journal header. If they do not match
39906  ** the  magic string found at the start of each journal header, return
39907  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
39908  ** proceed.
39909  */
39910  if( isHot || iHdrOff!=pPager->journalHdr ){
39911    rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
39912    if( rc ){
39913      return rc;
39914    }
39915    if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
39916      return SQLITE_DONE;
39917    }
39918  }
39919
39920  /* Read the first three 32-bit fields of the journal header: The nRec
39921  ** field, the checksum-initializer and the database size at the start
39922  ** of the transaction. Return an error code if anything goes wrong.
39923  */
39924  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
39925   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
39926   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
39927  ){
39928    return rc;
39929  }
39930
39931  if( pPager->journalOff==0 ){
39932    u32 iPageSize;               /* Page-size field of journal header */
39933    u32 iSectorSize;             /* Sector-size field of journal header */
39934
39935    /* Read the page-size and sector-size journal header fields. */
39936    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
39937     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
39938    ){
39939      return rc;
39940    }
39941
39942    /* Versions of SQLite prior to 3.5.8 set the page-size field of the
39943    ** journal header to zero. In this case, assume that the Pager.pageSize
39944    ** variable is already set to the correct page size.
39945    */
39946    if( iPageSize==0 ){
39947      iPageSize = pPager->pageSize;
39948    }
39949
39950    /* Check that the values read from the page-size and sector-size fields
39951    ** are within range. To be 'in range', both values need to be a power
39952    ** of two greater than or equal to 512 or 32, and not greater than their
39953    ** respective compile time maximum limits.
39954    */
39955    if( iPageSize<512                  || iSectorSize<32
39956     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
39957     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0
39958    ){
39959      /* If the either the page-size or sector-size in the journal-header is
39960      ** invalid, then the process that wrote the journal-header must have
39961      ** crashed before the header was synced. In this case stop reading
39962      ** the journal file here.
39963      */
39964      return SQLITE_DONE;
39965    }
39966
39967    /* Update the page-size to match the value read from the journal.
39968    ** Use a testcase() macro to make sure that malloc failure within
39969    ** PagerSetPagesize() is tested.
39970    */
39971    rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
39972    testcase( rc!=SQLITE_OK );
39973
39974    /* Update the assumed sector-size to match the value used by
39975    ** the process that created this journal. If this journal was
39976    ** created by a process other than this one, then this routine
39977    ** is being called from within pager_playback(). The local value
39978    ** of Pager.sectorSize is restored at the end of that routine.
39979    */
39980    pPager->sectorSize = iSectorSize;
39981  }
39982
39983  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
39984  return rc;
39985}
39986
39987
39988/*
39989** Write the supplied master journal name into the journal file for pager
39990** pPager at the current location. The master journal name must be the last
39991** thing written to a journal file. If the pager is in full-sync mode, the
39992** journal file descriptor is advanced to the next sector boundary before
39993** anything is written. The format is:
39994**
39995**   + 4 bytes: PAGER_MJ_PGNO.
39996**   + N bytes: Master journal filename in utf-8.
39997**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
39998**   + 4 bytes: Master journal name checksum.
39999**   + 8 bytes: aJournalMagic[].
40000**
40001** The master journal page checksum is the sum of the bytes in the master
40002** journal name, where each byte is interpreted as a signed 8-bit integer.
40003**
40004** If zMaster is a NULL pointer (occurs for a single database transaction),
40005** this call is a no-op.
40006*/
40007static int writeMasterJournal(Pager *pPager, const char *zMaster){
40008  int rc;                          /* Return code */
40009  int nMaster;                     /* Length of string zMaster */
40010  i64 iHdrOff;                     /* Offset of header in journal file */
40011  i64 jrnlSize;                    /* Size of journal file on disk */
40012  u32 cksum = 0;                   /* Checksum of string zMaster */
40013
40014  assert( pPager->setMaster==0 );
40015  assert( !pagerUseWal(pPager) );
40016
40017  if( !zMaster
40018   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
40019   || pPager->journalMode==PAGER_JOURNALMODE_OFF
40020  ){
40021    return SQLITE_OK;
40022  }
40023  pPager->setMaster = 1;
40024  assert( isOpen(pPager->jfd) );
40025  assert( pPager->journalHdr <= pPager->journalOff );
40026
40027  /* Calculate the length in bytes and the checksum of zMaster */
40028  for(nMaster=0; zMaster[nMaster]; nMaster++){
40029    cksum += zMaster[nMaster];
40030  }
40031
40032  /* If in full-sync mode, advance to the next disk sector before writing
40033  ** the master journal name. This is in case the previous page written to
40034  ** the journal has already been synced.
40035  */
40036  if( pPager->fullSync ){
40037    pPager->journalOff = journalHdrOffset(pPager);
40038  }
40039  iHdrOff = pPager->journalOff;
40040
40041  /* Write the master journal data to the end of the journal file. If
40042  ** an error occurs, return the error code to the caller.
40043  */
40044  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
40045   || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
40046   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
40047   || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
40048   || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
40049  ){
40050    return rc;
40051  }
40052  pPager->journalOff += (nMaster+20);
40053
40054  /* If the pager is in peristent-journal mode, then the physical
40055  ** journal-file may extend past the end of the master-journal name
40056  ** and 8 bytes of magic data just written to the file. This is
40057  ** dangerous because the code to rollback a hot-journal file
40058  ** will not be able to find the master-journal name to determine
40059  ** whether or not the journal is hot.
40060  **
40061  ** Easiest thing to do in this scenario is to truncate the journal
40062  ** file to the required size.
40063  */
40064  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
40065   && jrnlSize>pPager->journalOff
40066  ){
40067    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
40068  }
40069  return rc;
40070}
40071
40072/*
40073** Find a page in the hash table given its page number. Return
40074** a pointer to the page or NULL if the requested page is not
40075** already in memory.
40076*/
40077static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
40078  PgHdr *p;                         /* Return value */
40079
40080  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
40081  ** fail, since no attempt to allocate dynamic memory will be made.
40082  */
40083  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
40084  return p;
40085}
40086
40087/*
40088** Discard the entire contents of the in-memory page-cache.
40089*/
40090static void pager_reset(Pager *pPager){
40091  sqlite3BackupRestart(pPager->pBackup);
40092  sqlite3PcacheClear(pPager->pPCache);
40093}
40094
40095/*
40096** Free all structures in the Pager.aSavepoint[] array and set both
40097** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
40098** if it is open and the pager is not in exclusive mode.
40099*/
40100static void releaseAllSavepoints(Pager *pPager){
40101  int ii;               /* Iterator for looping through Pager.aSavepoint */
40102  for(ii=0; ii<pPager->nSavepoint; ii++){
40103    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40104  }
40105  if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
40106    sqlite3OsClose(pPager->sjfd);
40107  }
40108  sqlite3_free(pPager->aSavepoint);
40109  pPager->aSavepoint = 0;
40110  pPager->nSavepoint = 0;
40111  pPager->nSubRec = 0;
40112}
40113
40114/*
40115** Set the bit number pgno in the PagerSavepoint.pInSavepoint
40116** bitvecs of all open savepoints. Return SQLITE_OK if successful
40117** or SQLITE_NOMEM if a malloc failure occurs.
40118*/
40119static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
40120  int ii;                   /* Loop counter */
40121  int rc = SQLITE_OK;       /* Result code */
40122
40123  for(ii=0; ii<pPager->nSavepoint; ii++){
40124    PagerSavepoint *p = &pPager->aSavepoint[ii];
40125    if( pgno<=p->nOrig ){
40126      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
40127      testcase( rc==SQLITE_NOMEM );
40128      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40129    }
40130  }
40131  return rc;
40132}
40133
40134/*
40135** This function is a no-op if the pager is in exclusive mode and not
40136** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
40137** state.
40138**
40139** If the pager is not in exclusive-access mode, the database file is
40140** completely unlocked. If the file is unlocked and the file-system does
40141** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
40142** closed (if it is open).
40143**
40144** If the pager is in ERROR state when this function is called, the
40145** contents of the pager cache are discarded before switching back to
40146** the OPEN state. Regardless of whether the pager is in exclusive-mode
40147** or not, any journal file left in the file-system will be treated
40148** as a hot-journal and rolled back the next time a read-transaction
40149** is opened (by this or by any other connection).
40150*/
40151static void pager_unlock(Pager *pPager){
40152
40153  assert( pPager->eState==PAGER_READER
40154       || pPager->eState==PAGER_OPEN
40155       || pPager->eState==PAGER_ERROR
40156  );
40157
40158  sqlite3BitvecDestroy(pPager->pInJournal);
40159  pPager->pInJournal = 0;
40160  releaseAllSavepoints(pPager);
40161
40162  if( pagerUseWal(pPager) ){
40163    assert( !isOpen(pPager->jfd) );
40164    sqlite3WalEndReadTransaction(pPager->pWal);
40165    pPager->eState = PAGER_OPEN;
40166  }else if( !pPager->exclusiveMode ){
40167    int rc;                       /* Error code returned by pagerUnlockDb() */
40168    int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
40169
40170    /* If the operating system support deletion of open files, then
40171    ** close the journal file when dropping the database lock.  Otherwise
40172    ** another connection with journal_mode=delete might delete the file
40173    ** out from under us.
40174    */
40175    assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
40176    assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
40177    assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
40178    assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
40179    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
40180    assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
40181    if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
40182     || 1!=(pPager->journalMode & 5)
40183    ){
40184      sqlite3OsClose(pPager->jfd);
40185    }
40186
40187    /* If the pager is in the ERROR state and the call to unlock the database
40188    ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
40189    ** above the #define for UNKNOWN_LOCK for an explanation of why this
40190    ** is necessary.
40191    */
40192    rc = pagerUnlockDb(pPager, NO_LOCK);
40193    if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
40194      pPager->eLock = UNKNOWN_LOCK;
40195    }
40196
40197    /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
40198    ** without clearing the error code. This is intentional - the error
40199    ** code is cleared and the cache reset in the block below.
40200    */
40201    assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
40202    pPager->changeCountDone = 0;
40203    pPager->eState = PAGER_OPEN;
40204  }
40205
40206  /* If Pager.errCode is set, the contents of the pager cache cannot be
40207  ** trusted. Now that there are no outstanding references to the pager,
40208  ** it can safely move back to PAGER_OPEN state. This happens in both
40209  ** normal and exclusive-locking mode.
40210  */
40211  if( pPager->errCode ){
40212    assert( !MEMDB );
40213    pager_reset(pPager);
40214    pPager->changeCountDone = pPager->tempFile;
40215    pPager->eState = PAGER_OPEN;
40216    pPager->errCode = SQLITE_OK;
40217  }
40218
40219  pPager->journalOff = 0;
40220  pPager->journalHdr = 0;
40221  pPager->setMaster = 0;
40222}
40223
40224/*
40225** This function is called whenever an IOERR or FULL error that requires
40226** the pager to transition into the ERROR state may ahve occurred.
40227** The first argument is a pointer to the pager structure, the second
40228** the error-code about to be returned by a pager API function. The
40229** value returned is a copy of the second argument to this function.
40230**
40231** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
40232** IOERR sub-codes, the pager enters the ERROR state and the error code
40233** is stored in Pager.errCode. While the pager remains in the ERROR state,
40234** all major API calls on the Pager will immediately return Pager.errCode.
40235**
40236** The ERROR state indicates that the contents of the pager-cache
40237** cannot be trusted. This state can be cleared by completely discarding
40238** the contents of the pager-cache. If a transaction was active when
40239** the persistent error occurred, then the rollback journal may need
40240** to be replayed to restore the contents of the database file (as if
40241** it were a hot-journal).
40242*/
40243static int pager_error(Pager *pPager, int rc){
40244  int rc2 = rc & 0xff;
40245  assert( rc==SQLITE_OK || !MEMDB );
40246  assert(
40247       pPager->errCode==SQLITE_FULL ||
40248       pPager->errCode==SQLITE_OK ||
40249       (pPager->errCode & 0xff)==SQLITE_IOERR
40250  );
40251  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
40252    pPager->errCode = rc;
40253    pPager->eState = PAGER_ERROR;
40254  }
40255  return rc;
40256}
40257
40258/*
40259** This routine ends a transaction. A transaction is usually ended by
40260** either a COMMIT or a ROLLBACK operation. This routine may be called
40261** after rollback of a hot-journal, or if an error occurs while opening
40262** the journal file or writing the very first journal-header of a
40263** database transaction.
40264**
40265** This routine is never called in PAGER_ERROR state. If it is called
40266** in PAGER_NONE or PAGER_SHARED state and the lock held is less
40267** exclusive than a RESERVED lock, it is a no-op.
40268**
40269** Otherwise, any active savepoints are released.
40270**
40271** If the journal file is open, then it is "finalized". Once a journal
40272** file has been finalized it is not possible to use it to roll back a
40273** transaction. Nor will it be considered to be a hot-journal by this
40274** or any other database connection. Exactly how a journal is finalized
40275** depends on whether or not the pager is running in exclusive mode and
40276** the current journal-mode (Pager.journalMode value), as follows:
40277**
40278**   journalMode==MEMORY
40279**     Journal file descriptor is simply closed. This destroys an
40280**     in-memory journal.
40281**
40282**   journalMode==TRUNCATE
40283**     Journal file is truncated to zero bytes in size.
40284**
40285**   journalMode==PERSIST
40286**     The first 28 bytes of the journal file are zeroed. This invalidates
40287**     the first journal header in the file, and hence the entire journal
40288**     file. An invalid journal file cannot be rolled back.
40289**
40290**   journalMode==DELETE
40291**     The journal file is closed and deleted using sqlite3OsDelete().
40292**
40293**     If the pager is running in exclusive mode, this method of finalizing
40294**     the journal file is never used. Instead, if the journalMode is
40295**     DELETE and the pager is in exclusive mode, the method described under
40296**     journalMode==PERSIST is used instead.
40297**
40298** After the journal is finalized, the pager moves to PAGER_READER state.
40299** If running in non-exclusive rollback mode, the lock on the file is
40300** downgraded to a SHARED_LOCK.
40301**
40302** SQLITE_OK is returned if no error occurs. If an error occurs during
40303** any of the IO operations to finalize the journal file or unlock the
40304** database then the IO error code is returned to the user. If the
40305** operation to finalize the journal file fails, then the code still
40306** tries to unlock the database file if not in exclusive mode. If the
40307** unlock operation fails as well, then the first error code related
40308** to the first error encountered (the journal finalization one) is
40309** returned.
40310*/
40311static int pager_end_transaction(Pager *pPager, int hasMaster){
40312  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
40313  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
40314
40315  /* Do nothing if the pager does not have an open write transaction
40316  ** or at least a RESERVED lock. This function may be called when there
40317  ** is no write-transaction active but a RESERVED or greater lock is
40318  ** held under two circumstances:
40319  **
40320  **   1. After a successful hot-journal rollback, it is called with
40321  **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
40322  **
40323  **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
40324  **      lock switches back to locking_mode=normal and then executes a
40325  **      read-transaction, this function is called with eState==PAGER_READER
40326  **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
40327  */
40328  assert( assert_pager_state(pPager) );
40329  assert( pPager->eState!=PAGER_ERROR );
40330  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
40331    return SQLITE_OK;
40332  }
40333
40334  releaseAllSavepoints(pPager);
40335  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
40336  if( isOpen(pPager->jfd) ){
40337    assert( !pagerUseWal(pPager) );
40338
40339    /* Finalize the journal file. */
40340    if( sqlite3IsMemJournal(pPager->jfd) ){
40341      assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
40342      sqlite3OsClose(pPager->jfd);
40343    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
40344      if( pPager->journalOff==0 ){
40345        rc = SQLITE_OK;
40346      }else{
40347        rc = sqlite3OsTruncate(pPager->jfd, 0);
40348      }
40349      pPager->journalOff = 0;
40350    }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
40351      || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
40352    ){
40353      rc = zeroJournalHdr(pPager, hasMaster);
40354      pPager->journalOff = 0;
40355    }else{
40356      /* This branch may be executed with Pager.journalMode==MEMORY if
40357      ** a hot-journal was just rolled back. In this case the journal
40358      ** file should be closed and deleted. If this connection writes to
40359      ** the database file, it will do so using an in-memory journal.
40360      */
40361      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
40362           || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
40363           || pPager->journalMode==PAGER_JOURNALMODE_WAL
40364      );
40365      sqlite3OsClose(pPager->jfd);
40366      if( !pPager->tempFile ){
40367        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
40368      }
40369    }
40370  }
40371
40372#ifdef SQLITE_CHECK_PAGES
40373  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
40374  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
40375    PgHdr *p = pager_lookup(pPager, 1);
40376    if( p ){
40377      p->pageHash = 0;
40378      sqlite3PagerUnref(p);
40379    }
40380  }
40381#endif
40382
40383  sqlite3BitvecDestroy(pPager->pInJournal);
40384  pPager->pInJournal = 0;
40385  pPager->nRec = 0;
40386  sqlite3PcacheCleanAll(pPager->pPCache);
40387  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
40388
40389  if( pagerUseWal(pPager) ){
40390    /* Drop the WAL write-lock, if any. Also, if the connection was in
40391    ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
40392    ** lock held on the database file.
40393    */
40394    rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
40395    assert( rc2==SQLITE_OK );
40396  }
40397  if( !pPager->exclusiveMode
40398   && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
40399  ){
40400    rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
40401    pPager->changeCountDone = 0;
40402  }
40403  pPager->eState = PAGER_READER;
40404  pPager->setMaster = 0;
40405
40406  return (rc==SQLITE_OK?rc2:rc);
40407}
40408
40409/*
40410** Execute a rollback if a transaction is active and unlock the
40411** database file.
40412**
40413** If the pager has already entered the ERROR state, do not attempt
40414** the rollback at this time. Instead, pager_unlock() is called. The
40415** call to pager_unlock() will discard all in-memory pages, unlock
40416** the database file and move the pager back to OPEN state. If this
40417** means that there is a hot-journal left in the file-system, the next
40418** connection to obtain a shared lock on the pager (which may be this one)
40419** will roll it back.
40420**
40421** If the pager has not already entered the ERROR state, but an IO or
40422** malloc error occurs during a rollback, then this will itself cause
40423** the pager to enter the ERROR state. Which will be cleared by the
40424** call to pager_unlock(), as described above.
40425*/
40426static void pagerUnlockAndRollback(Pager *pPager){
40427  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
40428    assert( assert_pager_state(pPager) );
40429    if( pPager->eState>=PAGER_WRITER_LOCKED ){
40430      sqlite3BeginBenignMalloc();
40431      sqlite3PagerRollback(pPager);
40432      sqlite3EndBenignMalloc();
40433    }else if( !pPager->exclusiveMode ){
40434      assert( pPager->eState==PAGER_READER );
40435      pager_end_transaction(pPager, 0);
40436    }
40437  }
40438  pager_unlock(pPager);
40439}
40440
40441/*
40442** Parameter aData must point to a buffer of pPager->pageSize bytes
40443** of data. Compute and return a checksum based ont the contents of the
40444** page of data and the current value of pPager->cksumInit.
40445**
40446** This is not a real checksum. It is really just the sum of the
40447** random initial value (pPager->cksumInit) and every 200th byte
40448** of the page data, starting with byte offset (pPager->pageSize%200).
40449** Each byte is interpreted as an 8-bit unsigned integer.
40450**
40451** Changing the formula used to compute this checksum results in an
40452** incompatible journal file format.
40453**
40454** If journal corruption occurs due to a power failure, the most likely
40455** scenario is that one end or the other of the record will be changed.
40456** It is much less likely that the two ends of the journal record will be
40457** correct and the middle be corrupt.  Thus, this "checksum" scheme,
40458** though fast and simple, catches the mostly likely kind of corruption.
40459*/
40460static u32 pager_cksum(Pager *pPager, const u8 *aData){
40461  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
40462  int i = pPager->pageSize-200;          /* Loop counter */
40463  while( i>0 ){
40464    cksum += aData[i];
40465    i -= 200;
40466  }
40467  return cksum;
40468}
40469
40470/*
40471** Report the current page size and number of reserved bytes back
40472** to the codec.
40473*/
40474#ifdef SQLITE_HAS_CODEC
40475static void pagerReportSize(Pager *pPager){
40476  if( pPager->xCodecSizeChng ){
40477    pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
40478                           (int)pPager->nReserve);
40479  }
40480}
40481#else
40482# define pagerReportSize(X)     /* No-op if we do not support a codec */
40483#endif
40484
40485/*
40486** Read a single page from either the journal file (if isMainJrnl==1) or
40487** from the sub-journal (if isMainJrnl==0) and playback that page.
40488** The page begins at offset *pOffset into the file. The *pOffset
40489** value is increased to the start of the next page in the journal.
40490**
40491** The main rollback journal uses checksums - the statement journal does
40492** not.
40493**
40494** If the page number of the page record read from the (sub-)journal file
40495** is greater than the current value of Pager.dbSize, then playback is
40496** skipped and SQLITE_OK is returned.
40497**
40498** If pDone is not NULL, then it is a record of pages that have already
40499** been played back.  If the page at *pOffset has already been played back
40500** (if the corresponding pDone bit is set) then skip the playback.
40501** Make sure the pDone bit corresponding to the *pOffset page is set
40502** prior to returning.
40503**
40504** If the page record is successfully read from the (sub-)journal file
40505** and played back, then SQLITE_OK is returned. If an IO error occurs
40506** while reading the record from the (sub-)journal file or while writing
40507** to the database file, then the IO error code is returned. If data
40508** is successfully read from the (sub-)journal file but appears to be
40509** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
40510** two circumstances:
40511**
40512**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
40513**   * If the record is being rolled back from the main journal file
40514**     and the checksum field does not match the record content.
40515**
40516** Neither of these two scenarios are possible during a savepoint rollback.
40517**
40518** If this is a savepoint rollback, then memory may have to be dynamically
40519** allocated by this function. If this is the case and an allocation fails,
40520** SQLITE_NOMEM is returned.
40521*/
40522static int pager_playback_one_page(
40523  Pager *pPager,                /* The pager being played back */
40524  i64 *pOffset,                 /* Offset of record to playback */
40525  Bitvec *pDone,                /* Bitvec of pages already played back */
40526  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
40527  int isSavepnt                 /* True for a savepoint rollback */
40528){
40529  int rc;
40530  PgHdr *pPg;                   /* An existing page in the cache */
40531  Pgno pgno;                    /* The page number of a page in journal */
40532  u32 cksum;                    /* Checksum used for sanity checking */
40533  char *aData;                  /* Temporary storage for the page */
40534  sqlite3_file *jfd;            /* The file descriptor for the journal file */
40535  int isSynced;                 /* True if journal page is synced */
40536
40537  assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
40538  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
40539  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
40540  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
40541
40542  aData = pPager->pTmpSpace;
40543  assert( aData );         /* Temp storage must have already been allocated */
40544  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
40545
40546  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
40547  ** or savepoint rollback done at the request of the caller) or this is
40548  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
40549  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
40550  ** only reads from the main journal, not the sub-journal.
40551  */
40552  assert( pPager->eState>=PAGER_WRITER_CACHEMOD
40553       || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
40554  );
40555  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
40556
40557  /* Read the page number and page data from the journal or sub-journal
40558  ** file. Return an error code to the caller if an IO error occurs.
40559  */
40560  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
40561  rc = read32bits(jfd, *pOffset, &pgno);
40562  if( rc!=SQLITE_OK ) return rc;
40563  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
40564  if( rc!=SQLITE_OK ) return rc;
40565  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
40566
40567  /* Sanity checking on the page.  This is more important that I originally
40568  ** thought.  If a power failure occurs while the journal is being written,
40569  ** it could cause invalid data to be written into the journal.  We need to
40570  ** detect this invalid data (with high probability) and ignore it.
40571  */
40572  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
40573    assert( !isSavepnt );
40574    return SQLITE_DONE;
40575  }
40576  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
40577    return SQLITE_OK;
40578  }
40579  if( isMainJrnl ){
40580    rc = read32bits(jfd, (*pOffset)-4, &cksum);
40581    if( rc ) return rc;
40582    if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
40583      return SQLITE_DONE;
40584    }
40585  }
40586
40587  /* If this page has already been played by before during the current
40588  ** rollback, then don't bother to play it back again.
40589  */
40590  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
40591    return rc;
40592  }
40593
40594  /* When playing back page 1, restore the nReserve setting
40595  */
40596  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
40597    pPager->nReserve = ((u8*)aData)[20];
40598    pagerReportSize(pPager);
40599  }
40600
40601  /* If the pager is in CACHEMOD state, then there must be a copy of this
40602  ** page in the pager cache. In this case just update the pager cache,
40603  ** not the database file. The page is left marked dirty in this case.
40604  **
40605  ** An exception to the above rule: If the database is in no-sync mode
40606  ** and a page is moved during an incremental vacuum then the page may
40607  ** not be in the pager cache. Later: if a malloc() or IO error occurs
40608  ** during a Movepage() call, then the page may not be in the cache
40609  ** either. So the condition described in the above paragraph is not
40610  ** assert()able.
40611  **
40612  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
40613  ** pager cache if it exists and the main file. The page is then marked
40614  ** not dirty. Since this code is only executed in PAGER_OPEN state for
40615  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
40616  ** if the pager is in OPEN state.
40617  **
40618  ** Ticket #1171:  The statement journal might contain page content that is
40619  ** different from the page content at the start of the transaction.
40620  ** This occurs when a page is changed prior to the start of a statement
40621  ** then changed again within the statement.  When rolling back such a
40622  ** statement we must not write to the original database unless we know
40623  ** for certain that original page contents are synced into the main rollback
40624  ** journal.  Otherwise, a power loss might leave modified data in the
40625  ** database file without an entry in the rollback journal that can
40626  ** restore the database to its original form.  Two conditions must be
40627  ** met before writing to the database files. (1) the database must be
40628  ** locked.  (2) we know that the original page content is fully synced
40629  ** in the main journal either because the page is not in cache or else
40630  ** the page is marked as needSync==0.
40631  **
40632  ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
40633  ** is possible to fail a statement on a database that does not yet exist.
40634  ** Do not attempt to write if database file has never been opened.
40635  */
40636  if( pagerUseWal(pPager) ){
40637    pPg = 0;
40638  }else{
40639    pPg = pager_lookup(pPager, pgno);
40640  }
40641  assert( pPg || !MEMDB );
40642  assert( pPager->eState!=PAGER_OPEN || pPg==0 );
40643  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
40644           PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
40645           (isMainJrnl?"main-journal":"sub-journal")
40646  ));
40647  if( isMainJrnl ){
40648    isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
40649  }else{
40650    isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
40651  }
40652  if( isOpen(pPager->fd)
40653   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40654   && isSynced
40655  ){
40656    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
40657    testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
40658    assert( !pagerUseWal(pPager) );
40659    rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
40660    if( pgno>pPager->dbFileSize ){
40661      pPager->dbFileSize = pgno;
40662    }
40663    if( pPager->pBackup ){
40664      CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
40665      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
40666      CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
40667    }
40668  }else if( !isMainJrnl && pPg==0 ){
40669    /* If this is a rollback of a savepoint and data was not written to
40670    ** the database and the page is not in-memory, there is a potential
40671    ** problem. When the page is next fetched by the b-tree layer, it
40672    ** will be read from the database file, which may or may not be
40673    ** current.
40674    **
40675    ** There are a couple of different ways this can happen. All are quite
40676    ** obscure. When running in synchronous mode, this can only happen
40677    ** if the page is on the free-list at the start of the transaction, then
40678    ** populated, then moved using sqlite3PagerMovepage().
40679    **
40680    ** The solution is to add an in-memory page to the cache containing
40681    ** the data just read from the sub-journal. Mark the page as dirty
40682    ** and if the pager requires a journal-sync, then mark the page as
40683    ** requiring a journal-sync before it is written.
40684    */
40685    assert( isSavepnt );
40686    assert( pPager->doNotSpill==0 );
40687    pPager->doNotSpill++;
40688    rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
40689    assert( pPager->doNotSpill==1 );
40690    pPager->doNotSpill--;
40691    if( rc!=SQLITE_OK ) return rc;
40692    pPg->flags &= ~PGHDR_NEED_READ;
40693    sqlite3PcacheMakeDirty(pPg);
40694  }
40695  if( pPg ){
40696    /* No page should ever be explicitly rolled back that is in use, except
40697    ** for page 1 which is held in use in order to keep the lock on the
40698    ** database active. However such a page may be rolled back as a result
40699    ** of an internal error resulting in an automatic call to
40700    ** sqlite3PagerRollback().
40701    */
40702    void *pData;
40703    pData = pPg->pData;
40704    memcpy(pData, (u8*)aData, pPager->pageSize);
40705    pPager->xReiniter(pPg);
40706    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
40707      /* If the contents of this page were just restored from the main
40708      ** journal file, then its content must be as they were when the
40709      ** transaction was first opened. In this case we can mark the page
40710      ** as clean, since there will be no need to write it out to the
40711      ** database.
40712      **
40713      ** There is one exception to this rule. If the page is being rolled
40714      ** back as part of a savepoint (or statement) rollback from an
40715      ** unsynced portion of the main journal file, then it is not safe
40716      ** to mark the page as clean. This is because marking the page as
40717      ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
40718      ** already in the journal file (recorded in Pager.pInJournal) and
40719      ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
40720      ** again within this transaction, it will be marked as dirty but
40721      ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
40722      ** be written out into the database file before its journal file
40723      ** segment is synced. If a crash occurs during or following this,
40724      ** database corruption may ensue.
40725      */
40726      assert( !pagerUseWal(pPager) );
40727      sqlite3PcacheMakeClean(pPg);
40728    }
40729    pager_set_pagehash(pPg);
40730
40731    /* If this was page 1, then restore the value of Pager.dbFileVers.
40732    ** Do this before any decoding. */
40733    if( pgno==1 ){
40734      memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
40735    }
40736
40737    /* Decode the page just read from disk */
40738    CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
40739    sqlite3PcacheRelease(pPg);
40740  }
40741  return rc;
40742}
40743
40744/*
40745** Parameter zMaster is the name of a master journal file. A single journal
40746** file that referred to the master journal file has just been rolled back.
40747** This routine checks if it is possible to delete the master journal file,
40748** and does so if it is.
40749**
40750** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
40751** available for use within this function.
40752**
40753** When a master journal file is created, it is populated with the names
40754** of all of its child journals, one after another, formatted as utf-8
40755** encoded text. The end of each child journal file is marked with a
40756** nul-terminator byte (0x00). i.e. the entire contents of a master journal
40757** file for a transaction involving two databases might be:
40758**
40759**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
40760**
40761** A master journal file may only be deleted once all of its child
40762** journals have been rolled back.
40763**
40764** This function reads the contents of the master-journal file into
40765** memory and loops through each of the child journal names. For
40766** each child journal, it checks if:
40767**
40768**   * if the child journal exists, and if so
40769**   * if the child journal contains a reference to master journal
40770**     file zMaster
40771**
40772** If a child journal can be found that matches both of the criteria
40773** above, this function returns without doing anything. Otherwise, if
40774** no such child journal can be found, file zMaster is deleted from
40775** the file-system using sqlite3OsDelete().
40776**
40777** If an IO error within this function, an error code is returned. This
40778** function allocates memory by calling sqlite3Malloc(). If an allocation
40779** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
40780** occur, SQLITE_OK is returned.
40781**
40782** TODO: This function allocates a single block of memory to load
40783** the entire contents of the master journal file. This could be
40784** a couple of kilobytes or so - potentially larger than the page
40785** size.
40786*/
40787static int pager_delmaster(Pager *pPager, const char *zMaster){
40788  sqlite3_vfs *pVfs = pPager->pVfs;
40789  int rc;                   /* Return code */
40790  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
40791  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
40792  char *zMasterJournal = 0; /* Contents of master journal file */
40793  i64 nMasterJournal;       /* Size of master journal file */
40794  char *zJournal;           /* Pointer to one journal within MJ file */
40795  char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
40796  int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
40797
40798  /* Allocate space for both the pJournal and pMaster file descriptors.
40799  ** If successful, open the master journal file for reading.
40800  */
40801  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
40802  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
40803  if( !pMaster ){
40804    rc = SQLITE_NOMEM;
40805  }else{
40806    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
40807    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
40808  }
40809  if( rc!=SQLITE_OK ) goto delmaster_out;
40810
40811  /* Load the entire master journal file into space obtained from
40812  ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
40813  ** sufficient space (in zMasterPtr) to hold the names of master
40814  ** journal files extracted from regular rollback-journals.
40815  */
40816  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
40817  if( rc!=SQLITE_OK ) goto delmaster_out;
40818  nMasterPtr = pVfs->mxPathname+1;
40819  zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
40820  if( !zMasterJournal ){
40821    rc = SQLITE_NOMEM;
40822    goto delmaster_out;
40823  }
40824  zMasterPtr = &zMasterJournal[nMasterJournal+1];
40825  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
40826  if( rc!=SQLITE_OK ) goto delmaster_out;
40827  zMasterJournal[nMasterJournal] = 0;
40828
40829  zJournal = zMasterJournal;
40830  while( (zJournal-zMasterJournal)<nMasterJournal ){
40831    int exists;
40832    rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
40833    if( rc!=SQLITE_OK ){
40834      goto delmaster_out;
40835    }
40836    if( exists ){
40837      /* One of the journals pointed to by the master journal exists.
40838      ** Open it and check if it points at the master journal. If
40839      ** so, return without deleting the master journal file.
40840      */
40841      int c;
40842      int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
40843      rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
40844      if( rc!=SQLITE_OK ){
40845        goto delmaster_out;
40846      }
40847
40848      rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
40849      sqlite3OsClose(pJournal);
40850      if( rc!=SQLITE_OK ){
40851        goto delmaster_out;
40852      }
40853
40854      c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
40855      if( c ){
40856        /* We have a match. Do not delete the master journal file. */
40857        goto delmaster_out;
40858      }
40859    }
40860    zJournal += (sqlite3Strlen30(zJournal)+1);
40861  }
40862
40863  sqlite3OsClose(pMaster);
40864  rc = sqlite3OsDelete(pVfs, zMaster, 0);
40865
40866delmaster_out:
40867  sqlite3_free(zMasterJournal);
40868  if( pMaster ){
40869    sqlite3OsClose(pMaster);
40870    assert( !isOpen(pJournal) );
40871    sqlite3_free(pMaster);
40872  }
40873  return rc;
40874}
40875
40876
40877/*
40878** This function is used to change the actual size of the database
40879** file in the file-system. This only happens when committing a transaction,
40880** or rolling back a transaction (including rolling back a hot-journal).
40881**
40882** If the main database file is not open, or the pager is not in either
40883** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
40884** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
40885** If the file on disk is currently larger than nPage pages, then use the VFS
40886** xTruncate() method to truncate it.
40887**
40888** Or, it might might be the case that the file on disk is smaller than
40889** nPage pages. Some operating system implementations can get confused if
40890** you try to truncate a file to some size that is larger than it
40891** currently is, so detect this case and write a single zero byte to
40892** the end of the new file instead.
40893**
40894** If successful, return SQLITE_OK. If an IO error occurs while modifying
40895** the database file, return the error code to the caller.
40896*/
40897static int pager_truncate(Pager *pPager, Pgno nPage){
40898  int rc = SQLITE_OK;
40899  assert( pPager->eState!=PAGER_ERROR );
40900  assert( pPager->eState!=PAGER_READER );
40901
40902  if( isOpen(pPager->fd)
40903   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40904  ){
40905    i64 currentSize, newSize;
40906    int szPage = pPager->pageSize;
40907    assert( pPager->eLock==EXCLUSIVE_LOCK );
40908    /* TODO: Is it safe to use Pager.dbFileSize here? */
40909    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
40910    newSize = szPage*(i64)nPage;
40911    if( rc==SQLITE_OK && currentSize!=newSize ){
40912      if( currentSize>newSize ){
40913        rc = sqlite3OsTruncate(pPager->fd, newSize);
40914      }else if( (currentSize+szPage)<=newSize ){
40915        char *pTmp = pPager->pTmpSpace;
40916        memset(pTmp, 0, szPage);
40917        testcase( (newSize-szPage) == currentSize );
40918        testcase( (newSize-szPage) >  currentSize );
40919        rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
40920      }
40921      if( rc==SQLITE_OK ){
40922        pPager->dbFileSize = nPage;
40923      }
40924    }
40925  }
40926  return rc;
40927}
40928
40929/*
40930** Set the value of the Pager.sectorSize variable for the given
40931** pager based on the value returned by the xSectorSize method
40932** of the open database file. The sector size will be used used
40933** to determine the size and alignment of journal header and
40934** master journal pointers within created journal files.
40935**
40936** For temporary files the effective sector size is always 512 bytes.
40937**
40938** Otherwise, for non-temporary files, the effective sector size is
40939** the value returned by the xSectorSize() method rounded up to 32 if
40940** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
40941** is greater than MAX_SECTOR_SIZE.
40942**
40943** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
40944** the effective sector size to its minimum value (512).  The purpose of
40945** pPager->sectorSize is to define the "blast radius" of bytes that
40946** might change if a crash occurs while writing to a single byte in
40947** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
40948** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
40949** size.  For backwards compatibility of the rollback journal file format,
40950** we cannot reduce the effective sector size below 512.
40951*/
40952static void setSectorSize(Pager *pPager){
40953  assert( isOpen(pPager->fd) || pPager->tempFile );
40954
40955  if( pPager->tempFile
40956   || (sqlite3OsDeviceCharacteristics(pPager->fd) &
40957              SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
40958  ){
40959    /* Sector size doesn't matter for temporary files. Also, the file
40960    ** may not have been opened yet, in which case the OsSectorSize()
40961    ** call will segfault. */
40962    pPager->sectorSize = 512;
40963  }else{
40964    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
40965    if( pPager->sectorSize<32 ){
40966      pPager->sectorSize = 512;
40967    }
40968    if( pPager->sectorSize>MAX_SECTOR_SIZE ){
40969      assert( MAX_SECTOR_SIZE>=512 );
40970      pPager->sectorSize = MAX_SECTOR_SIZE;
40971    }
40972  }
40973}
40974
40975/*
40976** Playback the journal and thus restore the database file to
40977** the state it was in before we started making changes.
40978**
40979** The journal file format is as follows:
40980**
40981**  (1)  8 byte prefix.  A copy of aJournalMagic[].
40982**  (2)  4 byte big-endian integer which is the number of valid page records
40983**       in the journal.  If this value is 0xffffffff, then compute the
40984**       number of page records from the journal size.
40985**  (3)  4 byte big-endian integer which is the initial value for the
40986**       sanity checksum.
40987**  (4)  4 byte integer which is the number of pages to truncate the
40988**       database to during a rollback.
40989**  (5)  4 byte big-endian integer which is the sector size.  The header
40990**       is this many bytes in size.
40991**  (6)  4 byte big-endian integer which is the page size.
40992**  (7)  zero padding out to the next sector size.
40993**  (8)  Zero or more pages instances, each as follows:
40994**        +  4 byte page number.
40995**        +  pPager->pageSize bytes of data.
40996**        +  4 byte checksum
40997**
40998** When we speak of the journal header, we mean the first 7 items above.
40999** Each entry in the journal is an instance of the 8th item.
41000**
41001** Call the value from the second bullet "nRec".  nRec is the number of
41002** valid page entries in the journal.  In most cases, you can compute the
41003** value of nRec from the size of the journal file.  But if a power
41004** failure occurred while the journal was being written, it could be the
41005** case that the size of the journal file had already been increased but
41006** the extra entries had not yet made it safely to disk.  In such a case,
41007** the value of nRec computed from the file size would be too large.  For
41008** that reason, we always use the nRec value in the header.
41009**
41010** If the nRec value is 0xffffffff it means that nRec should be computed
41011** from the file size.  This value is used when the user selects the
41012** no-sync option for the journal.  A power failure could lead to corruption
41013** in this case.  But for things like temporary table (which will be
41014** deleted when the power is restored) we don't care.
41015**
41016** If the file opened as the journal file is not a well-formed
41017** journal file then all pages up to the first corrupted page are rolled
41018** back (or no pages if the journal header is corrupted). The journal file
41019** is then deleted and SQLITE_OK returned, just as if no corruption had
41020** been encountered.
41021**
41022** If an I/O or malloc() error occurs, the journal-file is not deleted
41023** and an error code is returned.
41024**
41025** The isHot parameter indicates that we are trying to rollback a journal
41026** that might be a hot journal.  Or, it could be that the journal is
41027** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
41028** If the journal really is hot, reset the pager cache prior rolling
41029** back any content.  If the journal is merely persistent, no reset is
41030** needed.
41031*/
41032static int pager_playback(Pager *pPager, int isHot){
41033  sqlite3_vfs *pVfs = pPager->pVfs;
41034  i64 szJ;                 /* Size of the journal file in bytes */
41035  u32 nRec;                /* Number of Records in the journal */
41036  u32 u;                   /* Unsigned loop counter */
41037  Pgno mxPg = 0;           /* Size of the original file in pages */
41038  int rc;                  /* Result code of a subroutine */
41039  int res = 1;             /* Value returned by sqlite3OsAccess() */
41040  char *zMaster = 0;       /* Name of master journal file if any */
41041  int needPagerReset;      /* True to reset page prior to first page rollback */
41042
41043  /* Figure out how many records are in the journal.  Abort early if
41044  ** the journal is empty.
41045  */
41046  assert( isOpen(pPager->jfd) );
41047  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
41048  if( rc!=SQLITE_OK ){
41049    goto end_playback;
41050  }
41051
41052  /* Read the master journal name from the journal, if it is present.
41053  ** If a master journal file name is specified, but the file is not
41054  ** present on disk, then the journal is not hot and does not need to be
41055  ** played back.
41056  **
41057  ** TODO: Technically the following is an error because it assumes that
41058  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
41059  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
41060  **  mxPathname is 512, which is the same as the minimum allowable value
41061  ** for pageSize.
41062  */
41063  zMaster = pPager->pTmpSpace;
41064  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41065  if( rc==SQLITE_OK && zMaster[0] ){
41066    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
41067  }
41068  zMaster = 0;
41069  if( rc!=SQLITE_OK || !res ){
41070    goto end_playback;
41071  }
41072  pPager->journalOff = 0;
41073  needPagerReset = isHot;
41074
41075  /* This loop terminates either when a readJournalHdr() or
41076  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
41077  ** occurs.
41078  */
41079  while( 1 ){
41080    /* Read the next journal header from the journal file.  If there are
41081    ** not enough bytes left in the journal file for a complete header, or
41082    ** it is corrupted, then a process must have failed while writing it.
41083    ** This indicates nothing more needs to be rolled back.
41084    */
41085    rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
41086    if( rc!=SQLITE_OK ){
41087      if( rc==SQLITE_DONE ){
41088        rc = SQLITE_OK;
41089      }
41090      goto end_playback;
41091    }
41092
41093    /* If nRec is 0xffffffff, then this journal was created by a process
41094    ** working in no-sync mode. This means that the rest of the journal
41095    ** file consists of pages, there are no more journal headers. Compute
41096    ** the value of nRec based on this assumption.
41097    */
41098    if( nRec==0xffffffff ){
41099      assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
41100      nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
41101    }
41102
41103    /* If nRec is 0 and this rollback is of a transaction created by this
41104    ** process and if this is the final header in the journal, then it means
41105    ** that this part of the journal was being filled but has not yet been
41106    ** synced to disk.  Compute the number of pages based on the remaining
41107    ** size of the file.
41108    **
41109    ** The third term of the test was added to fix ticket #2565.
41110    ** When rolling back a hot journal, nRec==0 always means that the next
41111    ** chunk of the journal contains zero pages to be rolled back.  But
41112    ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
41113    ** the journal, it means that the journal might contain additional
41114    ** pages that need to be rolled back and that the number of pages
41115    ** should be computed based on the journal file size.
41116    */
41117    if( nRec==0 && !isHot &&
41118        pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
41119      nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
41120    }
41121
41122    /* If this is the first header read from the journal, truncate the
41123    ** database file back to its original size.
41124    */
41125    if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
41126      rc = pager_truncate(pPager, mxPg);
41127      if( rc!=SQLITE_OK ){
41128        goto end_playback;
41129      }
41130      pPager->dbSize = mxPg;
41131    }
41132
41133    /* Copy original pages out of the journal and back into the
41134    ** database file and/or page cache.
41135    */
41136    for(u=0; u<nRec; u++){
41137      if( needPagerReset ){
41138        pager_reset(pPager);
41139        needPagerReset = 0;
41140      }
41141      rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
41142      if( rc!=SQLITE_OK ){
41143        if( rc==SQLITE_DONE ){
41144          pPager->journalOff = szJ;
41145          break;
41146        }else if( rc==SQLITE_IOERR_SHORT_READ ){
41147          /* If the journal has been truncated, simply stop reading and
41148          ** processing the journal. This might happen if the journal was
41149          ** not completely written and synced prior to a crash.  In that
41150          ** case, the database should have never been written in the
41151          ** first place so it is OK to simply abandon the rollback. */
41152          rc = SQLITE_OK;
41153          goto end_playback;
41154        }else{
41155          /* If we are unable to rollback, quit and return the error
41156          ** code.  This will cause the pager to enter the error state
41157          ** so that no further harm will be done.  Perhaps the next
41158          ** process to come along will be able to rollback the database.
41159          */
41160          goto end_playback;
41161        }
41162      }
41163    }
41164  }
41165  /*NOTREACHED*/
41166  assert( 0 );
41167
41168end_playback:
41169  /* Following a rollback, the database file should be back in its original
41170  ** state prior to the start of the transaction, so invoke the
41171  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
41172  ** assertion that the transaction counter was modified.
41173  */
41174#ifdef SQLITE_DEBUG
41175  if( pPager->fd->pMethods ){
41176    sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
41177  }
41178#endif
41179
41180  /* If this playback is happening automatically as a result of an IO or
41181  ** malloc error that occurred after the change-counter was updated but
41182  ** before the transaction was committed, then the change-counter
41183  ** modification may just have been reverted. If this happens in exclusive
41184  ** mode, then subsequent transactions performed by the connection will not
41185  ** update the change-counter at all. This may lead to cache inconsistency
41186  ** problems for other processes at some point in the future. So, just
41187  ** in case this has happened, clear the changeCountDone flag now.
41188  */
41189  pPager->changeCountDone = pPager->tempFile;
41190
41191  if( rc==SQLITE_OK ){
41192    zMaster = pPager->pTmpSpace;
41193    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41194    testcase( rc!=SQLITE_OK );
41195  }
41196  if( rc==SQLITE_OK
41197   && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41198  ){
41199    rc = sqlite3PagerSync(pPager);
41200  }
41201  if( rc==SQLITE_OK ){
41202    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
41203    testcase( rc!=SQLITE_OK );
41204  }
41205  if( rc==SQLITE_OK && zMaster[0] && res ){
41206    /* If there was a master journal and this routine will return success,
41207    ** see if it is possible to delete the master journal.
41208    */
41209    rc = pager_delmaster(pPager, zMaster);
41210    testcase( rc!=SQLITE_OK );
41211  }
41212
41213  /* The Pager.sectorSize variable may have been updated while rolling
41214  ** back a journal created by a process with a different sector size
41215  ** value. Reset it to the correct value for this process.
41216  */
41217  setSectorSize(pPager);
41218  return rc;
41219}
41220
41221
41222/*
41223** Read the content for page pPg out of the database file and into
41224** pPg->pData. A shared lock or greater must be held on the database
41225** file before this function is called.
41226**
41227** If page 1 is read, then the value of Pager.dbFileVers[] is set to
41228** the value read from the database file.
41229**
41230** If an IO error occurs, then the IO error is returned to the caller.
41231** Otherwise, SQLITE_OK is returned.
41232*/
41233static int readDbPage(PgHdr *pPg){
41234  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
41235  Pgno pgno = pPg->pgno;       /* Page number to read */
41236  int rc = SQLITE_OK;          /* Return code */
41237  int isInWal = 0;             /* True if page is in log file */
41238  int pgsz = pPager->pageSize; /* Number of bytes to read */
41239
41240  assert( pPager->eState>=PAGER_READER && !MEMDB );
41241  assert( isOpen(pPager->fd) );
41242
41243  if( NEVER(!isOpen(pPager->fd)) ){
41244    assert( pPager->tempFile );
41245    memset(pPg->pData, 0, pPager->pageSize);
41246    return SQLITE_OK;
41247  }
41248
41249  if( pagerUseWal(pPager) ){
41250    /* Try to pull the page from the write-ahead log. */
41251    rc = sqlite3WalRead(pPager->pWal, pgno, &isInWal, pgsz, pPg->pData);
41252  }
41253  if( rc==SQLITE_OK && !isInWal ){
41254    i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
41255    rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
41256    if( rc==SQLITE_IOERR_SHORT_READ ){
41257      rc = SQLITE_OK;
41258    }
41259  }
41260
41261  if( pgno==1 ){
41262    if( rc ){
41263      /* If the read is unsuccessful, set the dbFileVers[] to something
41264      ** that will never be a valid file version.  dbFileVers[] is a copy
41265      ** of bytes 24..39 of the database.  Bytes 28..31 should always be
41266      ** zero or the size of the database in page. Bytes 32..35 and 35..39
41267      ** should be page numbers which are never 0xffffffff.  So filling
41268      ** pPager->dbFileVers[] with all 0xff bytes should suffice.
41269      **
41270      ** For an encrypted database, the situation is more complex:  bytes
41271      ** 24..39 of the database are white noise.  But the probability of
41272      ** white noising equaling 16 bytes of 0xff is vanishingly small so
41273      ** we should still be ok.
41274      */
41275      memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
41276    }else{
41277      u8 *dbFileVers = &((u8*)pPg->pData)[24];
41278      memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
41279    }
41280  }
41281  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
41282
41283  PAGER_INCR(sqlite3_pager_readdb_count);
41284  PAGER_INCR(pPager->nRead);
41285  IOTRACE(("PGIN %p %d\n", pPager, pgno));
41286  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
41287               PAGERID(pPager), pgno, pager_pagehash(pPg)));
41288
41289  return rc;
41290}
41291
41292/*
41293** Update the value of the change-counter at offsets 24 and 92 in
41294** the header and the sqlite version number at offset 96.
41295**
41296** This is an unconditional update.  See also the pager_incr_changecounter()
41297** routine which only updates the change-counter if the update is actually
41298** needed, as determined by the pPager->changeCountDone state variable.
41299*/
41300static void pager_write_changecounter(PgHdr *pPg){
41301  u32 change_counter;
41302
41303  /* Increment the value just read and write it back to byte 24. */
41304  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
41305  put32bits(((char*)pPg->pData)+24, change_counter);
41306
41307  /* Also store the SQLite version number in bytes 96..99 and in
41308  ** bytes 92..95 store the change counter for which the version number
41309  ** is valid. */
41310  put32bits(((char*)pPg->pData)+92, change_counter);
41311  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
41312}
41313
41314#ifndef SQLITE_OMIT_WAL
41315/*
41316** This function is invoked once for each page that has already been
41317** written into the log file when a WAL transaction is rolled back.
41318** Parameter iPg is the page number of said page. The pCtx argument
41319** is actually a pointer to the Pager structure.
41320**
41321** If page iPg is present in the cache, and has no outstanding references,
41322** it is discarded. Otherwise, if there are one or more outstanding
41323** references, the page content is reloaded from the database. If the
41324** attempt to reload content from the database is required and fails,
41325** return an SQLite error code. Otherwise, SQLITE_OK.
41326*/
41327static int pagerUndoCallback(void *pCtx, Pgno iPg){
41328  int rc = SQLITE_OK;
41329  Pager *pPager = (Pager *)pCtx;
41330  PgHdr *pPg;
41331
41332  pPg = sqlite3PagerLookup(pPager, iPg);
41333  if( pPg ){
41334    if( sqlite3PcachePageRefcount(pPg)==1 ){
41335      sqlite3PcacheDrop(pPg);
41336    }else{
41337      rc = readDbPage(pPg);
41338      if( rc==SQLITE_OK ){
41339        pPager->xReiniter(pPg);
41340      }
41341      sqlite3PagerUnref(pPg);
41342    }
41343  }
41344
41345  /* Normally, if a transaction is rolled back, any backup processes are
41346  ** updated as data is copied out of the rollback journal and into the
41347  ** database. This is not generally possible with a WAL database, as
41348  ** rollback involves simply truncating the log file. Therefore, if one
41349  ** or more frames have already been written to the log (and therefore
41350  ** also copied into the backup databases) as part of this transaction,
41351  ** the backups must be restarted.
41352  */
41353  sqlite3BackupRestart(pPager->pBackup);
41354
41355  return rc;
41356}
41357
41358/*
41359** This function is called to rollback a transaction on a WAL database.
41360*/
41361static int pagerRollbackWal(Pager *pPager){
41362  int rc;                         /* Return Code */
41363  PgHdr *pList;                   /* List of dirty pages to revert */
41364
41365  /* For all pages in the cache that are currently dirty or have already
41366  ** been written (but not committed) to the log file, do one of the
41367  ** following:
41368  **
41369  **   + Discard the cached page (if refcount==0), or
41370  **   + Reload page content from the database (if refcount>0).
41371  */
41372  pPager->dbSize = pPager->dbOrigSize;
41373  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
41374  pList = sqlite3PcacheDirtyList(pPager->pPCache);
41375  while( pList && rc==SQLITE_OK ){
41376    PgHdr *pNext = pList->pDirty;
41377    rc = pagerUndoCallback((void *)pPager, pList->pgno);
41378    pList = pNext;
41379  }
41380
41381  return rc;
41382}
41383
41384/*
41385** This function is a wrapper around sqlite3WalFrames(). As well as logging
41386** the contents of the list of pages headed by pList (connected by pDirty),
41387** this function notifies any active backup processes that the pages have
41388** changed.
41389**
41390** The list of pages passed into this routine is always sorted by page number.
41391** Hence, if page 1 appears anywhere on the list, it will be the first page.
41392*/
41393static int pagerWalFrames(
41394  Pager *pPager,                  /* Pager object */
41395  PgHdr *pList,                   /* List of frames to log */
41396  Pgno nTruncate,                 /* Database size after this commit */
41397  int isCommit                    /* True if this is a commit */
41398){
41399  int rc;                         /* Return code */
41400#if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
41401  PgHdr *p;                       /* For looping over pages */
41402#endif
41403
41404  assert( pPager->pWal );
41405  assert( pList );
41406#ifdef SQLITE_DEBUG
41407  /* Verify that the page list is in accending order */
41408  for(p=pList; p && p->pDirty; p=p->pDirty){
41409    assert( p->pgno < p->pDirty->pgno );
41410  }
41411#endif
41412
41413  if( isCommit ){
41414    /* If a WAL transaction is being committed, there is no point in writing
41415    ** any pages with page numbers greater than nTruncate into the WAL file.
41416    ** They will never be read by any client. So remove them from the pDirty
41417    ** list here. */
41418    PgHdr *p;
41419    PgHdr **ppNext = &pList;
41420    for(p=pList; (*ppNext = p); p=p->pDirty){
41421      if( p->pgno<=nTruncate ) ppNext = &p->pDirty;
41422    }
41423    assert( pList );
41424  }
41425
41426  if( pList->pgno==1 ) pager_write_changecounter(pList);
41427  rc = sqlite3WalFrames(pPager->pWal,
41428      pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
41429  );
41430  if( rc==SQLITE_OK && pPager->pBackup ){
41431    PgHdr *p;
41432    for(p=pList; p; p=p->pDirty){
41433      sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
41434    }
41435  }
41436
41437#ifdef SQLITE_CHECK_PAGES
41438  pList = sqlite3PcacheDirtyList(pPager->pPCache);
41439  for(p=pList; p; p=p->pDirty){
41440    pager_set_pagehash(p);
41441  }
41442#endif
41443
41444  return rc;
41445}
41446
41447/*
41448** Begin a read transaction on the WAL.
41449**
41450** This routine used to be called "pagerOpenSnapshot()" because it essentially
41451** makes a snapshot of the database at the current point in time and preserves
41452** that snapshot for use by the reader in spite of concurrently changes by
41453** other writers or checkpointers.
41454*/
41455static int pagerBeginReadTransaction(Pager *pPager){
41456  int rc;                         /* Return code */
41457  int changed = 0;                /* True if cache must be reset */
41458
41459  assert( pagerUseWal(pPager) );
41460  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41461
41462  /* sqlite3WalEndReadTransaction() was not called for the previous
41463  ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
41464  ** are in locking_mode=NORMAL and EndRead() was previously called,
41465  ** the duplicate call is harmless.
41466  */
41467  sqlite3WalEndReadTransaction(pPager->pWal);
41468
41469  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
41470  if( rc!=SQLITE_OK || changed ){
41471    pager_reset(pPager);
41472  }
41473
41474  return rc;
41475}
41476#endif
41477
41478/*
41479** This function is called as part of the transition from PAGER_OPEN
41480** to PAGER_READER state to determine the size of the database file
41481** in pages (assuming the page size currently stored in Pager.pageSize).
41482**
41483** If no error occurs, SQLITE_OK is returned and the size of the database
41484** in pages is stored in *pnPage. Otherwise, an error code (perhaps
41485** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
41486*/
41487static int pagerPagecount(Pager *pPager, Pgno *pnPage){
41488  Pgno nPage;                     /* Value to return via *pnPage */
41489
41490  /* Query the WAL sub-system for the database size. The WalDbsize()
41491  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
41492  ** if the database size is not available. The database size is not
41493  ** available from the WAL sub-system if the log file is empty or
41494  ** contains no valid committed transactions.
41495  */
41496  assert( pPager->eState==PAGER_OPEN );
41497  assert( pPager->eLock>=SHARED_LOCK );
41498  nPage = sqlite3WalDbsize(pPager->pWal);
41499
41500  /* If the database size was not available from the WAL sub-system,
41501  ** determine it based on the size of the database file. If the size
41502  ** of the database file is not an integer multiple of the page-size,
41503  ** round down to the nearest page. Except, any file larger than 0
41504  ** bytes in size is considered to contain at least one page.
41505  */
41506  if( nPage==0 ){
41507    i64 n = 0;                    /* Size of db file in bytes */
41508    assert( isOpen(pPager->fd) || pPager->tempFile );
41509    if( isOpen(pPager->fd) ){
41510      int rc = sqlite3OsFileSize(pPager->fd, &n);
41511      if( rc!=SQLITE_OK ){
41512        return rc;
41513      }
41514    }
41515    nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
41516  }
41517
41518  /* If the current number of pages in the file is greater than the
41519  ** configured maximum pager number, increase the allowed limit so
41520  ** that the file can be read.
41521  */
41522  if( nPage>pPager->mxPgno ){
41523    pPager->mxPgno = (Pgno)nPage;
41524  }
41525
41526  *pnPage = nPage;
41527  return SQLITE_OK;
41528}
41529
41530#ifndef SQLITE_OMIT_WAL
41531/*
41532** Check if the *-wal file that corresponds to the database opened by pPager
41533** exists if the database is not empy, or verify that the *-wal file does
41534** not exist (by deleting it) if the database file is empty.
41535**
41536** If the database is not empty and the *-wal file exists, open the pager
41537** in WAL mode.  If the database is empty or if no *-wal file exists and
41538** if no error occurs, make sure Pager.journalMode is not set to
41539** PAGER_JOURNALMODE_WAL.
41540**
41541** Return SQLITE_OK or an error code.
41542**
41543** The caller must hold a SHARED lock on the database file to call this
41544** function. Because an EXCLUSIVE lock on the db file is required to delete
41545** a WAL on a none-empty database, this ensures there is no race condition
41546** between the xAccess() below and an xDelete() being executed by some
41547** other connection.
41548*/
41549static int pagerOpenWalIfPresent(Pager *pPager){
41550  int rc = SQLITE_OK;
41551  assert( pPager->eState==PAGER_OPEN );
41552  assert( pPager->eLock>=SHARED_LOCK );
41553
41554  if( !pPager->tempFile ){
41555    int isWal;                    /* True if WAL file exists */
41556    Pgno nPage;                   /* Size of the database file */
41557
41558    rc = pagerPagecount(pPager, &nPage);
41559    if( rc ) return rc;
41560    if( nPage==0 ){
41561      rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
41562      isWal = 0;
41563    }else{
41564      rc = sqlite3OsAccess(
41565          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
41566      );
41567    }
41568    if( rc==SQLITE_OK ){
41569      if( isWal ){
41570        testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
41571        rc = sqlite3PagerOpenWal(pPager, 0);
41572      }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
41573        pPager->journalMode = PAGER_JOURNALMODE_DELETE;
41574      }
41575    }
41576  }
41577  return rc;
41578}
41579#endif
41580
41581/*
41582** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
41583** the entire master journal file. The case pSavepoint==NULL occurs when
41584** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
41585** savepoint.
41586**
41587** When pSavepoint is not NULL (meaning a non-transaction savepoint is
41588** being rolled back), then the rollback consists of up to three stages,
41589** performed in the order specified:
41590**
41591**   * Pages are played back from the main journal starting at byte
41592**     offset PagerSavepoint.iOffset and continuing to
41593**     PagerSavepoint.iHdrOffset, or to the end of the main journal
41594**     file if PagerSavepoint.iHdrOffset is zero.
41595**
41596**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
41597**     back starting from the journal header immediately following
41598**     PagerSavepoint.iHdrOffset to the end of the main journal file.
41599**
41600**   * Pages are then played back from the sub-journal file, starting
41601**     with the PagerSavepoint.iSubRec and continuing to the end of
41602**     the journal file.
41603**
41604** Throughout the rollback process, each time a page is rolled back, the
41605** corresponding bit is set in a bitvec structure (variable pDone in the
41606** implementation below). This is used to ensure that a page is only
41607** rolled back the first time it is encountered in either journal.
41608**
41609** If pSavepoint is NULL, then pages are only played back from the main
41610** journal file. There is no need for a bitvec in this case.
41611**
41612** In either case, before playback commences the Pager.dbSize variable
41613** is reset to the value that it held at the start of the savepoint
41614** (or transaction). No page with a page-number greater than this value
41615** is played back. If one is encountered it is simply skipped.
41616*/
41617static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
41618  i64 szJ;                 /* Effective size of the main journal */
41619  i64 iHdrOff;             /* End of first segment of main-journal records */
41620  int rc = SQLITE_OK;      /* Return code */
41621  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
41622
41623  assert( pPager->eState!=PAGER_ERROR );
41624  assert( pPager->eState>=PAGER_WRITER_LOCKED );
41625
41626  /* Allocate a bitvec to use to store the set of pages rolled back */
41627  if( pSavepoint ){
41628    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
41629    if( !pDone ){
41630      return SQLITE_NOMEM;
41631    }
41632  }
41633
41634  /* Set the database size back to the value it was before the savepoint
41635  ** being reverted was opened.
41636  */
41637  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
41638  pPager->changeCountDone = pPager->tempFile;
41639
41640  if( !pSavepoint && pagerUseWal(pPager) ){
41641    return pagerRollbackWal(pPager);
41642  }
41643
41644  /* Use pPager->journalOff as the effective size of the main rollback
41645  ** journal.  The actual file might be larger than this in
41646  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
41647  ** past pPager->journalOff is off-limits to us.
41648  */
41649  szJ = pPager->journalOff;
41650  assert( pagerUseWal(pPager)==0 || szJ==0 );
41651
41652  /* Begin by rolling back records from the main journal starting at
41653  ** PagerSavepoint.iOffset and continuing to the next journal header.
41654  ** There might be records in the main journal that have a page number
41655  ** greater than the current database size (pPager->dbSize) but those
41656  ** will be skipped automatically.  Pages are added to pDone as they
41657  ** are played back.
41658  */
41659  if( pSavepoint && !pagerUseWal(pPager) ){
41660    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
41661    pPager->journalOff = pSavepoint->iOffset;
41662    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
41663      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41664    }
41665    assert( rc!=SQLITE_DONE );
41666  }else{
41667    pPager->journalOff = 0;
41668  }
41669
41670  /* Continue rolling back records out of the main journal starting at
41671  ** the first journal header seen and continuing until the effective end
41672  ** of the main journal file.  Continue to skip out-of-range pages and
41673  ** continue adding pages rolled back to pDone.
41674  */
41675  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
41676    u32 ii;            /* Loop counter */
41677    u32 nJRec = 0;     /* Number of Journal Records */
41678    u32 dummy;
41679    rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
41680    assert( rc!=SQLITE_DONE );
41681
41682    /*
41683    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
41684    ** test is related to ticket #2565.  See the discussion in the
41685    ** pager_playback() function for additional information.
41686    */
41687    if( nJRec==0
41688     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
41689    ){
41690      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
41691    }
41692    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
41693      rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41694    }
41695    assert( rc!=SQLITE_DONE );
41696  }
41697  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
41698
41699  /* Finally,  rollback pages from the sub-journal.  Page that were
41700  ** previously rolled back out of the main journal (and are hence in pDone)
41701  ** will be skipped.  Out-of-range pages are also skipped.
41702  */
41703  if( pSavepoint ){
41704    u32 ii;            /* Loop counter */
41705    i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
41706
41707    if( pagerUseWal(pPager) ){
41708      rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
41709    }
41710    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
41711      assert( offset==(i64)ii*(4+pPager->pageSize) );
41712      rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
41713    }
41714    assert( rc!=SQLITE_DONE );
41715  }
41716
41717  sqlite3BitvecDestroy(pDone);
41718  if( rc==SQLITE_OK ){
41719    pPager->journalOff = szJ;
41720  }
41721
41722  return rc;
41723}
41724
41725/*
41726** Change the maximum number of in-memory pages that are allowed.
41727*/
41728SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
41729  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
41730}
41731
41732/*
41733** Free as much memory as possible from the pager.
41734*/
41735SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
41736  sqlite3PcacheShrink(pPager->pPCache);
41737}
41738
41739/*
41740** Adjust the robustness of the database to damage due to OS crashes
41741** or power failures by changing the number of syncs()s when writing
41742** the rollback journal.  There are three levels:
41743**
41744**    OFF       sqlite3OsSync() is never called.  This is the default
41745**              for temporary and transient files.
41746**
41747**    NORMAL    The journal is synced once before writes begin on the
41748**              database.  This is normally adequate protection, but
41749**              it is theoretically possible, though very unlikely,
41750**              that an inopertune power failure could leave the journal
41751**              in a state which would cause damage to the database
41752**              when it is rolled back.
41753**
41754**    FULL      The journal is synced twice before writes begin on the
41755**              database (with some additional information - the nRec field
41756**              of the journal header - being written in between the two
41757**              syncs).  If we assume that writing a
41758**              single disk sector is atomic, then this mode provides
41759**              assurance that the journal will not be corrupted to the
41760**              point of causing damage to the database during rollback.
41761**
41762** The above is for a rollback-journal mode.  For WAL mode, OFF continues
41763** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
41764** prior to the start of checkpoint and that the database file is synced
41765** at the conclusion of the checkpoint if the entire content of the WAL
41766** was written back into the database.  But no sync operations occur for
41767** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
41768** file is synced following each commit operation, in addition to the
41769** syncs associated with NORMAL.
41770**
41771** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
41772** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
41773** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
41774** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
41775** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
41776** synchronous=FULL versus synchronous=NORMAL setting determines when
41777** the xSync primitive is called and is relevant to all platforms.
41778**
41779** Numeric values associated with these states are OFF==1, NORMAL=2,
41780** and FULL=3.
41781*/
41782#ifndef SQLITE_OMIT_PAGER_PRAGMAS
41783SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
41784  Pager *pPager,        /* The pager to set safety level for */
41785  int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
41786  int bFullFsync,       /* PRAGMA fullfsync */
41787  int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
41788){
41789  assert( level>=1 && level<=3 );
41790  pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
41791  pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
41792  if( pPager->noSync ){
41793    pPager->syncFlags = 0;
41794    pPager->ckptSyncFlags = 0;
41795  }else if( bFullFsync ){
41796    pPager->syncFlags = SQLITE_SYNC_FULL;
41797    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41798  }else if( bCkptFullFsync ){
41799    pPager->syncFlags = SQLITE_SYNC_NORMAL;
41800    pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41801  }else{
41802    pPager->syncFlags = SQLITE_SYNC_NORMAL;
41803    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
41804  }
41805  pPager->walSyncFlags = pPager->syncFlags;
41806  if( pPager->fullSync ){
41807    pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
41808  }
41809}
41810#endif
41811
41812/*
41813** The following global variable is incremented whenever the library
41814** attempts to open a temporary file.  This information is used for
41815** testing and analysis only.
41816*/
41817#ifdef SQLITE_TEST
41818SQLITE_API int sqlite3_opentemp_count = 0;
41819#endif
41820
41821/*
41822** Open a temporary file.
41823**
41824** Write the file descriptor into *pFile. Return SQLITE_OK on success
41825** or some other error code if we fail. The OS will automatically
41826** delete the temporary file when it is closed.
41827**
41828** The flags passed to the VFS layer xOpen() call are those specified
41829** by parameter vfsFlags ORed with the following:
41830**
41831**     SQLITE_OPEN_READWRITE
41832**     SQLITE_OPEN_CREATE
41833**     SQLITE_OPEN_EXCLUSIVE
41834**     SQLITE_OPEN_DELETEONCLOSE
41835*/
41836static int pagerOpentemp(
41837  Pager *pPager,        /* The pager object */
41838  sqlite3_file *pFile,  /* Write the file descriptor here */
41839  int vfsFlags          /* Flags passed through to the VFS */
41840){
41841  int rc;               /* Return code */
41842
41843#ifdef SQLITE_TEST
41844  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
41845#endif
41846
41847  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
41848            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
41849  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
41850  assert( rc!=SQLITE_OK || isOpen(pFile) );
41851  return rc;
41852}
41853
41854/*
41855** Set the busy handler function.
41856**
41857** The pager invokes the busy-handler if sqlite3OsLock() returns
41858** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
41859** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
41860** lock. It does *not* invoke the busy handler when upgrading from
41861** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
41862** (which occurs during hot-journal rollback). Summary:
41863**
41864**   Transition                        | Invokes xBusyHandler
41865**   --------------------------------------------------------
41866**   NO_LOCK       -> SHARED_LOCK      | Yes
41867**   SHARED_LOCK   -> RESERVED_LOCK    | No
41868**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
41869**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
41870**
41871** If the busy-handler callback returns non-zero, the lock is
41872** retried. If it returns zero, then the SQLITE_BUSY error is
41873** returned to the caller of the pager API function.
41874*/
41875SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
41876  Pager *pPager,                       /* Pager object */
41877  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
41878  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
41879){
41880  pPager->xBusyHandler = xBusyHandler;
41881  pPager->pBusyHandlerArg = pBusyHandlerArg;
41882}
41883
41884/*
41885** Change the page size used by the Pager object. The new page size
41886** is passed in *pPageSize.
41887**
41888** If the pager is in the error state when this function is called, it
41889** is a no-op. The value returned is the error state error code (i.e.
41890** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
41891**
41892** Otherwise, if all of the following are true:
41893**
41894**   * the new page size (value of *pPageSize) is valid (a power
41895**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
41896**
41897**   * there are no outstanding page references, and
41898**
41899**   * the database is either not an in-memory database or it is
41900**     an in-memory database that currently consists of zero pages.
41901**
41902** then the pager object page size is set to *pPageSize.
41903**
41904** If the page size is changed, then this function uses sqlite3PagerMalloc()
41905** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
41906** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
41907** In all other cases, SQLITE_OK is returned.
41908**
41909** If the page size is not changed, either because one of the enumerated
41910** conditions above is not true, the pager was in error state when this
41911** function was called, or because the memory allocation attempt failed,
41912** then *pPageSize is set to the old, retained page size before returning.
41913*/
41914SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
41915  int rc = SQLITE_OK;
41916
41917  /* It is not possible to do a full assert_pager_state() here, as this
41918  ** function may be called from within PagerOpen(), before the state
41919  ** of the Pager object is internally consistent.
41920  **
41921  ** At one point this function returned an error if the pager was in
41922  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
41923  ** there is at least one outstanding page reference, this function
41924  ** is a no-op for that case anyhow.
41925  */
41926
41927  u32 pageSize = *pPageSize;
41928  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
41929  if( (pPager->memDb==0 || pPager->dbSize==0)
41930   && sqlite3PcacheRefCount(pPager->pPCache)==0
41931   && pageSize && pageSize!=(u32)pPager->pageSize
41932  ){
41933    char *pNew = NULL;             /* New temp space */
41934    i64 nByte = 0;
41935
41936    if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
41937      rc = sqlite3OsFileSize(pPager->fd, &nByte);
41938    }
41939    if( rc==SQLITE_OK ){
41940      pNew = (char *)sqlite3PageMalloc(pageSize);
41941      if( !pNew ) rc = SQLITE_NOMEM;
41942    }
41943
41944    if( rc==SQLITE_OK ){
41945      pager_reset(pPager);
41946      pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
41947      pPager->pageSize = pageSize;
41948      sqlite3PageFree(pPager->pTmpSpace);
41949      pPager->pTmpSpace = pNew;
41950      sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
41951    }
41952  }
41953
41954  *pPageSize = pPager->pageSize;
41955  if( rc==SQLITE_OK ){
41956    if( nReserve<0 ) nReserve = pPager->nReserve;
41957    assert( nReserve>=0 && nReserve<1000 );
41958    pPager->nReserve = (i16)nReserve;
41959    pagerReportSize(pPager);
41960  }
41961  return rc;
41962}
41963
41964/*
41965** Return a pointer to the "temporary page" buffer held internally
41966** by the pager.  This is a buffer that is big enough to hold the
41967** entire content of a database page.  This buffer is used internally
41968** during rollback and will be overwritten whenever a rollback
41969** occurs.  But other modules are free to use it too, as long as
41970** no rollbacks are happening.
41971*/
41972SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
41973  return pPager->pTmpSpace;
41974}
41975
41976/*
41977** Attempt to set the maximum database page count if mxPage is positive.
41978** Make no changes if mxPage is zero or negative.  And never reduce the
41979** maximum page count below the current size of the database.
41980**
41981** Regardless of mxPage, return the current maximum page count.
41982*/
41983SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
41984  if( mxPage>0 ){
41985    pPager->mxPgno = mxPage;
41986  }
41987  assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
41988  assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
41989  return pPager->mxPgno;
41990}
41991
41992/*
41993** The following set of routines are used to disable the simulated
41994** I/O error mechanism.  These routines are used to avoid simulated
41995** errors in places where we do not care about errors.
41996**
41997** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
41998** and generate no code.
41999*/
42000#ifdef SQLITE_TEST
42001SQLITE_API extern int sqlite3_io_error_pending;
42002SQLITE_API extern int sqlite3_io_error_hit;
42003static int saved_cnt;
42004void disable_simulated_io_errors(void){
42005  saved_cnt = sqlite3_io_error_pending;
42006  sqlite3_io_error_pending = -1;
42007}
42008void enable_simulated_io_errors(void){
42009  sqlite3_io_error_pending = saved_cnt;
42010}
42011#else
42012# define disable_simulated_io_errors()
42013# define enable_simulated_io_errors()
42014#endif
42015
42016/*
42017** Read the first N bytes from the beginning of the file into memory
42018** that pDest points to.
42019**
42020** If the pager was opened on a transient file (zFilename==""), or
42021** opened on a file less than N bytes in size, the output buffer is
42022** zeroed and SQLITE_OK returned. The rationale for this is that this
42023** function is used to read database headers, and a new transient or
42024** zero sized database has a header than consists entirely of zeroes.
42025**
42026** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
42027** the error code is returned to the caller and the contents of the
42028** output buffer undefined.
42029*/
42030SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
42031  int rc = SQLITE_OK;
42032  memset(pDest, 0, N);
42033  assert( isOpen(pPager->fd) || pPager->tempFile );
42034
42035  /* This routine is only called by btree immediately after creating
42036  ** the Pager object.  There has not been an opportunity to transition
42037  ** to WAL mode yet.
42038  */
42039  assert( !pagerUseWal(pPager) );
42040
42041  if( isOpen(pPager->fd) ){
42042    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
42043    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
42044    if( rc==SQLITE_IOERR_SHORT_READ ){
42045      rc = SQLITE_OK;
42046    }
42047  }
42048  return rc;
42049}
42050
42051/*
42052** This function may only be called when a read-transaction is open on
42053** the pager. It returns the total number of pages in the database.
42054**
42055** However, if the file is between 1 and <page-size> bytes in size, then
42056** this is considered a 1 page file.
42057*/
42058SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
42059  assert( pPager->eState>=PAGER_READER );
42060  assert( pPager->eState!=PAGER_WRITER_FINISHED );
42061  *pnPage = (int)pPager->dbSize;
42062}
42063
42064
42065/*
42066** Try to obtain a lock of type locktype on the database file. If
42067** a similar or greater lock is already held, this function is a no-op
42068** (returning SQLITE_OK immediately).
42069**
42070** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
42071** the busy callback if the lock is currently not available. Repeat
42072** until the busy callback returns false or until the attempt to
42073** obtain the lock succeeds.
42074**
42075** Return SQLITE_OK on success and an error code if we cannot obtain
42076** the lock. If the lock is obtained successfully, set the Pager.state
42077** variable to locktype before returning.
42078*/
42079static int pager_wait_on_lock(Pager *pPager, int locktype){
42080  int rc;                              /* Return code */
42081
42082  /* Check that this is either a no-op (because the requested lock is
42083  ** already held, or one of the transistions that the busy-handler
42084  ** may be invoked during, according to the comment above
42085  ** sqlite3PagerSetBusyhandler().
42086  */
42087  assert( (pPager->eLock>=locktype)
42088       || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
42089       || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
42090  );
42091
42092  do {
42093    rc = pagerLockDb(pPager, locktype);
42094  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
42095  return rc;
42096}
42097
42098/*
42099** Function assertTruncateConstraint(pPager) checks that one of the
42100** following is true for all dirty pages currently in the page-cache:
42101**
42102**   a) The page number is less than or equal to the size of the
42103**      current database image, in pages, OR
42104**
42105**   b) if the page content were written at this time, it would not
42106**      be necessary to write the current content out to the sub-journal
42107**      (as determined by function subjRequiresPage()).
42108**
42109** If the condition asserted by this function were not true, and the
42110** dirty page were to be discarded from the cache via the pagerStress()
42111** routine, pagerStress() would not write the current page content to
42112** the database file. If a savepoint transaction were rolled back after
42113** this happened, the correct behaviour would be to restore the current
42114** content of the page. However, since this content is not present in either
42115** the database file or the portion of the rollback journal and
42116** sub-journal rolled back the content could not be restored and the
42117** database image would become corrupt. It is therefore fortunate that
42118** this circumstance cannot arise.
42119*/
42120#if defined(SQLITE_DEBUG)
42121static void assertTruncateConstraintCb(PgHdr *pPg){
42122  assert( pPg->flags&PGHDR_DIRTY );
42123  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
42124}
42125static void assertTruncateConstraint(Pager *pPager){
42126  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
42127}
42128#else
42129# define assertTruncateConstraint(pPager)
42130#endif
42131
42132/*
42133** Truncate the in-memory database file image to nPage pages. This
42134** function does not actually modify the database file on disk. It
42135** just sets the internal state of the pager object so that the
42136** truncation will be done when the current transaction is committed.
42137*/
42138SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
42139  assert( pPager->dbSize>=nPage );
42140  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42141  pPager->dbSize = nPage;
42142  assertTruncateConstraint(pPager);
42143}
42144
42145
42146/*
42147** This function is called before attempting a hot-journal rollback. It
42148** syncs the journal file to disk, then sets pPager->journalHdr to the
42149** size of the journal file so that the pager_playback() routine knows
42150** that the entire journal file has been synced.
42151**
42152** Syncing a hot-journal to disk before attempting to roll it back ensures
42153** that if a power-failure occurs during the rollback, the process that
42154** attempts rollback following system recovery sees the same journal
42155** content as this process.
42156**
42157** If everything goes as planned, SQLITE_OK is returned. Otherwise,
42158** an SQLite error code.
42159*/
42160static int pagerSyncHotJournal(Pager *pPager){
42161  int rc = SQLITE_OK;
42162  if( !pPager->noSync ){
42163    rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
42164  }
42165  if( rc==SQLITE_OK ){
42166    rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
42167  }
42168  return rc;
42169}
42170
42171/*
42172** Shutdown the page cache.  Free all memory and close all files.
42173**
42174** If a transaction was in progress when this routine is called, that
42175** transaction is rolled back.  All outstanding pages are invalidated
42176** and their memory is freed.  Any attempt to use a page associated
42177** with this page cache after this function returns will likely
42178** result in a coredump.
42179**
42180** This function always succeeds. If a transaction is active an attempt
42181** is made to roll it back. If an error occurs during the rollback
42182** a hot journal may be left in the filesystem but no error is returned
42183** to the caller.
42184*/
42185SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
42186  u8 *pTmp = (u8 *)pPager->pTmpSpace;
42187
42188  assert( assert_pager_state(pPager) );
42189  disable_simulated_io_errors();
42190  sqlite3BeginBenignMalloc();
42191  /* pPager->errCode = 0; */
42192  pPager->exclusiveMode = 0;
42193#ifndef SQLITE_OMIT_WAL
42194  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
42195  pPager->pWal = 0;
42196#endif
42197  pager_reset(pPager);
42198  if( MEMDB ){
42199    pager_unlock(pPager);
42200  }else{
42201    /* If it is open, sync the journal file before calling UnlockAndRollback.
42202    ** If this is not done, then an unsynced portion of the open journal
42203    ** file may be played back into the database. If a power failure occurs
42204    ** while this is happening, the database could become corrupt.
42205    **
42206    ** If an error occurs while trying to sync the journal, shift the pager
42207    ** into the ERROR state. This causes UnlockAndRollback to unlock the
42208    ** database and close the journal file without attempting to roll it
42209    ** back or finalize it. The next database user will have to do hot-journal
42210    ** rollback before accessing the database file.
42211    */
42212    if( isOpen(pPager->jfd) ){
42213      pager_error(pPager, pagerSyncHotJournal(pPager));
42214    }
42215    pagerUnlockAndRollback(pPager);
42216  }
42217  sqlite3EndBenignMalloc();
42218  enable_simulated_io_errors();
42219  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
42220  IOTRACE(("CLOSE %p\n", pPager))
42221  sqlite3OsClose(pPager->jfd);
42222  sqlite3OsClose(pPager->fd);
42223  sqlite3PageFree(pTmp);
42224  sqlite3PcacheClose(pPager->pPCache);
42225
42226#ifdef SQLITE_HAS_CODEC
42227  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42228#endif
42229
42230  assert( !pPager->aSavepoint && !pPager->pInJournal );
42231  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
42232
42233  sqlite3_free(pPager);
42234  return SQLITE_OK;
42235}
42236
42237#if !defined(NDEBUG) || defined(SQLITE_TEST)
42238/*
42239** Return the page number for page pPg.
42240*/
42241SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
42242  return pPg->pgno;
42243}
42244#endif
42245
42246/*
42247** Increment the reference count for page pPg.
42248*/
42249SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
42250  sqlite3PcacheRef(pPg);
42251}
42252
42253/*
42254** Sync the journal. In other words, make sure all the pages that have
42255** been written to the journal have actually reached the surface of the
42256** disk and can be restored in the event of a hot-journal rollback.
42257**
42258** If the Pager.noSync flag is set, then this function is a no-op.
42259** Otherwise, the actions required depend on the journal-mode and the
42260** device characteristics of the the file-system, as follows:
42261**
42262**   * If the journal file is an in-memory journal file, no action need
42263**     be taken.
42264**
42265**   * Otherwise, if the device does not support the SAFE_APPEND property,
42266**     then the nRec field of the most recently written journal header
42267**     is updated to contain the number of journal records that have
42268**     been written following it. If the pager is operating in full-sync
42269**     mode, then the journal file is synced before this field is updated.
42270**
42271**   * If the device does not support the SEQUENTIAL property, then
42272**     journal file is synced.
42273**
42274** Or, in pseudo-code:
42275**
42276**   if( NOT <in-memory journal> ){
42277**     if( NOT SAFE_APPEND ){
42278**       if( <full-sync mode> ) xSync(<journal file>);
42279**       <update nRec field>
42280**     }
42281**     if( NOT SEQUENTIAL ) xSync(<journal file>);
42282**   }
42283**
42284** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
42285** page currently held in memory before returning SQLITE_OK. If an IO
42286** error is encountered, then the IO error code is returned to the caller.
42287*/
42288static int syncJournal(Pager *pPager, int newHdr){
42289  int rc;                         /* Return code */
42290
42291  assert( pPager->eState==PAGER_WRITER_CACHEMOD
42292       || pPager->eState==PAGER_WRITER_DBMOD
42293  );
42294  assert( assert_pager_state(pPager) );
42295  assert( !pagerUseWal(pPager) );
42296
42297  rc = sqlite3PagerExclusiveLock(pPager);
42298  if( rc!=SQLITE_OK ) return rc;
42299
42300  if( !pPager->noSync ){
42301    assert( !pPager->tempFile );
42302    if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
42303      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
42304      assert( isOpen(pPager->jfd) );
42305
42306      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42307        /* This block deals with an obscure problem. If the last connection
42308        ** that wrote to this database was operating in persistent-journal
42309        ** mode, then the journal file may at this point actually be larger
42310        ** than Pager.journalOff bytes. If the next thing in the journal
42311        ** file happens to be a journal-header (written as part of the
42312        ** previous connection's transaction), and a crash or power-failure
42313        ** occurs after nRec is updated but before this connection writes
42314        ** anything else to the journal file (or commits/rolls back its
42315        ** transaction), then SQLite may become confused when doing the
42316        ** hot-journal rollback following recovery. It may roll back all
42317        ** of this connections data, then proceed to rolling back the old,
42318        ** out-of-date data that follows it. Database corruption.
42319        **
42320        ** To work around this, if the journal file does appear to contain
42321        ** a valid header following Pager.journalOff, then write a 0x00
42322        ** byte to the start of it to prevent it from being recognized.
42323        **
42324        ** Variable iNextHdrOffset is set to the offset at which this
42325        ** problematic header will occur, if it exists. aMagic is used
42326        ** as a temporary buffer to inspect the first couple of bytes of
42327        ** the potential journal header.
42328        */
42329        i64 iNextHdrOffset;
42330        u8 aMagic[8];
42331        u8 zHeader[sizeof(aJournalMagic)+4];
42332
42333        memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42334        put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
42335
42336        iNextHdrOffset = journalHdrOffset(pPager);
42337        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
42338        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
42339          static const u8 zerobyte = 0;
42340          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
42341        }
42342        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
42343          return rc;
42344        }
42345
42346        /* Write the nRec value into the journal file header. If in
42347        ** full-synchronous mode, sync the journal first. This ensures that
42348        ** all data has really hit the disk before nRec is updated to mark
42349        ** it as a candidate for rollback.
42350        **
42351        ** This is not required if the persistent media supports the
42352        ** SAFE_APPEND property. Because in this case it is not possible
42353        ** for garbage data to be appended to the file, the nRec field
42354        ** is populated with 0xFFFFFFFF when the journal header is written
42355        ** and never needs to be updated.
42356        */
42357        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42358          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42359          IOTRACE(("JSYNC %p\n", pPager))
42360          rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
42361          if( rc!=SQLITE_OK ) return rc;
42362        }
42363        IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
42364        rc = sqlite3OsWrite(
42365            pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
42366        );
42367        if( rc!=SQLITE_OK ) return rc;
42368      }
42369      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42370        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42371        IOTRACE(("JSYNC %p\n", pPager))
42372        rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
42373          (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
42374        );
42375        if( rc!=SQLITE_OK ) return rc;
42376      }
42377
42378      pPager->journalHdr = pPager->journalOff;
42379      if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42380        pPager->nRec = 0;
42381        rc = writeJournalHdr(pPager);
42382        if( rc!=SQLITE_OK ) return rc;
42383      }
42384    }else{
42385      pPager->journalHdr = pPager->journalOff;
42386    }
42387  }
42388
42389  /* Unless the pager is in noSync mode, the journal file was just
42390  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
42391  ** all pages.
42392  */
42393  sqlite3PcacheClearSyncFlags(pPager->pPCache);
42394  pPager->eState = PAGER_WRITER_DBMOD;
42395  assert( assert_pager_state(pPager) );
42396  return SQLITE_OK;
42397}
42398
42399/*
42400** The argument is the first in a linked list of dirty pages connected
42401** by the PgHdr.pDirty pointer. This function writes each one of the
42402** in-memory pages in the list to the database file. The argument may
42403** be NULL, representing an empty list. In this case this function is
42404** a no-op.
42405**
42406** The pager must hold at least a RESERVED lock when this function
42407** is called. Before writing anything to the database file, this lock
42408** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
42409** SQLITE_BUSY is returned and no data is written to the database file.
42410**
42411** If the pager is a temp-file pager and the actual file-system file
42412** is not yet open, it is created and opened before any data is
42413** written out.
42414**
42415** Once the lock has been upgraded and, if necessary, the file opened,
42416** the pages are written out to the database file in list order. Writing
42417** a page is skipped if it meets either of the following criteria:
42418**
42419**   * The page number is greater than Pager.dbSize, or
42420**   * The PGHDR_DONT_WRITE flag is set on the page.
42421**
42422** If writing out a page causes the database file to grow, Pager.dbFileSize
42423** is updated accordingly. If page 1 is written out, then the value cached
42424** in Pager.dbFileVers[] is updated to match the new value stored in
42425** the database file.
42426**
42427** If everything is successful, SQLITE_OK is returned. If an IO error
42428** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
42429** be obtained, SQLITE_BUSY is returned.
42430*/
42431static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
42432  int rc = SQLITE_OK;                  /* Return code */
42433
42434  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
42435  assert( !pagerUseWal(pPager) );
42436  assert( pPager->eState==PAGER_WRITER_DBMOD );
42437  assert( pPager->eLock==EXCLUSIVE_LOCK );
42438
42439  /* If the file is a temp-file has not yet been opened, open it now. It
42440  ** is not possible for rc to be other than SQLITE_OK if this branch
42441  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
42442  */
42443  if( !isOpen(pPager->fd) ){
42444    assert( pPager->tempFile && rc==SQLITE_OK );
42445    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
42446  }
42447
42448  /* Before the first write, give the VFS a hint of what the final
42449  ** file size will be.
42450  */
42451  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
42452  if( rc==SQLITE_OK && pPager->dbSize>pPager->dbHintSize ){
42453    sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
42454    sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
42455    pPager->dbHintSize = pPager->dbSize;
42456  }
42457
42458  while( rc==SQLITE_OK && pList ){
42459    Pgno pgno = pList->pgno;
42460
42461    /* If there are dirty pages in the page cache with page numbers greater
42462    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
42463    ** make the file smaller (presumably by auto-vacuum code). Do not write
42464    ** any such pages to the file.
42465    **
42466    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
42467    ** set (set by sqlite3PagerDontWrite()).
42468    */
42469    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
42470      i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
42471      char *pData;                                   /* Data to write */
42472
42473      assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
42474      if( pList->pgno==1 ) pager_write_changecounter(pList);
42475
42476      /* Encode the database */
42477      CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
42478
42479      /* Write out the page data. */
42480      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
42481
42482      /* If page 1 was just written, update Pager.dbFileVers to match
42483      ** the value now stored in the database file. If writing this
42484      ** page caused the database file to grow, update dbFileSize.
42485      */
42486      if( pgno==1 ){
42487        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
42488      }
42489      if( pgno>pPager->dbFileSize ){
42490        pPager->dbFileSize = pgno;
42491      }
42492
42493      /* Update any backup objects copying the contents of this pager. */
42494      sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
42495
42496      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
42497                   PAGERID(pPager), pgno, pager_pagehash(pList)));
42498      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
42499      PAGER_INCR(sqlite3_pager_writedb_count);
42500      PAGER_INCR(pPager->nWrite);
42501    }else{
42502      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
42503    }
42504    pager_set_pagehash(pList);
42505    pList = pList->pDirty;
42506  }
42507
42508  return rc;
42509}
42510
42511/*
42512** Ensure that the sub-journal file is open. If it is already open, this
42513** function is a no-op.
42514**
42515** SQLITE_OK is returned if everything goes according to plan. An
42516** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
42517** fails.
42518*/
42519static int openSubJournal(Pager *pPager){
42520  int rc = SQLITE_OK;
42521  if( !isOpen(pPager->sjfd) ){
42522    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
42523      sqlite3MemJournalOpen(pPager->sjfd);
42524    }else{
42525      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
42526    }
42527  }
42528  return rc;
42529}
42530
42531/*
42532** Append a record of the current state of page pPg to the sub-journal.
42533** It is the callers responsibility to use subjRequiresPage() to check
42534** that it is really required before calling this function.
42535**
42536** If successful, set the bit corresponding to pPg->pgno in the bitvecs
42537** for all open savepoints before returning.
42538**
42539** This function returns SQLITE_OK if everything is successful, an IO
42540** error code if the attempt to write to the sub-journal fails, or
42541** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
42542** bitvec.
42543*/
42544static int subjournalPage(PgHdr *pPg){
42545  int rc = SQLITE_OK;
42546  Pager *pPager = pPg->pPager;
42547  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42548
42549    /* Open the sub-journal, if it has not already been opened */
42550    assert( pPager->useJournal );
42551    assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
42552    assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
42553    assert( pagerUseWal(pPager)
42554         || pageInJournal(pPg)
42555         || pPg->pgno>pPager->dbOrigSize
42556    );
42557    rc = openSubJournal(pPager);
42558
42559    /* If the sub-journal was opened successfully (or was already open),
42560    ** write the journal record into the file.  */
42561    if( rc==SQLITE_OK ){
42562      void *pData = pPg->pData;
42563      i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
42564      char *pData2;
42565
42566      CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42567      PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
42568      rc = write32bits(pPager->sjfd, offset, pPg->pgno);
42569      if( rc==SQLITE_OK ){
42570        rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
42571      }
42572    }
42573  }
42574  if( rc==SQLITE_OK ){
42575    pPager->nSubRec++;
42576    assert( pPager->nSavepoint>0 );
42577    rc = addToSavepointBitvecs(pPager, pPg->pgno);
42578  }
42579  return rc;
42580}
42581
42582/*
42583** This function is called by the pcache layer when it has reached some
42584** soft memory limit. The first argument is a pointer to a Pager object
42585** (cast as a void*). The pager is always 'purgeable' (not an in-memory
42586** database). The second argument is a reference to a page that is
42587** currently dirty but has no outstanding references. The page
42588** is always associated with the Pager object passed as the first
42589** argument.
42590**
42591** The job of this function is to make pPg clean by writing its contents
42592** out to the database file, if possible. This may involve syncing the
42593** journal file.
42594**
42595** If successful, sqlite3PcacheMakeClean() is called on the page and
42596** SQLITE_OK returned. If an IO error occurs while trying to make the
42597** page clean, the IO error code is returned. If the page cannot be
42598** made clean for some other reason, but no error occurs, then SQLITE_OK
42599** is returned by sqlite3PcacheMakeClean() is not called.
42600*/
42601static int pagerStress(void *p, PgHdr *pPg){
42602  Pager *pPager = (Pager *)p;
42603  int rc = SQLITE_OK;
42604
42605  assert( pPg->pPager==pPager );
42606  assert( pPg->flags&PGHDR_DIRTY );
42607
42608  /* The doNotSyncSpill flag is set during times when doing a sync of
42609  ** journal (and adding a new header) is not allowed.  This occurs
42610  ** during calls to sqlite3PagerWrite() while trying to journal multiple
42611  ** pages belonging to the same sector.
42612  **
42613  ** The doNotSpill flag inhibits all cache spilling regardless of whether
42614  ** or not a sync is required.  This is set during a rollback.
42615  **
42616  ** Spilling is also prohibited when in an error state since that could
42617  ** lead to database corruption.   In the current implementaton it
42618  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
42619  ** while in the error state, hence it is impossible for this routine to
42620  ** be called in the error state.  Nevertheless, we include a NEVER()
42621  ** test for the error state as a safeguard against future changes.
42622  */
42623  if( NEVER(pPager->errCode) ) return SQLITE_OK;
42624  if( pPager->doNotSpill ) return SQLITE_OK;
42625  if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
42626    return SQLITE_OK;
42627  }
42628
42629  pPg->pDirty = 0;
42630  if( pagerUseWal(pPager) ){
42631    /* Write a single frame for this page to the log. */
42632    if( subjRequiresPage(pPg) ){
42633      rc = subjournalPage(pPg);
42634    }
42635    if( rc==SQLITE_OK ){
42636      rc = pagerWalFrames(pPager, pPg, 0, 0);
42637    }
42638  }else{
42639
42640    /* Sync the journal file if required. */
42641    if( pPg->flags&PGHDR_NEED_SYNC
42642     || pPager->eState==PAGER_WRITER_CACHEMOD
42643    ){
42644      rc = syncJournal(pPager, 1);
42645    }
42646
42647    /* If the page number of this page is larger than the current size of
42648    ** the database image, it may need to be written to the sub-journal.
42649    ** This is because the call to pager_write_pagelist() below will not
42650    ** actually write data to the file in this case.
42651    **
42652    ** Consider the following sequence of events:
42653    **
42654    **   BEGIN;
42655    **     <journal page X>
42656    **     <modify page X>
42657    **     SAVEPOINT sp;
42658    **       <shrink database file to Y pages>
42659    **       pagerStress(page X)
42660    **     ROLLBACK TO sp;
42661    **
42662    ** If (X>Y), then when pagerStress is called page X will not be written
42663    ** out to the database file, but will be dropped from the cache. Then,
42664    ** following the "ROLLBACK TO sp" statement, reading page X will read
42665    ** data from the database file. This will be the copy of page X as it
42666    ** was when the transaction started, not as it was when "SAVEPOINT sp"
42667    ** was executed.
42668    **
42669    ** The solution is to write the current data for page X into the
42670    ** sub-journal file now (if it is not already there), so that it will
42671    ** be restored to its current value when the "ROLLBACK TO sp" is
42672    ** executed.
42673    */
42674    if( NEVER(
42675        rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
42676    ) ){
42677      rc = subjournalPage(pPg);
42678    }
42679
42680    /* Write the contents of the page out to the database file. */
42681    if( rc==SQLITE_OK ){
42682      assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
42683      rc = pager_write_pagelist(pPager, pPg);
42684    }
42685  }
42686
42687  /* Mark the page as clean. */
42688  if( rc==SQLITE_OK ){
42689    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
42690    sqlite3PcacheMakeClean(pPg);
42691  }
42692
42693  return pager_error(pPager, rc);
42694}
42695
42696
42697/*
42698** Allocate and initialize a new Pager object and put a pointer to it
42699** in *ppPager. The pager should eventually be freed by passing it
42700** to sqlite3PagerClose().
42701**
42702** The zFilename argument is the path to the database file to open.
42703** If zFilename is NULL then a randomly-named temporary file is created
42704** and used as the file to be cached. Temporary files are be deleted
42705** automatically when they are closed. If zFilename is ":memory:" then
42706** all information is held in cache. It is never written to disk.
42707** This can be used to implement an in-memory database.
42708**
42709** The nExtra parameter specifies the number of bytes of space allocated
42710** along with each page reference. This space is available to the user
42711** via the sqlite3PagerGetExtra() API.
42712**
42713** The flags argument is used to specify properties that affect the
42714** operation of the pager. It should be passed some bitwise combination
42715** of the PAGER_* flags.
42716**
42717** The vfsFlags parameter is a bitmask to pass to the flags parameter
42718** of the xOpen() method of the supplied VFS when opening files.
42719**
42720** If the pager object is allocated and the specified file opened
42721** successfully, SQLITE_OK is returned and *ppPager set to point to
42722** the new pager object. If an error occurs, *ppPager is set to NULL
42723** and error code returned. This function may return SQLITE_NOMEM
42724** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
42725** various SQLITE_IO_XXX errors.
42726*/
42727SQLITE_PRIVATE int sqlite3PagerOpen(
42728  sqlite3_vfs *pVfs,       /* The virtual file system to use */
42729  Pager **ppPager,         /* OUT: Return the Pager structure here */
42730  const char *zFilename,   /* Name of the database file to open */
42731  int nExtra,              /* Extra bytes append to each in-memory page */
42732  int flags,               /* flags controlling this file */
42733  int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
42734  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
42735){
42736  u8 *pPtr;
42737  Pager *pPager = 0;       /* Pager object to allocate and return */
42738  int rc = SQLITE_OK;      /* Return code */
42739  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
42740  int memDb = 0;           /* True if this is an in-memory file */
42741  int readOnly = 0;        /* True if this is a read-only file */
42742  int journalFileSize;     /* Bytes to allocate for each journal fd */
42743  char *zPathname = 0;     /* Full path to database file */
42744  int nPathname = 0;       /* Number of bytes in zPathname */
42745  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
42746  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
42747  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
42748  const char *zUri = 0;    /* URI args to copy */
42749  int nUri = 0;            /* Number of bytes of URI args at *zUri */
42750
42751  /* Figure out how much space is required for each journal file-handle
42752  ** (there are two of them, the main journal and the sub-journal). This
42753  ** is the maximum space required for an in-memory journal file handle
42754  ** and a regular journal file-handle. Note that a "regular journal-handle"
42755  ** may be a wrapper capable of caching the first portion of the journal
42756  ** file in memory to implement the atomic-write optimization (see
42757  ** source file journal.c).
42758  */
42759  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
42760    journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
42761  }else{
42762    journalFileSize = ROUND8(sqlite3MemJournalSize());
42763  }
42764
42765  /* Set the output variable to NULL in case an error occurs. */
42766  *ppPager = 0;
42767
42768#ifndef SQLITE_OMIT_MEMORYDB
42769  if( flags & PAGER_MEMORY ){
42770    memDb = 1;
42771    zFilename = 0;
42772  }
42773#endif
42774
42775  /* Compute and store the full pathname in an allocated buffer pointed
42776  ** to by zPathname, length nPathname. Or, if this is a temporary file,
42777  ** leave both nPathname and zPathname set to 0.
42778  */
42779  if( zFilename && zFilename[0] ){
42780    const char *z;
42781    nPathname = pVfs->mxPathname+1;
42782    zPathname = sqlite3Malloc(nPathname*2);
42783    if( zPathname==0 ){
42784      return SQLITE_NOMEM;
42785    }
42786    zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
42787    rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
42788    nPathname = sqlite3Strlen30(zPathname);
42789    z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
42790    while( *z ){
42791      z += sqlite3Strlen30(z)+1;
42792      z += sqlite3Strlen30(z)+1;
42793    }
42794    nUri = (int)(&z[1] - zUri);
42795    assert( nUri>=0 );
42796    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
42797      /* This branch is taken when the journal path required by
42798      ** the database being opened will be more than pVfs->mxPathname
42799      ** bytes in length. This means the database cannot be opened,
42800      ** as it will not be possible to open the journal file or even
42801      ** check for a hot-journal before reading.
42802      */
42803      rc = SQLITE_CANTOPEN_BKPT;
42804    }
42805    if( rc!=SQLITE_OK ){
42806      sqlite3_free(zPathname);
42807      return rc;
42808    }
42809  }
42810
42811  /* Allocate memory for the Pager structure, PCache object, the
42812  ** three file descriptors, the database file name and the journal
42813  ** file name. The layout in memory is as follows:
42814  **
42815  **     Pager object                    (sizeof(Pager) bytes)
42816  **     PCache object                   (sqlite3PcacheSize() bytes)
42817  **     Database file handle            (pVfs->szOsFile bytes)
42818  **     Sub-journal file handle         (journalFileSize bytes)
42819  **     Main journal file handle        (journalFileSize bytes)
42820  **     Database file name              (nPathname+1 bytes)
42821  **     Journal file name               (nPathname+8+1 bytes)
42822  */
42823  pPtr = (u8 *)sqlite3MallocZero(
42824    ROUND8(sizeof(*pPager)) +      /* Pager structure */
42825    ROUND8(pcacheSize) +           /* PCache object */
42826    ROUND8(pVfs->szOsFile) +       /* The main db file */
42827    journalFileSize * 2 +          /* The two journal files */
42828    nPathname + 1 + nUri +         /* zFilename */
42829    nPathname + 8 + 2              /* zJournal */
42830#ifndef SQLITE_OMIT_WAL
42831    + nPathname + 4 + 2            /* zWal */
42832#endif
42833  );
42834  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
42835  if( !pPtr ){
42836    sqlite3_free(zPathname);
42837    return SQLITE_NOMEM;
42838  }
42839  pPager =              (Pager*)(pPtr);
42840  pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
42841  pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
42842  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
42843  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
42844  pPager->zFilename =    (char*)(pPtr += journalFileSize);
42845  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
42846
42847  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
42848  if( zPathname ){
42849    assert( nPathname>0 );
42850    pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
42851    memcpy(pPager->zFilename, zPathname, nPathname);
42852    memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
42853    memcpy(pPager->zJournal, zPathname, nPathname);
42854    memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+1);
42855    sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
42856#ifndef SQLITE_OMIT_WAL
42857    pPager->zWal = &pPager->zJournal[nPathname+8+1];
42858    memcpy(pPager->zWal, zPathname, nPathname);
42859    memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
42860    sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
42861#endif
42862    sqlite3_free(zPathname);
42863  }
42864  pPager->pVfs = pVfs;
42865  pPager->vfsFlags = vfsFlags;
42866
42867  /* Open the pager file.
42868  */
42869  if( zFilename && zFilename[0] ){
42870    int fout = 0;                    /* VFS flags returned by xOpen() */
42871    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
42872    assert( !memDb );
42873    readOnly = (fout&SQLITE_OPEN_READONLY);
42874
42875    /* If the file was successfully opened for read/write access,
42876    ** choose a default page size in case we have to create the
42877    ** database file. The default page size is the maximum of:
42878    **
42879    **    + SQLITE_DEFAULT_PAGE_SIZE,
42880    **    + The value returned by sqlite3OsSectorSize()
42881    **    + The largest page size that can be written atomically.
42882    */
42883    if( rc==SQLITE_OK && !readOnly ){
42884      setSectorSize(pPager);
42885      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
42886      if( szPageDflt<pPager->sectorSize ){
42887        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
42888          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
42889        }else{
42890          szPageDflt = (u32)pPager->sectorSize;
42891        }
42892      }
42893#ifdef SQLITE_ENABLE_ATOMIC_WRITE
42894      {
42895        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
42896        int ii;
42897        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
42898        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
42899        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
42900        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
42901          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
42902            szPageDflt = ii;
42903          }
42904        }
42905      }
42906#endif
42907    }
42908  }else{
42909    /* If a temporary file is requested, it is not opened immediately.
42910    ** In this case we accept the default page size and delay actually
42911    ** opening the file until the first call to OsWrite().
42912    **
42913    ** This branch is also run for an in-memory database. An in-memory
42914    ** database is the same as a temp-file that is never written out to
42915    ** disk and uses an in-memory rollback journal.
42916    */
42917    tempFile = 1;
42918    pPager->eState = PAGER_READER;
42919    pPager->eLock = EXCLUSIVE_LOCK;
42920    readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
42921  }
42922
42923  /* The following call to PagerSetPagesize() serves to set the value of
42924  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
42925  */
42926  if( rc==SQLITE_OK ){
42927    assert( pPager->memDb==0 );
42928    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
42929    testcase( rc!=SQLITE_OK );
42930  }
42931
42932  /* If an error occurred in either of the blocks above, free the
42933  ** Pager structure and close the file.
42934  */
42935  if( rc!=SQLITE_OK ){
42936    assert( !pPager->pTmpSpace );
42937    sqlite3OsClose(pPager->fd);
42938    sqlite3_free(pPager);
42939    return rc;
42940  }
42941
42942  /* Initialize the PCache object. */
42943  assert( nExtra<1000 );
42944  nExtra = ROUND8(nExtra);
42945  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
42946                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
42947
42948  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
42949  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
42950
42951  pPager->useJournal = (u8)useJournal;
42952  /* pPager->stmtOpen = 0; */
42953  /* pPager->stmtInUse = 0; */
42954  /* pPager->nRef = 0; */
42955  /* pPager->stmtSize = 0; */
42956  /* pPager->stmtJSize = 0; */
42957  /* pPager->nPage = 0; */
42958  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
42959  /* pPager->state = PAGER_UNLOCK; */
42960#if 0
42961  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
42962#endif
42963  /* pPager->errMask = 0; */
42964  pPager->tempFile = (u8)tempFile;
42965  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
42966          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
42967  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
42968  pPager->exclusiveMode = (u8)tempFile;
42969  pPager->changeCountDone = pPager->tempFile;
42970  pPager->memDb = (u8)memDb;
42971  pPager->readOnly = (u8)readOnly;
42972  assert( useJournal || pPager->tempFile );
42973  pPager->noSync = pPager->tempFile;
42974  if( pPager->noSync ){
42975    assert( pPager->fullSync==0 );
42976    assert( pPager->syncFlags==0 );
42977    assert( pPager->walSyncFlags==0 );
42978    assert( pPager->ckptSyncFlags==0 );
42979  }else{
42980    pPager->fullSync = 1;
42981    pPager->syncFlags = SQLITE_SYNC_NORMAL;
42982    pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
42983    pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
42984  }
42985  /* pPager->pFirst = 0; */
42986  /* pPager->pFirstSynced = 0; */
42987  /* pPager->pLast = 0; */
42988  pPager->nExtra = (u16)nExtra;
42989  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
42990  assert( isOpen(pPager->fd) || tempFile );
42991  setSectorSize(pPager);
42992  if( !useJournal ){
42993    pPager->journalMode = PAGER_JOURNALMODE_OFF;
42994  }else if( memDb ){
42995    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
42996  }
42997  /* pPager->xBusyHandler = 0; */
42998  /* pPager->pBusyHandlerArg = 0; */
42999  pPager->xReiniter = xReinit;
43000  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
43001
43002  *ppPager = pPager;
43003  return SQLITE_OK;
43004}
43005
43006
43007
43008/*
43009** This function is called after transitioning from PAGER_UNLOCK to
43010** PAGER_SHARED state. It tests if there is a hot journal present in
43011** the file-system for the given pager. A hot journal is one that
43012** needs to be played back. According to this function, a hot-journal
43013** file exists if the following criteria are met:
43014**
43015**   * The journal file exists in the file system, and
43016**   * No process holds a RESERVED or greater lock on the database file, and
43017**   * The database file itself is greater than 0 bytes in size, and
43018**   * The first byte of the journal file exists and is not 0x00.
43019**
43020** If the current size of the database file is 0 but a journal file
43021** exists, that is probably an old journal left over from a prior
43022** database with the same name. In this case the journal file is
43023** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
43024** is returned.
43025**
43026** This routine does not check if there is a master journal filename
43027** at the end of the file. If there is, and that master journal file
43028** does not exist, then the journal file is not really hot. In this
43029** case this routine will return a false-positive. The pager_playback()
43030** routine will discover that the journal file is not really hot and
43031** will not roll it back.
43032**
43033** If a hot-journal file is found to exist, *pExists is set to 1 and
43034** SQLITE_OK returned. If no hot-journal file is present, *pExists is
43035** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
43036** to determine whether or not a hot-journal file exists, the IO error
43037** code is returned and the value of *pExists is undefined.
43038*/
43039static int hasHotJournal(Pager *pPager, int *pExists){
43040  sqlite3_vfs * const pVfs = pPager->pVfs;
43041  int rc = SQLITE_OK;           /* Return code */
43042  int exists = 1;               /* True if a journal file is present */
43043  int jrnlOpen = !!isOpen(pPager->jfd);
43044
43045  assert( pPager->useJournal );
43046  assert( isOpen(pPager->fd) );
43047  assert( pPager->eState==PAGER_OPEN );
43048
43049  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
43050    SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
43051  ));
43052
43053  *pExists = 0;
43054  if( !jrnlOpen ){
43055    rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
43056  }
43057  if( rc==SQLITE_OK && exists ){
43058    int locked = 0;             /* True if some process holds a RESERVED lock */
43059
43060    /* Race condition here:  Another process might have been holding the
43061    ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
43062    ** call above, but then delete the journal and drop the lock before
43063    ** we get to the following sqlite3OsCheckReservedLock() call.  If that
43064    ** is the case, this routine might think there is a hot journal when
43065    ** in fact there is none.  This results in a false-positive which will
43066    ** be dealt with by the playback routine.  Ticket #3883.
43067    */
43068    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
43069    if( rc==SQLITE_OK && !locked ){
43070      Pgno nPage;                 /* Number of pages in database file */
43071
43072      /* Check the size of the database file. If it consists of 0 pages,
43073      ** then delete the journal file. See the header comment above for
43074      ** the reasoning here.  Delete the obsolete journal file under
43075      ** a RESERVED lock to avoid race conditions and to avoid violating
43076      ** [H33020].
43077      */
43078      rc = pagerPagecount(pPager, &nPage);
43079      if( rc==SQLITE_OK ){
43080        if( nPage==0 ){
43081          sqlite3BeginBenignMalloc();
43082          if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
43083            sqlite3OsDelete(pVfs, pPager->zJournal, 0);
43084            if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
43085          }
43086          sqlite3EndBenignMalloc();
43087        }else{
43088          /* The journal file exists and no other connection has a reserved
43089          ** or greater lock on the database file. Now check that there is
43090          ** at least one non-zero bytes at the start of the journal file.
43091          ** If there is, then we consider this journal to be hot. If not,
43092          ** it can be ignored.
43093          */
43094          if( !jrnlOpen ){
43095            int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
43096            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
43097          }
43098          if( rc==SQLITE_OK ){
43099            u8 first = 0;
43100            rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
43101            if( rc==SQLITE_IOERR_SHORT_READ ){
43102              rc = SQLITE_OK;
43103            }
43104            if( !jrnlOpen ){
43105              sqlite3OsClose(pPager->jfd);
43106            }
43107            *pExists = (first!=0);
43108          }else if( rc==SQLITE_CANTOPEN ){
43109            /* If we cannot open the rollback journal file in order to see if
43110            ** its has a zero header, that might be due to an I/O error, or
43111            ** it might be due to the race condition described above and in
43112            ** ticket #3883.  Either way, assume that the journal is hot.
43113            ** This might be a false positive.  But if it is, then the
43114            ** automatic journal playback and recovery mechanism will deal
43115            ** with it under an EXCLUSIVE lock where we do not need to
43116            ** worry so much with race conditions.
43117            */
43118            *pExists = 1;
43119            rc = SQLITE_OK;
43120          }
43121        }
43122      }
43123    }
43124  }
43125
43126  return rc;
43127}
43128
43129/*
43130** This function is called to obtain a shared lock on the database file.
43131** It is illegal to call sqlite3PagerAcquire() until after this function
43132** has been successfully called. If a shared-lock is already held when
43133** this function is called, it is a no-op.
43134**
43135** The following operations are also performed by this function.
43136**
43137**   1) If the pager is currently in PAGER_OPEN state (no lock held
43138**      on the database file), then an attempt is made to obtain a
43139**      SHARED lock on the database file. Immediately after obtaining
43140**      the SHARED lock, the file-system is checked for a hot-journal,
43141**      which is played back if present. Following any hot-journal
43142**      rollback, the contents of the cache are validated by checking
43143**      the 'change-counter' field of the database file header and
43144**      discarded if they are found to be invalid.
43145**
43146**   2) If the pager is running in exclusive-mode, and there are currently
43147**      no outstanding references to any pages, and is in the error state,
43148**      then an attempt is made to clear the error state by discarding
43149**      the contents of the page cache and rolling back any open journal
43150**      file.
43151**
43152** If everything is successful, SQLITE_OK is returned. If an IO error
43153** occurs while locking the database, checking for a hot-journal file or
43154** rolling back a journal file, the IO error code is returned.
43155*/
43156SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
43157  int rc = SQLITE_OK;                /* Return code */
43158
43159  /* This routine is only called from b-tree and only when there are no
43160  ** outstanding pages. This implies that the pager state should either
43161  ** be OPEN or READER. READER is only possible if the pager is or was in
43162  ** exclusive access mode.
43163  */
43164  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
43165  assert( assert_pager_state(pPager) );
43166  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
43167  if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
43168
43169  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
43170    int bHotJournal = 1;          /* True if there exists a hot journal-file */
43171
43172    assert( !MEMDB );
43173
43174    rc = pager_wait_on_lock(pPager, SHARED_LOCK);
43175    if( rc!=SQLITE_OK ){
43176      assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
43177      goto failed;
43178    }
43179
43180    /* If a journal file exists, and there is no RESERVED lock on the
43181    ** database file, then it either needs to be played back or deleted.
43182    */
43183    if( pPager->eLock<=SHARED_LOCK ){
43184      rc = hasHotJournal(pPager, &bHotJournal);
43185    }
43186    if( rc!=SQLITE_OK ){
43187      goto failed;
43188    }
43189    if( bHotJournal ){
43190      /* Get an EXCLUSIVE lock on the database file. At this point it is
43191      ** important that a RESERVED lock is not obtained on the way to the
43192      ** EXCLUSIVE lock. If it were, another process might open the
43193      ** database file, detect the RESERVED lock, and conclude that the
43194      ** database is safe to read while this process is still rolling the
43195      ** hot-journal back.
43196      **
43197      ** Because the intermediate RESERVED lock is not requested, any
43198      ** other process attempting to access the database file will get to
43199      ** this point in the code and fail to obtain its own EXCLUSIVE lock
43200      ** on the database file.
43201      **
43202      ** Unless the pager is in locking_mode=exclusive mode, the lock is
43203      ** downgraded to SHARED_LOCK before this function returns.
43204      */
43205      rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43206      if( rc!=SQLITE_OK ){
43207        goto failed;
43208      }
43209
43210      /* If it is not already open and the file exists on disk, open the
43211      ** journal for read/write access. Write access is required because
43212      ** in exclusive-access mode the file descriptor will be kept open
43213      ** and possibly used for a transaction later on. Also, write-access
43214      ** is usually required to finalize the journal in journal_mode=persist
43215      ** mode (and also for journal_mode=truncate on some systems).
43216      **
43217      ** If the journal does not exist, it usually means that some
43218      ** other connection managed to get in and roll it back before
43219      ** this connection obtained the exclusive lock above. Or, it
43220      ** may mean that the pager was in the error-state when this
43221      ** function was called and the journal file does not exist.
43222      */
43223      if( !isOpen(pPager->jfd) ){
43224        sqlite3_vfs * const pVfs = pPager->pVfs;
43225        int bExists;              /* True if journal file exists */
43226        rc = sqlite3OsAccess(
43227            pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
43228        if( rc==SQLITE_OK && bExists ){
43229          int fout = 0;
43230          int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
43231          assert( !pPager->tempFile );
43232          rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
43233          assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43234          if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
43235            rc = SQLITE_CANTOPEN_BKPT;
43236            sqlite3OsClose(pPager->jfd);
43237          }
43238        }
43239      }
43240
43241      /* Playback and delete the journal.  Drop the database write
43242      ** lock and reacquire the read lock. Purge the cache before
43243      ** playing back the hot-journal so that we don't end up with
43244      ** an inconsistent cache.  Sync the hot journal before playing
43245      ** it back since the process that crashed and left the hot journal
43246      ** probably did not sync it and we are required to always sync
43247      ** the journal before playing it back.
43248      */
43249      if( isOpen(pPager->jfd) ){
43250        assert( rc==SQLITE_OK );
43251        rc = pagerSyncHotJournal(pPager);
43252        if( rc==SQLITE_OK ){
43253          rc = pager_playback(pPager, 1);
43254          pPager->eState = PAGER_OPEN;
43255        }
43256      }else if( !pPager->exclusiveMode ){
43257        pagerUnlockDb(pPager, SHARED_LOCK);
43258      }
43259
43260      if( rc!=SQLITE_OK ){
43261        /* This branch is taken if an error occurs while trying to open
43262        ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
43263        ** pager_unlock() routine will be called before returning to unlock
43264        ** the file. If the unlock attempt fails, then Pager.eLock must be
43265        ** set to UNKNOWN_LOCK (see the comment above the #define for
43266        ** UNKNOWN_LOCK above for an explanation).
43267        **
43268        ** In order to get pager_unlock() to do this, set Pager.eState to
43269        ** PAGER_ERROR now. This is not actually counted as a transition
43270        ** to ERROR state in the state diagram at the top of this file,
43271        ** since we know that the same call to pager_unlock() will very
43272        ** shortly transition the pager object to the OPEN state. Calling
43273        ** assert_pager_state() would fail now, as it should not be possible
43274        ** to be in ERROR state when there are zero outstanding page
43275        ** references.
43276        */
43277        pager_error(pPager, rc);
43278        goto failed;
43279      }
43280
43281      assert( pPager->eState==PAGER_OPEN );
43282      assert( (pPager->eLock==SHARED_LOCK)
43283           || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
43284      );
43285    }
43286
43287    if( !pPager->tempFile
43288     && (pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0)
43289    ){
43290      /* The shared-lock has just been acquired on the database file
43291      ** and there are already pages in the cache (from a previous
43292      ** read or write transaction).  Check to see if the database
43293      ** has been modified.  If the database has changed, flush the
43294      ** cache.
43295      **
43296      ** Database changes is detected by looking at 15 bytes beginning
43297      ** at offset 24 into the file.  The first 4 of these 16 bytes are
43298      ** a 32-bit counter that is incremented with each change.  The
43299      ** other bytes change randomly with each file change when
43300      ** a codec is in use.
43301      **
43302      ** There is a vanishingly small chance that a change will not be
43303      ** detected.  The chance of an undetected change is so small that
43304      ** it can be neglected.
43305      */
43306      Pgno nPage = 0;
43307      char dbFileVers[sizeof(pPager->dbFileVers)];
43308
43309      rc = pagerPagecount(pPager, &nPage);
43310      if( rc ) goto failed;
43311
43312      if( nPage>0 ){
43313        IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
43314        rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
43315        if( rc!=SQLITE_OK ){
43316          goto failed;
43317        }
43318      }else{
43319        memset(dbFileVers, 0, sizeof(dbFileVers));
43320      }
43321
43322      if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
43323        pager_reset(pPager);
43324      }
43325    }
43326
43327    /* If there is a WAL file in the file-system, open this database in WAL
43328    ** mode. Otherwise, the following function call is a no-op.
43329    */
43330    rc = pagerOpenWalIfPresent(pPager);
43331#ifndef SQLITE_OMIT_WAL
43332    assert( pPager->pWal==0 || rc==SQLITE_OK );
43333#endif
43334  }
43335
43336  if( pagerUseWal(pPager) ){
43337    assert( rc==SQLITE_OK );
43338    rc = pagerBeginReadTransaction(pPager);
43339  }
43340
43341  if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
43342    rc = pagerPagecount(pPager, &pPager->dbSize);
43343  }
43344
43345 failed:
43346  if( rc!=SQLITE_OK ){
43347    assert( !MEMDB );
43348    pager_unlock(pPager);
43349    assert( pPager->eState==PAGER_OPEN );
43350  }else{
43351    pPager->eState = PAGER_READER;
43352  }
43353  return rc;
43354}
43355
43356/*
43357** If the reference count has reached zero, rollback any active
43358** transaction and unlock the pager.
43359**
43360** Except, in locking_mode=EXCLUSIVE when there is nothing to in
43361** the rollback journal, the unlock is not performed and there is
43362** nothing to rollback, so this routine is a no-op.
43363*/
43364static void pagerUnlockIfUnused(Pager *pPager){
43365  if( (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
43366    pagerUnlockAndRollback(pPager);
43367  }
43368}
43369
43370/*
43371** Acquire a reference to page number pgno in pager pPager (a page
43372** reference has type DbPage*). If the requested reference is
43373** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
43374**
43375** If the requested page is already in the cache, it is returned.
43376** Otherwise, a new page object is allocated and populated with data
43377** read from the database file. In some cases, the pcache module may
43378** choose not to allocate a new page object and may reuse an existing
43379** object with no outstanding references.
43380**
43381** The extra data appended to a page is always initialized to zeros the
43382** first time a page is loaded into memory. If the page requested is
43383** already in the cache when this function is called, then the extra
43384** data is left as it was when the page object was last used.
43385**
43386** If the database image is smaller than the requested page or if a
43387** non-zero value is passed as the noContent parameter and the
43388** requested page is not already stored in the cache, then no
43389** actual disk read occurs. In this case the memory image of the
43390** page is initialized to all zeros.
43391**
43392** If noContent is true, it means that we do not care about the contents
43393** of the page. This occurs in two seperate scenarios:
43394**
43395**   a) When reading a free-list leaf page from the database, and
43396**
43397**   b) When a savepoint is being rolled back and we need to load
43398**      a new page into the cache to be filled with the data read
43399**      from the savepoint journal.
43400**
43401** If noContent is true, then the data returned is zeroed instead of
43402** being read from the database. Additionally, the bits corresponding
43403** to pgno in Pager.pInJournal (bitvec of pages already written to the
43404** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
43405** savepoints are set. This means if the page is made writable at any
43406** point in the future, using a call to sqlite3PagerWrite(), its contents
43407** will not be journaled. This saves IO.
43408**
43409** The acquisition might fail for several reasons.  In all cases,
43410** an appropriate error code is returned and *ppPage is set to NULL.
43411**
43412** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
43413** to find a page in the in-memory cache first.  If the page is not already
43414** in memory, this routine goes to disk to read it in whereas Lookup()
43415** just returns 0.  This routine acquires a read-lock the first time it
43416** has to go to disk, and could also playback an old journal if necessary.
43417** Since Lookup() never goes to disk, it never has to deal with locks
43418** or journal files.
43419*/
43420SQLITE_PRIVATE int sqlite3PagerAcquire(
43421  Pager *pPager,      /* The pager open on the database file */
43422  Pgno pgno,          /* Page number to fetch */
43423  DbPage **ppPage,    /* Write a pointer to the page here */
43424  int noContent       /* Do not bother reading content from disk if true */
43425){
43426  int rc;
43427  PgHdr *pPg;
43428
43429  assert( pPager->eState>=PAGER_READER );
43430  assert( assert_pager_state(pPager) );
43431
43432  if( pgno==0 ){
43433    return SQLITE_CORRUPT_BKPT;
43434  }
43435
43436  /* If the pager is in the error state, return an error immediately.
43437  ** Otherwise, request the page from the PCache layer. */
43438  if( pPager->errCode!=SQLITE_OK ){
43439    rc = pPager->errCode;
43440  }else{
43441    rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
43442  }
43443
43444  if( rc!=SQLITE_OK ){
43445    /* Either the call to sqlite3PcacheFetch() returned an error or the
43446    ** pager was already in the error-state when this function was called.
43447    ** Set pPg to 0 and jump to the exception handler.  */
43448    pPg = 0;
43449    goto pager_acquire_err;
43450  }
43451  assert( (*ppPage)->pgno==pgno );
43452  assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
43453
43454  if( (*ppPage)->pPager && !noContent ){
43455    /* In this case the pcache already contains an initialized copy of
43456    ** the page. Return without further ado.  */
43457    assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
43458    pPager->nHit++;
43459    return SQLITE_OK;
43460
43461  }else{
43462    /* The pager cache has created a new page. Its content needs to
43463    ** be initialized.  */
43464
43465    pPg = *ppPage;
43466    pPg->pPager = pPager;
43467
43468    /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
43469    ** number greater than this, or the unused locking-page, is requested. */
43470    if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
43471      rc = SQLITE_CORRUPT_BKPT;
43472      goto pager_acquire_err;
43473    }
43474
43475    if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
43476      if( pgno>pPager->mxPgno ){
43477        rc = SQLITE_FULL;
43478        goto pager_acquire_err;
43479      }
43480      if( noContent ){
43481        /* Failure to set the bits in the InJournal bit-vectors is benign.
43482        ** It merely means that we might do some extra work to journal a
43483        ** page that does not need to be journaled.  Nevertheless, be sure
43484        ** to test the case where a malloc error occurs while trying to set
43485        ** a bit in a bit vector.
43486        */
43487        sqlite3BeginBenignMalloc();
43488        if( pgno<=pPager->dbOrigSize ){
43489          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
43490          testcase( rc==SQLITE_NOMEM );
43491        }
43492        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
43493        testcase( rc==SQLITE_NOMEM );
43494        sqlite3EndBenignMalloc();
43495      }
43496      memset(pPg->pData, 0, pPager->pageSize);
43497      IOTRACE(("ZERO %p %d\n", pPager, pgno));
43498    }else{
43499      assert( pPg->pPager==pPager );
43500      pPager->nMiss++;
43501      rc = readDbPage(pPg);
43502      if( rc!=SQLITE_OK ){
43503        goto pager_acquire_err;
43504      }
43505    }
43506    pager_set_pagehash(pPg);
43507  }
43508
43509  return SQLITE_OK;
43510
43511pager_acquire_err:
43512  assert( rc!=SQLITE_OK );
43513  if( pPg ){
43514    sqlite3PcacheDrop(pPg);
43515  }
43516  pagerUnlockIfUnused(pPager);
43517
43518  *ppPage = 0;
43519  return rc;
43520}
43521
43522/*
43523** Acquire a page if it is already in the in-memory cache.  Do
43524** not read the page from disk.  Return a pointer to the page,
43525** or 0 if the page is not in cache.
43526**
43527** See also sqlite3PagerGet().  The difference between this routine
43528** and sqlite3PagerGet() is that _get() will go to the disk and read
43529** in the page if the page is not already in cache.  This routine
43530** returns NULL if the page is not in cache or if a disk I/O error
43531** has ever happened.
43532*/
43533SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
43534  PgHdr *pPg = 0;
43535  assert( pPager!=0 );
43536  assert( pgno!=0 );
43537  assert( pPager->pPCache!=0 );
43538  assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
43539  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
43540  return pPg;
43541}
43542
43543/*
43544** Release a page reference.
43545**
43546** If the number of references to the page drop to zero, then the
43547** page is added to the LRU list.  When all references to all pages
43548** are released, a rollback occurs and the lock on the database is
43549** removed.
43550*/
43551SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
43552  if( pPg ){
43553    Pager *pPager = pPg->pPager;
43554    sqlite3PcacheRelease(pPg);
43555    pagerUnlockIfUnused(pPager);
43556  }
43557}
43558
43559/*
43560** This function is called at the start of every write transaction.
43561** There must already be a RESERVED or EXCLUSIVE lock on the database
43562** file when this routine is called.
43563**
43564** Open the journal file for pager pPager and write a journal header
43565** to the start of it. If there are active savepoints, open the sub-journal
43566** as well. This function is only used when the journal file is being
43567** opened to write a rollback log for a transaction. It is not used
43568** when opening a hot journal file to roll it back.
43569**
43570** If the journal file is already open (as it may be in exclusive mode),
43571** then this function just writes a journal header to the start of the
43572** already open file.
43573**
43574** Whether or not the journal file is opened by this function, the
43575** Pager.pInJournal bitvec structure is allocated.
43576**
43577** Return SQLITE_OK if everything is successful. Otherwise, return
43578** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
43579** an IO error code if opening or writing the journal file fails.
43580*/
43581static int pager_open_journal(Pager *pPager){
43582  int rc = SQLITE_OK;                        /* Return code */
43583  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
43584
43585  assert( pPager->eState==PAGER_WRITER_LOCKED );
43586  assert( assert_pager_state(pPager) );
43587  assert( pPager->pInJournal==0 );
43588
43589  /* If already in the error state, this function is a no-op.  But on
43590  ** the other hand, this routine is never called if we are already in
43591  ** an error state. */
43592  if( NEVER(pPager->errCode) ) return pPager->errCode;
43593
43594  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43595    pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
43596    if( pPager->pInJournal==0 ){
43597      return SQLITE_NOMEM;
43598    }
43599
43600    /* Open the journal file if it is not already open. */
43601    if( !isOpen(pPager->jfd) ){
43602      if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
43603        sqlite3MemJournalOpen(pPager->jfd);
43604      }else{
43605        const int flags =                   /* VFS flags to open journal file */
43606          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
43607          (pPager->tempFile ?
43608            (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
43609            (SQLITE_OPEN_MAIN_JOURNAL)
43610          );
43611  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43612        rc = sqlite3JournalOpen(
43613            pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
43614        );
43615  #else
43616        rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
43617  #endif
43618      }
43619      assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43620    }
43621
43622
43623    /* Write the first journal header to the journal file and open
43624    ** the sub-journal if necessary.
43625    */
43626    if( rc==SQLITE_OK ){
43627      /* TODO: Check if all of these are really required. */
43628      pPager->nRec = 0;
43629      pPager->journalOff = 0;
43630      pPager->setMaster = 0;
43631      pPager->journalHdr = 0;
43632      rc = writeJournalHdr(pPager);
43633    }
43634  }
43635
43636  if( rc!=SQLITE_OK ){
43637    sqlite3BitvecDestroy(pPager->pInJournal);
43638    pPager->pInJournal = 0;
43639  }else{
43640    assert( pPager->eState==PAGER_WRITER_LOCKED );
43641    pPager->eState = PAGER_WRITER_CACHEMOD;
43642  }
43643
43644  return rc;
43645}
43646
43647/*
43648** Begin a write-transaction on the specified pager object. If a
43649** write-transaction has already been opened, this function is a no-op.
43650**
43651** If the exFlag argument is false, then acquire at least a RESERVED
43652** lock on the database file. If exFlag is true, then acquire at least
43653** an EXCLUSIVE lock. If such a lock is already held, no locking
43654** functions need be called.
43655**
43656** If the subjInMemory argument is non-zero, then any sub-journal opened
43657** within this transaction will be opened as an in-memory file. This
43658** has no effect if the sub-journal is already opened (as it may be when
43659** running in exclusive mode) or if the transaction does not require a
43660** sub-journal. If the subjInMemory argument is zero, then any required
43661** sub-journal is implemented in-memory if pPager is an in-memory database,
43662** or using a temporary file otherwise.
43663*/
43664SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
43665  int rc = SQLITE_OK;
43666
43667  if( pPager->errCode ) return pPager->errCode;
43668  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
43669  pPager->subjInMemory = (u8)subjInMemory;
43670
43671  if( ALWAYS(pPager->eState==PAGER_READER) ){
43672    assert( pPager->pInJournal==0 );
43673
43674    if( pagerUseWal(pPager) ){
43675      /* If the pager is configured to use locking_mode=exclusive, and an
43676      ** exclusive lock on the database is not already held, obtain it now.
43677      */
43678      if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
43679        rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43680        if( rc!=SQLITE_OK ){
43681          return rc;
43682        }
43683        sqlite3WalExclusiveMode(pPager->pWal, 1);
43684      }
43685
43686      /* Grab the write lock on the log file. If successful, upgrade to
43687      ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
43688      ** The busy-handler is not invoked if another connection already
43689      ** holds the write-lock. If possible, the upper layer will call it.
43690      */
43691      rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
43692    }else{
43693      /* Obtain a RESERVED lock on the database file. If the exFlag parameter
43694      ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
43695      ** busy-handler callback can be used when upgrading to the EXCLUSIVE
43696      ** lock, but not when obtaining the RESERVED lock.
43697      */
43698      rc = pagerLockDb(pPager, RESERVED_LOCK);
43699      if( rc==SQLITE_OK && exFlag ){
43700        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43701      }
43702    }
43703
43704    if( rc==SQLITE_OK ){
43705      /* Change to WRITER_LOCKED state.
43706      **
43707      ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
43708      ** when it has an open transaction, but never to DBMOD or FINISHED.
43709      ** This is because in those states the code to roll back savepoint
43710      ** transactions may copy data from the sub-journal into the database
43711      ** file as well as into the page cache. Which would be incorrect in
43712      ** WAL mode.
43713      */
43714      pPager->eState = PAGER_WRITER_LOCKED;
43715      pPager->dbHintSize = pPager->dbSize;
43716      pPager->dbFileSize = pPager->dbSize;
43717      pPager->dbOrigSize = pPager->dbSize;
43718      pPager->journalOff = 0;
43719    }
43720
43721    assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
43722    assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
43723    assert( assert_pager_state(pPager) );
43724  }
43725
43726  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
43727  return rc;
43728}
43729
43730/*
43731** Mark a single data page as writeable. The page is written into the
43732** main journal or sub-journal as required. If the page is written into
43733** one of the journals, the corresponding bit is set in the
43734** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
43735** of any open savepoints as appropriate.
43736*/
43737static int pager_write(PgHdr *pPg){
43738  void *pData = pPg->pData;
43739  Pager *pPager = pPg->pPager;
43740  int rc = SQLITE_OK;
43741
43742  /* This routine is not called unless a write-transaction has already
43743  ** been started. The journal file may or may not be open at this point.
43744  ** It is never called in the ERROR state.
43745  */
43746  assert( pPager->eState==PAGER_WRITER_LOCKED
43747       || pPager->eState==PAGER_WRITER_CACHEMOD
43748       || pPager->eState==PAGER_WRITER_DBMOD
43749  );
43750  assert( assert_pager_state(pPager) );
43751
43752  /* If an error has been previously detected, report the same error
43753  ** again. This should not happen, but the check provides robustness. */
43754  if( NEVER(pPager->errCode) )  return pPager->errCode;
43755
43756  /* Higher-level routines never call this function if database is not
43757  ** writable.  But check anyway, just for robustness. */
43758  if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
43759
43760  CHECK_PAGE(pPg);
43761
43762  /* The journal file needs to be opened. Higher level routines have already
43763  ** obtained the necessary locks to begin the write-transaction, but the
43764  ** rollback journal might not yet be open. Open it now if this is the case.
43765  **
43766  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
43767  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
43768  ** an error might occur and the pager would end up in WRITER_LOCKED state
43769  ** with pages marked as dirty in the cache.
43770  */
43771  if( pPager->eState==PAGER_WRITER_LOCKED ){
43772    rc = pager_open_journal(pPager);
43773    if( rc!=SQLITE_OK ) return rc;
43774  }
43775  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43776  assert( assert_pager_state(pPager) );
43777
43778  /* Mark the page as dirty.  If the page has already been written
43779  ** to the journal then we can return right away.
43780  */
43781  sqlite3PcacheMakeDirty(pPg);
43782  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
43783    assert( !pagerUseWal(pPager) );
43784  }else{
43785
43786    /* The transaction journal now exists and we have a RESERVED or an
43787    ** EXCLUSIVE lock on the main database file.  Write the current page to
43788    ** the transaction journal if it is not there already.
43789    */
43790    if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
43791      assert( pagerUseWal(pPager)==0 );
43792      if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
43793        u32 cksum;
43794        char *pData2;
43795        i64 iOff = pPager->journalOff;
43796
43797        /* We should never write to the journal file the page that
43798        ** contains the database locks.  The following assert verifies
43799        ** that we do not. */
43800        assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
43801
43802        assert( pPager->journalHdr<=pPager->journalOff );
43803        CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
43804        cksum = pager_cksum(pPager, (u8*)pData2);
43805
43806        /* Even if an IO or diskfull error occurs while journalling the
43807        ** page in the block above, set the need-sync flag for the page.
43808        ** Otherwise, when the transaction is rolled back, the logic in
43809        ** playback_one_page() will think that the page needs to be restored
43810        ** in the database file. And if an IO error occurs while doing so,
43811        ** then corruption may follow.
43812        */
43813        pPg->flags |= PGHDR_NEED_SYNC;
43814
43815        rc = write32bits(pPager->jfd, iOff, pPg->pgno);
43816        if( rc!=SQLITE_OK ) return rc;
43817        rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
43818        if( rc!=SQLITE_OK ) return rc;
43819        rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
43820        if( rc!=SQLITE_OK ) return rc;
43821
43822        IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
43823                 pPager->journalOff, pPager->pageSize));
43824        PAGER_INCR(sqlite3_pager_writej_count);
43825        PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
43826             PAGERID(pPager), pPg->pgno,
43827             ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
43828
43829        pPager->journalOff += 8 + pPager->pageSize;
43830        pPager->nRec++;
43831        assert( pPager->pInJournal!=0 );
43832        rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
43833        testcase( rc==SQLITE_NOMEM );
43834        assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
43835        rc |= addToSavepointBitvecs(pPager, pPg->pgno);
43836        if( rc!=SQLITE_OK ){
43837          assert( rc==SQLITE_NOMEM );
43838          return rc;
43839        }
43840      }else{
43841        if( pPager->eState!=PAGER_WRITER_DBMOD ){
43842          pPg->flags |= PGHDR_NEED_SYNC;
43843        }
43844        PAGERTRACE(("APPEND %d page %d needSync=%d\n",
43845                PAGERID(pPager), pPg->pgno,
43846               ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
43847      }
43848    }
43849
43850    /* If the statement journal is open and the page is not in it,
43851    ** then write the current page to the statement journal.  Note that
43852    ** the statement journal format differs from the standard journal format
43853    ** in that it omits the checksums and the header.
43854    */
43855    if( subjRequiresPage(pPg) ){
43856      rc = subjournalPage(pPg);
43857    }
43858  }
43859
43860  /* Update the database size and return.
43861  */
43862  if( pPager->dbSize<pPg->pgno ){
43863    pPager->dbSize = pPg->pgno;
43864  }
43865  return rc;
43866}
43867
43868/*
43869** Mark a data page as writeable. This routine must be called before
43870** making changes to a page. The caller must check the return value
43871** of this function and be careful not to change any page data unless
43872** this routine returns SQLITE_OK.
43873**
43874** The difference between this function and pager_write() is that this
43875** function also deals with the special case where 2 or more pages
43876** fit on a single disk sector. In this case all co-resident pages
43877** must have been written to the journal file before returning.
43878**
43879** If an error occurs, SQLITE_NOMEM or an IO error code is returned
43880** as appropriate. Otherwise, SQLITE_OK.
43881*/
43882SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
43883  int rc = SQLITE_OK;
43884
43885  PgHdr *pPg = pDbPage;
43886  Pager *pPager = pPg->pPager;
43887  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
43888
43889  assert( pPager->eState>=PAGER_WRITER_LOCKED );
43890  assert( pPager->eState!=PAGER_ERROR );
43891  assert( assert_pager_state(pPager) );
43892
43893  if( nPagePerSector>1 ){
43894    Pgno nPageCount;          /* Total number of pages in database file */
43895    Pgno pg1;                 /* First page of the sector pPg is located on. */
43896    int nPage = 0;            /* Number of pages starting at pg1 to journal */
43897    int ii;                   /* Loop counter */
43898    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
43899
43900    /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
43901    ** a journal header to be written between the pages journaled by
43902    ** this function.
43903    */
43904    assert( !MEMDB );
43905    assert( pPager->doNotSyncSpill==0 );
43906    pPager->doNotSyncSpill++;
43907
43908    /* This trick assumes that both the page-size and sector-size are
43909    ** an integer power of 2. It sets variable pg1 to the identifier
43910    ** of the first page of the sector pPg is located on.
43911    */
43912    pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
43913
43914    nPageCount = pPager->dbSize;
43915    if( pPg->pgno>nPageCount ){
43916      nPage = (pPg->pgno - pg1)+1;
43917    }else if( (pg1+nPagePerSector-1)>nPageCount ){
43918      nPage = nPageCount+1-pg1;
43919    }else{
43920      nPage = nPagePerSector;
43921    }
43922    assert(nPage>0);
43923    assert(pg1<=pPg->pgno);
43924    assert((pg1+nPage)>pPg->pgno);
43925
43926    for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
43927      Pgno pg = pg1+ii;
43928      PgHdr *pPage;
43929      if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
43930        if( pg!=PAGER_MJ_PGNO(pPager) ){
43931          rc = sqlite3PagerGet(pPager, pg, &pPage);
43932          if( rc==SQLITE_OK ){
43933            rc = pager_write(pPage);
43934            if( pPage->flags&PGHDR_NEED_SYNC ){
43935              needSync = 1;
43936            }
43937            sqlite3PagerUnref(pPage);
43938          }
43939        }
43940      }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
43941        if( pPage->flags&PGHDR_NEED_SYNC ){
43942          needSync = 1;
43943        }
43944        sqlite3PagerUnref(pPage);
43945      }
43946    }
43947
43948    /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
43949    ** starting at pg1, then it needs to be set for all of them. Because
43950    ** writing to any of these nPage pages may damage the others, the
43951    ** journal file must contain sync()ed copies of all of them
43952    ** before any of them can be written out to the database file.
43953    */
43954    if( rc==SQLITE_OK && needSync ){
43955      assert( !MEMDB );
43956      for(ii=0; ii<nPage; ii++){
43957        PgHdr *pPage = pager_lookup(pPager, pg1+ii);
43958        if( pPage ){
43959          pPage->flags |= PGHDR_NEED_SYNC;
43960          sqlite3PagerUnref(pPage);
43961        }
43962      }
43963    }
43964
43965    assert( pPager->doNotSyncSpill==1 );
43966    pPager->doNotSyncSpill--;
43967  }else{
43968    rc = pager_write(pDbPage);
43969  }
43970  return rc;
43971}
43972
43973/*
43974** Return TRUE if the page given in the argument was previously passed
43975** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
43976** to change the content of the page.
43977*/
43978#ifndef NDEBUG
43979SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
43980  return pPg->flags&PGHDR_DIRTY;
43981}
43982#endif
43983
43984/*
43985** A call to this routine tells the pager that it is not necessary to
43986** write the information on page pPg back to the disk, even though
43987** that page might be marked as dirty.  This happens, for example, when
43988** the page has been added as a leaf of the freelist and so its
43989** content no longer matters.
43990**
43991** The overlying software layer calls this routine when all of the data
43992** on the given page is unused. The pager marks the page as clean so
43993** that it does not get written to disk.
43994**
43995** Tests show that this optimization can quadruple the speed of large
43996** DELETE operations.
43997*/
43998SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
43999  Pager *pPager = pPg->pPager;
44000  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
44001    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
44002    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
44003    pPg->flags |= PGHDR_DONT_WRITE;
44004    pager_set_pagehash(pPg);
44005  }
44006}
44007
44008/*
44009** This routine is called to increment the value of the database file
44010** change-counter, stored as a 4-byte big-endian integer starting at
44011** byte offset 24 of the pager file.  The secondary change counter at
44012** 92 is also updated, as is the SQLite version number at offset 96.
44013**
44014** But this only happens if the pPager->changeCountDone flag is false.
44015** To avoid excess churning of page 1, the update only happens once.
44016** See also the pager_write_changecounter() routine that does an
44017** unconditional update of the change counters.
44018**
44019** If the isDirectMode flag is zero, then this is done by calling
44020** sqlite3PagerWrite() on page 1, then modifying the contents of the
44021** page data. In this case the file will be updated when the current
44022** transaction is committed.
44023**
44024** The isDirectMode flag may only be non-zero if the library was compiled
44025** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
44026** if isDirect is non-zero, then the database file is updated directly
44027** by writing an updated version of page 1 using a call to the
44028** sqlite3OsWrite() function.
44029*/
44030static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
44031  int rc = SQLITE_OK;
44032
44033  assert( pPager->eState==PAGER_WRITER_CACHEMOD
44034       || pPager->eState==PAGER_WRITER_DBMOD
44035  );
44036  assert( assert_pager_state(pPager) );
44037
44038  /* Declare and initialize constant integer 'isDirect'. If the
44039  ** atomic-write optimization is enabled in this build, then isDirect
44040  ** is initialized to the value passed as the isDirectMode parameter
44041  ** to this function. Otherwise, it is always set to zero.
44042  **
44043  ** The idea is that if the atomic-write optimization is not
44044  ** enabled at compile time, the compiler can omit the tests of
44045  ** 'isDirect' below, as well as the block enclosed in the
44046  ** "if( isDirect )" condition.
44047  */
44048#ifndef SQLITE_ENABLE_ATOMIC_WRITE
44049# define DIRECT_MODE 0
44050  assert( isDirectMode==0 );
44051  UNUSED_PARAMETER(isDirectMode);
44052#else
44053# define DIRECT_MODE isDirectMode
44054#endif
44055
44056  if( !pPager->changeCountDone && pPager->dbSize>0 ){
44057    PgHdr *pPgHdr;                /* Reference to page 1 */
44058
44059    assert( !pPager->tempFile && isOpen(pPager->fd) );
44060
44061    /* Open page 1 of the file for writing. */
44062    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
44063    assert( pPgHdr==0 || rc==SQLITE_OK );
44064
44065    /* If page one was fetched successfully, and this function is not
44066    ** operating in direct-mode, make page 1 writable.  When not in
44067    ** direct mode, page 1 is always held in cache and hence the PagerGet()
44068    ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
44069    */
44070    if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
44071      rc = sqlite3PagerWrite(pPgHdr);
44072    }
44073
44074    if( rc==SQLITE_OK ){
44075      /* Actually do the update of the change counter */
44076      pager_write_changecounter(pPgHdr);
44077
44078      /* If running in direct mode, write the contents of page 1 to the file. */
44079      if( DIRECT_MODE ){
44080        const void *zBuf;
44081        assert( pPager->dbFileSize>0 );
44082        CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
44083        if( rc==SQLITE_OK ){
44084          rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
44085        }
44086        if( rc==SQLITE_OK ){
44087          pPager->changeCountDone = 1;
44088        }
44089      }else{
44090        pPager->changeCountDone = 1;
44091      }
44092    }
44093
44094    /* Release the page reference. */
44095    sqlite3PagerUnref(pPgHdr);
44096  }
44097  return rc;
44098}
44099
44100/*
44101** Sync the database file to disk. This is a no-op for in-memory databases
44102** or pages with the Pager.noSync flag set.
44103**
44104** If successful, or if called on a pager for which it is a no-op, this
44105** function returns SQLITE_OK. Otherwise, an IO error code is returned.
44106*/
44107SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
44108  int rc = SQLITE_OK;
44109  if( !pPager->noSync ){
44110    assert( !MEMDB );
44111    rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
44112  }else if( isOpen(pPager->fd) ){
44113    assert( !MEMDB );
44114    rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
44115    if( rc==SQLITE_NOTFOUND ){
44116      rc = SQLITE_OK;
44117    }
44118  }
44119  return rc;
44120}
44121
44122/*
44123** This function may only be called while a write-transaction is active in
44124** rollback. If the connection is in WAL mode, this call is a no-op.
44125** Otherwise, if the connection does not already have an EXCLUSIVE lock on
44126** the database file, an attempt is made to obtain one.
44127**
44128** If the EXCLUSIVE lock is already held or the attempt to obtain it is
44129** successful, or the connection is in WAL mode, SQLITE_OK is returned.
44130** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
44131** returned.
44132*/
44133SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
44134  int rc = SQLITE_OK;
44135  assert( pPager->eState==PAGER_WRITER_CACHEMOD
44136       || pPager->eState==PAGER_WRITER_DBMOD
44137       || pPager->eState==PAGER_WRITER_LOCKED
44138  );
44139  assert( assert_pager_state(pPager) );
44140  if( 0==pagerUseWal(pPager) ){
44141    rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44142  }
44143  return rc;
44144}
44145
44146/*
44147** Sync the database file for the pager pPager. zMaster points to the name
44148** of a master journal file that should be written into the individual
44149** journal file. zMaster may be NULL, which is interpreted as no master
44150** journal (a single database transaction).
44151**
44152** This routine ensures that:
44153**
44154**   * The database file change-counter is updated,
44155**   * the journal is synced (unless the atomic-write optimization is used),
44156**   * all dirty pages are written to the database file,
44157**   * the database file is truncated (if required), and
44158**   * the database file synced.
44159**
44160** The only thing that remains to commit the transaction is to finalize
44161** (delete, truncate or zero the first part of) the journal file (or
44162** delete the master journal file if specified).
44163**
44164** Note that if zMaster==NULL, this does not overwrite a previous value
44165** passed to an sqlite3PagerCommitPhaseOne() call.
44166**
44167** If the final parameter - noSync - is true, then the database file itself
44168** is not synced. The caller must call sqlite3PagerSync() directly to
44169** sync the database file before calling CommitPhaseTwo() to delete the
44170** journal file in this case.
44171*/
44172SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
44173  Pager *pPager,                  /* Pager object */
44174  const char *zMaster,            /* If not NULL, the master journal name */
44175  int noSync                      /* True to omit the xSync on the db file */
44176){
44177  int rc = SQLITE_OK;             /* Return code */
44178
44179  assert( pPager->eState==PAGER_WRITER_LOCKED
44180       || pPager->eState==PAGER_WRITER_CACHEMOD
44181       || pPager->eState==PAGER_WRITER_DBMOD
44182       || pPager->eState==PAGER_ERROR
44183  );
44184  assert( assert_pager_state(pPager) );
44185
44186  /* If a prior error occurred, report that error again. */
44187  if( NEVER(pPager->errCode) ) return pPager->errCode;
44188
44189  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
44190      pPager->zFilename, zMaster, pPager->dbSize));
44191
44192  /* If no database changes have been made, return early. */
44193  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
44194
44195  if( MEMDB ){
44196    /* If this is an in-memory db, or no pages have been written to, or this
44197    ** function has already been called, it is mostly a no-op.  However, any
44198    ** backup in progress needs to be restarted.
44199    */
44200    sqlite3BackupRestart(pPager->pBackup);
44201  }else{
44202    if( pagerUseWal(pPager) ){
44203      PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
44204      PgHdr *pPageOne = 0;
44205      if( pList==0 ){
44206        /* Must have at least one page for the WAL commit flag.
44207        ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
44208        rc = sqlite3PagerGet(pPager, 1, &pPageOne);
44209        pList = pPageOne;
44210        pList->pDirty = 0;
44211      }
44212      assert( rc==SQLITE_OK );
44213      if( ALWAYS(pList) ){
44214        rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
44215      }
44216      sqlite3PagerUnref(pPageOne);
44217      if( rc==SQLITE_OK ){
44218        sqlite3PcacheCleanAll(pPager->pPCache);
44219      }
44220    }else{
44221      /* The following block updates the change-counter. Exactly how it
44222      ** does this depends on whether or not the atomic-update optimization
44223      ** was enabled at compile time, and if this transaction meets the
44224      ** runtime criteria to use the operation:
44225      **
44226      **    * The file-system supports the atomic-write property for
44227      **      blocks of size page-size, and
44228      **    * This commit is not part of a multi-file transaction, and
44229      **    * Exactly one page has been modified and store in the journal file.
44230      **
44231      ** If the optimization was not enabled at compile time, then the
44232      ** pager_incr_changecounter() function is called to update the change
44233      ** counter in 'indirect-mode'. If the optimization is compiled in but
44234      ** is not applicable to this transaction, call sqlite3JournalCreate()
44235      ** to make sure the journal file has actually been created, then call
44236      ** pager_incr_changecounter() to update the change-counter in indirect
44237      ** mode.
44238      **
44239      ** Otherwise, if the optimization is both enabled and applicable,
44240      ** then call pager_incr_changecounter() to update the change-counter
44241      ** in 'direct' mode. In this case the journal file will never be
44242      ** created for this transaction.
44243      */
44244  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44245      PgHdr *pPg;
44246      assert( isOpen(pPager->jfd)
44247           || pPager->journalMode==PAGER_JOURNALMODE_OFF
44248           || pPager->journalMode==PAGER_JOURNALMODE_WAL
44249      );
44250      if( !zMaster && isOpen(pPager->jfd)
44251       && pPager->journalOff==jrnlBufferSize(pPager)
44252       && pPager->dbSize>=pPager->dbOrigSize
44253       && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
44254      ){
44255        /* Update the db file change counter via the direct-write method. The
44256        ** following call will modify the in-memory representation of page 1
44257        ** to include the updated change counter and then write page 1
44258        ** directly to the database file. Because of the atomic-write
44259        ** property of the host file-system, this is safe.
44260        */
44261        rc = pager_incr_changecounter(pPager, 1);
44262      }else{
44263        rc = sqlite3JournalCreate(pPager->jfd);
44264        if( rc==SQLITE_OK ){
44265          rc = pager_incr_changecounter(pPager, 0);
44266        }
44267      }
44268  #else
44269      rc = pager_incr_changecounter(pPager, 0);
44270  #endif
44271      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44272
44273      /* If this transaction has made the database smaller, then all pages
44274      ** being discarded by the truncation must be written to the journal
44275      ** file. This can only happen in auto-vacuum mode.
44276      **
44277      ** Before reading the pages with page numbers larger than the
44278      ** current value of Pager.dbSize, set dbSize back to the value
44279      ** that it took at the start of the transaction. Otherwise, the
44280      ** calls to sqlite3PagerGet() return zeroed pages instead of
44281      ** reading data from the database file.
44282      */
44283  #ifndef SQLITE_OMIT_AUTOVACUUM
44284      if( pPager->dbSize<pPager->dbOrigSize
44285       && pPager->journalMode!=PAGER_JOURNALMODE_OFF
44286      ){
44287        Pgno i;                                   /* Iterator variable */
44288        const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
44289        const Pgno dbSize = pPager->dbSize;       /* Database image size */
44290        pPager->dbSize = pPager->dbOrigSize;
44291        for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
44292          if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
44293            PgHdr *pPage;             /* Page to journal */
44294            rc = sqlite3PagerGet(pPager, i, &pPage);
44295            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44296            rc = sqlite3PagerWrite(pPage);
44297            sqlite3PagerUnref(pPage);
44298            if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44299          }
44300        }
44301        pPager->dbSize = dbSize;
44302      }
44303  #endif
44304
44305      /* Write the master journal name into the journal file. If a master
44306      ** journal file name has already been written to the journal file,
44307      ** or if zMaster is NULL (no master journal), then this call is a no-op.
44308      */
44309      rc = writeMasterJournal(pPager, zMaster);
44310      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44311
44312      /* Sync the journal file and write all dirty pages to the database.
44313      ** If the atomic-update optimization is being used, this sync will not
44314      ** create the journal file or perform any real IO.
44315      **
44316      ** Because the change-counter page was just modified, unless the
44317      ** atomic-update optimization is used it is almost certain that the
44318      ** journal requires a sync here. However, in locking_mode=exclusive
44319      ** on a system under memory pressure it is just possible that this is
44320      ** not the case. In this case it is likely enough that the redundant
44321      ** xSync() call will be changed to a no-op by the OS anyhow.
44322      */
44323      rc = syncJournal(pPager, 0);
44324      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44325
44326      rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
44327      if( rc!=SQLITE_OK ){
44328        assert( rc!=SQLITE_IOERR_BLOCKED );
44329        goto commit_phase_one_exit;
44330      }
44331      sqlite3PcacheCleanAll(pPager->pPCache);
44332
44333      /* If the file on disk is not the same size as the database image,
44334      ** then use pager_truncate to grow or shrink the file here.
44335      */
44336      if( pPager->dbSize!=pPager->dbFileSize ){
44337        Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
44338        assert( pPager->eState==PAGER_WRITER_DBMOD );
44339        rc = pager_truncate(pPager, nNew);
44340        if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44341      }
44342
44343      /* Finally, sync the database file. */
44344      if( !noSync ){
44345        rc = sqlite3PagerSync(pPager);
44346      }
44347      IOTRACE(("DBSYNC %p\n", pPager))
44348    }
44349  }
44350
44351commit_phase_one_exit:
44352  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
44353    pPager->eState = PAGER_WRITER_FINISHED;
44354  }
44355  return rc;
44356}
44357
44358
44359/*
44360** When this function is called, the database file has been completely
44361** updated to reflect the changes made by the current transaction and
44362** synced to disk. The journal file still exists in the file-system
44363** though, and if a failure occurs at this point it will eventually
44364** be used as a hot-journal and the current transaction rolled back.
44365**
44366** This function finalizes the journal file, either by deleting,
44367** truncating or partially zeroing it, so that it cannot be used
44368** for hot-journal rollback. Once this is done the transaction is
44369** irrevocably committed.
44370**
44371** If an error occurs, an IO error code is returned and the pager
44372** moves into the error state. Otherwise, SQLITE_OK is returned.
44373*/
44374SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
44375  int rc = SQLITE_OK;                  /* Return code */
44376
44377  /* This routine should not be called if a prior error has occurred.
44378  ** But if (due to a coding error elsewhere in the system) it does get
44379  ** called, just return the same error code without doing anything. */
44380  if( NEVER(pPager->errCode) ) return pPager->errCode;
44381
44382  assert( pPager->eState==PAGER_WRITER_LOCKED
44383       || pPager->eState==PAGER_WRITER_FINISHED
44384       || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
44385  );
44386  assert( assert_pager_state(pPager) );
44387
44388  /* An optimization. If the database was not actually modified during
44389  ** this transaction, the pager is running in exclusive-mode and is
44390  ** using persistent journals, then this function is a no-op.
44391  **
44392  ** The start of the journal file currently contains a single journal
44393  ** header with the nRec field set to 0. If such a journal is used as
44394  ** a hot-journal during hot-journal rollback, 0 changes will be made
44395  ** to the database file. So there is no need to zero the journal
44396  ** header. Since the pager is in exclusive mode, there is no need
44397  ** to drop any locks either.
44398  */
44399  if( pPager->eState==PAGER_WRITER_LOCKED
44400   && pPager->exclusiveMode
44401   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
44402  ){
44403    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
44404    pPager->eState = PAGER_READER;
44405    return SQLITE_OK;
44406  }
44407
44408  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
44409  rc = pager_end_transaction(pPager, pPager->setMaster);
44410  return pager_error(pPager, rc);
44411}
44412
44413/*
44414** If a write transaction is open, then all changes made within the
44415** transaction are reverted and the current write-transaction is closed.
44416** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
44417** state if an error occurs.
44418**
44419** If the pager is already in PAGER_ERROR state when this function is called,
44420** it returns Pager.errCode immediately. No work is performed in this case.
44421**
44422** Otherwise, in rollback mode, this function performs two functions:
44423**
44424**   1) It rolls back the journal file, restoring all database file and
44425**      in-memory cache pages to the state they were in when the transaction
44426**      was opened, and
44427**
44428**   2) It finalizes the journal file, so that it is not used for hot
44429**      rollback at any point in the future.
44430**
44431** Finalization of the journal file (task 2) is only performed if the
44432** rollback is successful.
44433**
44434** In WAL mode, all cache-entries containing data modified within the
44435** current transaction are either expelled from the cache or reverted to
44436** their pre-transaction state by re-reading data from the database or
44437** WAL files. The WAL transaction is then closed.
44438*/
44439SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
44440  int rc = SQLITE_OK;                  /* Return code */
44441  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
44442
44443  /* PagerRollback() is a no-op if called in READER or OPEN state. If
44444  ** the pager is already in the ERROR state, the rollback is not
44445  ** attempted here. Instead, the error code is returned to the caller.
44446  */
44447  assert( assert_pager_state(pPager) );
44448  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
44449  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
44450
44451  if( pagerUseWal(pPager) ){
44452    int rc2;
44453    rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
44454    rc2 = pager_end_transaction(pPager, pPager->setMaster);
44455    if( rc==SQLITE_OK ) rc = rc2;
44456  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
44457    int eState = pPager->eState;
44458    rc = pager_end_transaction(pPager, 0);
44459    if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
44460      /* This can happen using journal_mode=off. Move the pager to the error
44461      ** state to indicate that the contents of the cache may not be trusted.
44462      ** Any active readers will get SQLITE_ABORT.
44463      */
44464      pPager->errCode = SQLITE_ABORT;
44465      pPager->eState = PAGER_ERROR;
44466      return rc;
44467    }
44468  }else{
44469    rc = pager_playback(pPager, 0);
44470  }
44471
44472  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
44473  assert( rc==SQLITE_OK || rc==SQLITE_FULL
44474          || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
44475
44476  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
44477  ** cache. So call pager_error() on the way out to make any error persistent.
44478  */
44479  return pager_error(pPager, rc);
44480}
44481
44482/*
44483** Return TRUE if the database file is opened read-only.  Return FALSE
44484** if the database is (in theory) writable.
44485*/
44486SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
44487  return pPager->readOnly;
44488}
44489
44490/*
44491** Return the number of references to the pager.
44492*/
44493SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
44494  return sqlite3PcacheRefCount(pPager->pPCache);
44495}
44496
44497/*
44498** Return the approximate number of bytes of memory currently
44499** used by the pager and its associated cache.
44500*/
44501SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
44502  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
44503                                     + 5*sizeof(void*);
44504  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
44505           + sqlite3MallocSize(pPager)
44506           + pPager->pageSize;
44507}
44508
44509/*
44510** Return the number of references to the specified page.
44511*/
44512SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
44513  return sqlite3PcachePageRefcount(pPage);
44514}
44515
44516#ifdef SQLITE_TEST
44517/*
44518** This routine is used for testing and analysis only.
44519*/
44520SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
44521  static int a[11];
44522  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
44523  a[1] = sqlite3PcachePagecount(pPager->pPCache);
44524  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
44525  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
44526  a[4] = pPager->eState;
44527  a[5] = pPager->errCode;
44528  a[6] = pPager->nHit;
44529  a[7] = pPager->nMiss;
44530  a[8] = 0;  /* Used to be pPager->nOvfl */
44531  a[9] = pPager->nRead;
44532  a[10] = pPager->nWrite;
44533  return a;
44534}
44535#endif
44536
44537/*
44538** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
44539** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
44540** current cache hit or miss count, according to the value of eStat. If the
44541** reset parameter is non-zero, the cache hit or miss count is zeroed before
44542** returning.
44543*/
44544SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
44545  int *piStat;
44546
44547  assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
44548       || eStat==SQLITE_DBSTATUS_CACHE_MISS
44549  );
44550  if( eStat==SQLITE_DBSTATUS_CACHE_HIT ){
44551    piStat = &pPager->nHit;
44552  }else{
44553    piStat = &pPager->nMiss;
44554  }
44555
44556  *pnVal += *piStat;
44557  if( reset ){
44558    *piStat = 0;
44559  }
44560}
44561
44562/*
44563** Return true if this is an in-memory pager.
44564*/
44565SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
44566  return MEMDB;
44567}
44568
44569/*
44570** Check that there are at least nSavepoint savepoints open. If there are
44571** currently less than nSavepoints open, then open one or more savepoints
44572** to make up the difference. If the number of savepoints is already
44573** equal to nSavepoint, then this function is a no-op.
44574**
44575** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
44576** occurs while opening the sub-journal file, then an IO error code is
44577** returned. Otherwise, SQLITE_OK.
44578*/
44579SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
44580  int rc = SQLITE_OK;                       /* Return code */
44581  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
44582
44583  assert( pPager->eState>=PAGER_WRITER_LOCKED );
44584  assert( assert_pager_state(pPager) );
44585
44586  if( nSavepoint>nCurrent && pPager->useJournal ){
44587    int ii;                                 /* Iterator variable */
44588    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
44589
44590    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
44591    ** if the allocation fails. Otherwise, zero the new portion in case a
44592    ** malloc failure occurs while populating it in the for(...) loop below.
44593    */
44594    aNew = (PagerSavepoint *)sqlite3Realloc(
44595        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
44596    );
44597    if( !aNew ){
44598      return SQLITE_NOMEM;
44599    }
44600    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
44601    pPager->aSavepoint = aNew;
44602
44603    /* Populate the PagerSavepoint structures just allocated. */
44604    for(ii=nCurrent; ii<nSavepoint; ii++){
44605      aNew[ii].nOrig = pPager->dbSize;
44606      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
44607        aNew[ii].iOffset = pPager->journalOff;
44608      }else{
44609        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
44610      }
44611      aNew[ii].iSubRec = pPager->nSubRec;
44612      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
44613      if( !aNew[ii].pInSavepoint ){
44614        return SQLITE_NOMEM;
44615      }
44616      if( pagerUseWal(pPager) ){
44617        sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
44618      }
44619      pPager->nSavepoint = ii+1;
44620    }
44621    assert( pPager->nSavepoint==nSavepoint );
44622    assertTruncateConstraint(pPager);
44623  }
44624
44625  return rc;
44626}
44627
44628/*
44629** This function is called to rollback or release (commit) a savepoint.
44630** The savepoint to release or rollback need not be the most recently
44631** created savepoint.
44632**
44633** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
44634** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
44635** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
44636** that have occurred since the specified savepoint was created.
44637**
44638** The savepoint to rollback or release is identified by parameter
44639** iSavepoint. A value of 0 means to operate on the outermost savepoint
44640** (the first created). A value of (Pager.nSavepoint-1) means operate
44641** on the most recently created savepoint. If iSavepoint is greater than
44642** (Pager.nSavepoint-1), then this function is a no-op.
44643**
44644** If a negative value is passed to this function, then the current
44645** transaction is rolled back. This is different to calling
44646** sqlite3PagerRollback() because this function does not terminate
44647** the transaction or unlock the database, it just restores the
44648** contents of the database to its original state.
44649**
44650** In any case, all savepoints with an index greater than iSavepoint
44651** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
44652** then savepoint iSavepoint is also destroyed.
44653**
44654** This function may return SQLITE_NOMEM if a memory allocation fails,
44655** or an IO error code if an IO error occurs while rolling back a
44656** savepoint. If no errors occur, SQLITE_OK is returned.
44657*/
44658SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
44659  int rc = pPager->errCode;       /* Return code */
44660
44661  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
44662  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
44663
44664  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
44665    int ii;            /* Iterator variable */
44666    int nNew;          /* Number of remaining savepoints after this op. */
44667
44668    /* Figure out how many savepoints will still be active after this
44669    ** operation. Store this value in nNew. Then free resources associated
44670    ** with any savepoints that are destroyed by this operation.
44671    */
44672    nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
44673    for(ii=nNew; ii<pPager->nSavepoint; ii++){
44674      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
44675    }
44676    pPager->nSavepoint = nNew;
44677
44678    /* If this is a release of the outermost savepoint, truncate
44679    ** the sub-journal to zero bytes in size. */
44680    if( op==SAVEPOINT_RELEASE ){
44681      if( nNew==0 && isOpen(pPager->sjfd) ){
44682        /* Only truncate if it is an in-memory sub-journal. */
44683        if( sqlite3IsMemJournal(pPager->sjfd) ){
44684          rc = sqlite3OsTruncate(pPager->sjfd, 0);
44685          assert( rc==SQLITE_OK );
44686        }
44687        pPager->nSubRec = 0;
44688      }
44689    }
44690    /* Else this is a rollback operation, playback the specified savepoint.
44691    ** If this is a temp-file, it is possible that the journal file has
44692    ** not yet been opened. In this case there have been no changes to
44693    ** the database file, so the playback operation can be skipped.
44694    */
44695    else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
44696      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
44697      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
44698      assert(rc!=SQLITE_DONE);
44699    }
44700  }
44701
44702  return rc;
44703}
44704
44705/*
44706** Return the full pathname of the database file.
44707*/
44708SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
44709  return pPager->zFilename;
44710}
44711
44712/*
44713** Return the VFS structure for the pager.
44714*/
44715SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
44716  return pPager->pVfs;
44717}
44718
44719/*
44720** Return the file handle for the database file associated
44721** with the pager.  This might return NULL if the file has
44722** not yet been opened.
44723*/
44724SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
44725  return pPager->fd;
44726}
44727
44728/*
44729** Return the full pathname of the journal file.
44730*/
44731SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
44732  return pPager->zJournal;
44733}
44734
44735/*
44736** Return true if fsync() calls are disabled for this pager.  Return FALSE
44737** if fsync()s are executed normally.
44738*/
44739SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
44740  return pPager->noSync;
44741}
44742
44743#ifdef SQLITE_HAS_CODEC
44744/*
44745** Set or retrieve the codec for this pager
44746*/
44747SQLITE_PRIVATE void sqlite3PagerSetCodec(
44748  Pager *pPager,
44749  void *(*xCodec)(void*,void*,Pgno,int),
44750  void (*xCodecSizeChng)(void*,int,int),
44751  void (*xCodecFree)(void*),
44752  void *pCodec
44753){
44754  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
44755  pPager->xCodec = pPager->memDb ? 0 : xCodec;
44756  pPager->xCodecSizeChng = xCodecSizeChng;
44757  pPager->xCodecFree = xCodecFree;
44758  pPager->pCodec = pCodec;
44759  pagerReportSize(pPager);
44760}
44761SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
44762  return pPager->pCodec;
44763}
44764#endif
44765
44766#ifndef SQLITE_OMIT_AUTOVACUUM
44767/*
44768** Move the page pPg to location pgno in the file.
44769**
44770** There must be no references to the page previously located at
44771** pgno (which we call pPgOld) though that page is allowed to be
44772** in cache.  If the page previously located at pgno is not already
44773** in the rollback journal, it is not put there by by this routine.
44774**
44775** References to the page pPg remain valid. Updating any
44776** meta-data associated with pPg (i.e. data stored in the nExtra bytes
44777** allocated along with the page) is the responsibility of the caller.
44778**
44779** A transaction must be active when this routine is called. It used to be
44780** required that a statement transaction was not active, but this restriction
44781** has been removed (CREATE INDEX needs to move a page when a statement
44782** transaction is active).
44783**
44784** If the fourth argument, isCommit, is non-zero, then this page is being
44785** moved as part of a database reorganization just before the transaction
44786** is being committed. In this case, it is guaranteed that the database page
44787** pPg refers to will not be written to again within this transaction.
44788**
44789** This function may return SQLITE_NOMEM or an IO error code if an error
44790** occurs. Otherwise, it returns SQLITE_OK.
44791*/
44792SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
44793  PgHdr *pPgOld;               /* The page being overwritten. */
44794  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
44795  int rc;                      /* Return code */
44796  Pgno origPgno;               /* The original page number */
44797
44798  assert( pPg->nRef>0 );
44799  assert( pPager->eState==PAGER_WRITER_CACHEMOD
44800       || pPager->eState==PAGER_WRITER_DBMOD
44801  );
44802  assert( assert_pager_state(pPager) );
44803
44804  /* In order to be able to rollback, an in-memory database must journal
44805  ** the page we are moving from.
44806  */
44807  if( MEMDB ){
44808    rc = sqlite3PagerWrite(pPg);
44809    if( rc ) return rc;
44810  }
44811
44812  /* If the page being moved is dirty and has not been saved by the latest
44813  ** savepoint, then save the current contents of the page into the
44814  ** sub-journal now. This is required to handle the following scenario:
44815  **
44816  **   BEGIN;
44817  **     <journal page X, then modify it in memory>
44818  **     SAVEPOINT one;
44819  **       <Move page X to location Y>
44820  **     ROLLBACK TO one;
44821  **
44822  ** If page X were not written to the sub-journal here, it would not
44823  ** be possible to restore its contents when the "ROLLBACK TO one"
44824  ** statement were is processed.
44825  **
44826  ** subjournalPage() may need to allocate space to store pPg->pgno into
44827  ** one or more savepoint bitvecs. This is the reason this function
44828  ** may return SQLITE_NOMEM.
44829  */
44830  if( pPg->flags&PGHDR_DIRTY
44831   && subjRequiresPage(pPg)
44832   && SQLITE_OK!=(rc = subjournalPage(pPg))
44833  ){
44834    return rc;
44835  }
44836
44837  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
44838      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
44839  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
44840
44841  /* If the journal needs to be sync()ed before page pPg->pgno can
44842  ** be written to, store pPg->pgno in local variable needSyncPgno.
44843  **
44844  ** If the isCommit flag is set, there is no need to remember that
44845  ** the journal needs to be sync()ed before database page pPg->pgno
44846  ** can be written to. The caller has already promised not to write to it.
44847  */
44848  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
44849    needSyncPgno = pPg->pgno;
44850    assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
44851    assert( pPg->flags&PGHDR_DIRTY );
44852  }
44853
44854  /* If the cache contains a page with page-number pgno, remove it
44855  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
44856  ** page pgno before the 'move' operation, it needs to be retained
44857  ** for the page moved there.
44858  */
44859  pPg->flags &= ~PGHDR_NEED_SYNC;
44860  pPgOld = pager_lookup(pPager, pgno);
44861  assert( !pPgOld || pPgOld->nRef==1 );
44862  if( pPgOld ){
44863    pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
44864    if( MEMDB ){
44865      /* Do not discard pages from an in-memory database since we might
44866      ** need to rollback later.  Just move the page out of the way. */
44867      sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
44868    }else{
44869      sqlite3PcacheDrop(pPgOld);
44870    }
44871  }
44872
44873  origPgno = pPg->pgno;
44874  sqlite3PcacheMove(pPg, pgno);
44875  sqlite3PcacheMakeDirty(pPg);
44876
44877  /* For an in-memory database, make sure the original page continues
44878  ** to exist, in case the transaction needs to roll back.  Use pPgOld
44879  ** as the original page since it has already been allocated.
44880  */
44881  if( MEMDB ){
44882    assert( pPgOld );
44883    sqlite3PcacheMove(pPgOld, origPgno);
44884    sqlite3PagerUnref(pPgOld);
44885  }
44886
44887  if( needSyncPgno ){
44888    /* If needSyncPgno is non-zero, then the journal file needs to be
44889    ** sync()ed before any data is written to database file page needSyncPgno.
44890    ** Currently, no such page exists in the page-cache and the
44891    ** "is journaled" bitvec flag has been set. This needs to be remedied by
44892    ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
44893    ** flag.
44894    **
44895    ** If the attempt to load the page into the page-cache fails, (due
44896    ** to a malloc() or IO failure), clear the bit in the pInJournal[]
44897    ** array. Otherwise, if the page is loaded and written again in
44898    ** this transaction, it may be written to the database file before
44899    ** it is synced into the journal file. This way, it may end up in
44900    ** the journal file twice, but that is not a problem.
44901    */
44902    PgHdr *pPgHdr;
44903    rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
44904    if( rc!=SQLITE_OK ){
44905      if( needSyncPgno<=pPager->dbOrigSize ){
44906        assert( pPager->pTmpSpace!=0 );
44907        sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
44908      }
44909      return rc;
44910    }
44911    pPgHdr->flags |= PGHDR_NEED_SYNC;
44912    sqlite3PcacheMakeDirty(pPgHdr);
44913    sqlite3PagerUnref(pPgHdr);
44914  }
44915
44916  return SQLITE_OK;
44917}
44918#endif
44919
44920/*
44921** Return a pointer to the data for the specified page.
44922*/
44923SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
44924  assert( pPg->nRef>0 || pPg->pPager->memDb );
44925  return pPg->pData;
44926}
44927
44928/*
44929** Return a pointer to the Pager.nExtra bytes of "extra" space
44930** allocated along with the specified page.
44931*/
44932SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
44933  return pPg->pExtra;
44934}
44935
44936/*
44937** Get/set the locking-mode for this pager. Parameter eMode must be one
44938** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
44939** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
44940** the locking-mode is set to the value specified.
44941**
44942** The returned value is either PAGER_LOCKINGMODE_NORMAL or
44943** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
44944** locking-mode.
44945*/
44946SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
44947  assert( eMode==PAGER_LOCKINGMODE_QUERY
44948            || eMode==PAGER_LOCKINGMODE_NORMAL
44949            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
44950  assert( PAGER_LOCKINGMODE_QUERY<0 );
44951  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
44952  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
44953  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
44954    pPager->exclusiveMode = (u8)eMode;
44955  }
44956  return (int)pPager->exclusiveMode;
44957}
44958
44959/*
44960** Set the journal-mode for this pager. Parameter eMode must be one of:
44961**
44962**    PAGER_JOURNALMODE_DELETE
44963**    PAGER_JOURNALMODE_TRUNCATE
44964**    PAGER_JOURNALMODE_PERSIST
44965**    PAGER_JOURNALMODE_OFF
44966**    PAGER_JOURNALMODE_MEMORY
44967**    PAGER_JOURNALMODE_WAL
44968**
44969** The journalmode is set to the value specified if the change is allowed.
44970** The change may be disallowed for the following reasons:
44971**
44972**   *  An in-memory database can only have its journal_mode set to _OFF
44973**      or _MEMORY.
44974**
44975**   *  Temporary databases cannot have _WAL journalmode.
44976**
44977** The returned indicate the current (possibly updated) journal-mode.
44978*/
44979SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
44980  u8 eOld = pPager->journalMode;    /* Prior journalmode */
44981
44982#ifdef SQLITE_DEBUG
44983  /* The print_pager_state() routine is intended to be used by the debugger
44984  ** only.  We invoke it once here to suppress a compiler warning. */
44985  print_pager_state(pPager);
44986#endif
44987
44988
44989  /* The eMode parameter is always valid */
44990  assert(      eMode==PAGER_JOURNALMODE_DELETE
44991            || eMode==PAGER_JOURNALMODE_TRUNCATE
44992            || eMode==PAGER_JOURNALMODE_PERSIST
44993            || eMode==PAGER_JOURNALMODE_OFF
44994            || eMode==PAGER_JOURNALMODE_WAL
44995            || eMode==PAGER_JOURNALMODE_MEMORY );
44996
44997  /* This routine is only called from the OP_JournalMode opcode, and
44998  ** the logic there will never allow a temporary file to be changed
44999  ** to WAL mode.
45000  */
45001  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
45002
45003  /* Do allow the journalmode of an in-memory database to be set to
45004  ** anything other than MEMORY or OFF
45005  */
45006  if( MEMDB ){
45007    assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
45008    if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
45009      eMode = eOld;
45010    }
45011  }
45012
45013  if( eMode!=eOld ){
45014
45015    /* Change the journal mode. */
45016    assert( pPager->eState!=PAGER_ERROR );
45017    pPager->journalMode = (u8)eMode;
45018
45019    /* When transistioning from TRUNCATE or PERSIST to any other journal
45020    ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
45021    ** delete the journal file.
45022    */
45023    assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
45024    assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
45025    assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
45026    assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
45027    assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
45028    assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
45029
45030    assert( isOpen(pPager->fd) || pPager->exclusiveMode );
45031    if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
45032
45033      /* In this case we would like to delete the journal file. If it is
45034      ** not possible, then that is not a problem. Deleting the journal file
45035      ** here is an optimization only.
45036      **
45037      ** Before deleting the journal file, obtain a RESERVED lock on the
45038      ** database file. This ensures that the journal file is not deleted
45039      ** while it is in use by some other client.
45040      */
45041      sqlite3OsClose(pPager->jfd);
45042      if( pPager->eLock>=RESERVED_LOCK ){
45043        sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45044      }else{
45045        int rc = SQLITE_OK;
45046        int state = pPager->eState;
45047        assert( state==PAGER_OPEN || state==PAGER_READER );
45048        if( state==PAGER_OPEN ){
45049          rc = sqlite3PagerSharedLock(pPager);
45050        }
45051        if( pPager->eState==PAGER_READER ){
45052          assert( rc==SQLITE_OK );
45053          rc = pagerLockDb(pPager, RESERVED_LOCK);
45054        }
45055        if( rc==SQLITE_OK ){
45056          sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45057        }
45058        if( rc==SQLITE_OK && state==PAGER_READER ){
45059          pagerUnlockDb(pPager, SHARED_LOCK);
45060        }else if( state==PAGER_OPEN ){
45061          pager_unlock(pPager);
45062        }
45063        assert( state==pPager->eState );
45064      }
45065    }
45066  }
45067
45068  /* Return the new journal mode */
45069  return (int)pPager->journalMode;
45070}
45071
45072/*
45073** Return the current journal mode.
45074*/
45075SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
45076  return (int)pPager->journalMode;
45077}
45078
45079/*
45080** Return TRUE if the pager is in a state where it is OK to change the
45081** journalmode.  Journalmode changes can only happen when the database
45082** is unmodified.
45083*/
45084SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
45085  assert( assert_pager_state(pPager) );
45086  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
45087  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
45088  return 1;
45089}
45090
45091/*
45092** Get/set the size-limit used for persistent journal files.
45093**
45094** Setting the size limit to -1 means no limit is enforced.
45095** An attempt to set a limit smaller than -1 is a no-op.
45096*/
45097SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
45098  if( iLimit>=-1 ){
45099    pPager->journalSizeLimit = iLimit;
45100    sqlite3WalLimit(pPager->pWal, iLimit);
45101  }
45102  return pPager->journalSizeLimit;
45103}
45104
45105/*
45106** Return a pointer to the pPager->pBackup variable. The backup module
45107** in backup.c maintains the content of this variable. This module
45108** uses it opaquely as an argument to sqlite3BackupRestart() and
45109** sqlite3BackupUpdate() only.
45110*/
45111SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
45112  return &pPager->pBackup;
45113}
45114
45115#ifndef SQLITE_OMIT_VACUUM
45116/*
45117** Unless this is an in-memory or temporary database, clear the pager cache.
45118*/
45119SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
45120  if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
45121}
45122#endif
45123
45124#ifndef SQLITE_OMIT_WAL
45125/*
45126** This function is called when the user invokes "PRAGMA wal_checkpoint",
45127** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
45128** or wal_blocking_checkpoint() API functions.
45129**
45130** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
45131*/
45132SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
45133  int rc = SQLITE_OK;
45134  if( pPager->pWal ){
45135    rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
45136        pPager->xBusyHandler, pPager->pBusyHandlerArg,
45137        pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
45138        pnLog, pnCkpt
45139    );
45140  }
45141  return rc;
45142}
45143
45144SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
45145  return sqlite3WalCallback(pPager->pWal);
45146}
45147
45148/*
45149** Return true if the underlying VFS for the given pager supports the
45150** primitives necessary for write-ahead logging.
45151*/
45152SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
45153  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
45154  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
45155}
45156
45157/*
45158** Attempt to take an exclusive lock on the database file. If a PENDING lock
45159** is obtained instead, immediately release it.
45160*/
45161static int pagerExclusiveLock(Pager *pPager){
45162  int rc;                         /* Return code */
45163
45164  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45165  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
45166  if( rc!=SQLITE_OK ){
45167    /* If the attempt to grab the exclusive lock failed, release the
45168    ** pending lock that may have been obtained instead.  */
45169    pagerUnlockDb(pPager, SHARED_LOCK);
45170  }
45171
45172  return rc;
45173}
45174
45175/*
45176** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
45177** exclusive-locking mode when this function is called, take an EXCLUSIVE
45178** lock on the database file and use heap-memory to store the wal-index
45179** in. Otherwise, use the normal shared-memory.
45180*/
45181static int pagerOpenWal(Pager *pPager){
45182  int rc = SQLITE_OK;
45183
45184  assert( pPager->pWal==0 && pPager->tempFile==0 );
45185  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45186
45187  /* If the pager is already in exclusive-mode, the WAL module will use
45188  ** heap-memory for the wal-index instead of the VFS shared-memory
45189  ** implementation. Take the exclusive lock now, before opening the WAL
45190  ** file, to make sure this is safe.
45191  */
45192  if( pPager->exclusiveMode ){
45193    rc = pagerExclusiveLock(pPager);
45194  }
45195
45196  /* Open the connection to the log file. If this operation fails,
45197  ** (e.g. due to malloc() failure), return an error code.
45198  */
45199  if( rc==SQLITE_OK ){
45200    rc = sqlite3WalOpen(pPager->pVfs,
45201        pPager->fd, pPager->zWal, pPager->exclusiveMode,
45202        pPager->journalSizeLimit, &pPager->pWal
45203    );
45204  }
45205
45206  return rc;
45207}
45208
45209
45210/*
45211** The caller must be holding a SHARED lock on the database file to call
45212** this function.
45213**
45214** If the pager passed as the first argument is open on a real database
45215** file (not a temp file or an in-memory database), and the WAL file
45216** is not already open, make an attempt to open it now. If successful,
45217** return SQLITE_OK. If an error occurs or the VFS used by the pager does
45218** not support the xShmXXX() methods, return an error code. *pbOpen is
45219** not modified in either case.
45220**
45221** If the pager is open on a temp-file (or in-memory database), or if
45222** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
45223** without doing anything.
45224*/
45225SQLITE_PRIVATE int sqlite3PagerOpenWal(
45226  Pager *pPager,                  /* Pager object */
45227  int *pbOpen                     /* OUT: Set to true if call is a no-op */
45228){
45229  int rc = SQLITE_OK;             /* Return code */
45230
45231  assert( assert_pager_state(pPager) );
45232  assert( pPager->eState==PAGER_OPEN   || pbOpen );
45233  assert( pPager->eState==PAGER_READER || !pbOpen );
45234  assert( pbOpen==0 || *pbOpen==0 );
45235  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
45236
45237  if( !pPager->tempFile && !pPager->pWal ){
45238    if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
45239
45240    /* Close any rollback journal previously open */
45241    sqlite3OsClose(pPager->jfd);
45242
45243    rc = pagerOpenWal(pPager);
45244    if( rc==SQLITE_OK ){
45245      pPager->journalMode = PAGER_JOURNALMODE_WAL;
45246      pPager->eState = PAGER_OPEN;
45247    }
45248  }else{
45249    *pbOpen = 1;
45250  }
45251
45252  return rc;
45253}
45254
45255/*
45256** This function is called to close the connection to the log file prior
45257** to switching from WAL to rollback mode.
45258**
45259** Before closing the log file, this function attempts to take an
45260** EXCLUSIVE lock on the database file. If this cannot be obtained, an
45261** error (SQLITE_BUSY) is returned and the log connection is not closed.
45262** If successful, the EXCLUSIVE lock is not released before returning.
45263*/
45264SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
45265  int rc = SQLITE_OK;
45266
45267  assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
45268
45269  /* If the log file is not already open, but does exist in the file-system,
45270  ** it may need to be checkpointed before the connection can switch to
45271  ** rollback mode. Open it now so this can happen.
45272  */
45273  if( !pPager->pWal ){
45274    int logexists = 0;
45275    rc = pagerLockDb(pPager, SHARED_LOCK);
45276    if( rc==SQLITE_OK ){
45277      rc = sqlite3OsAccess(
45278          pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
45279      );
45280    }
45281    if( rc==SQLITE_OK && logexists ){
45282      rc = pagerOpenWal(pPager);
45283    }
45284  }
45285
45286  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
45287  ** the database file, the log and log-summary files will be deleted.
45288  */
45289  if( rc==SQLITE_OK && pPager->pWal ){
45290    rc = pagerExclusiveLock(pPager);
45291    if( rc==SQLITE_OK ){
45292      rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
45293                           pPager->pageSize, (u8*)pPager->pTmpSpace);
45294      pPager->pWal = 0;
45295    }
45296  }
45297  return rc;
45298}
45299
45300#ifdef SQLITE_ENABLE_ZIPVFS
45301/*
45302** A read-lock must be held on the pager when this function is called. If
45303** the pager is in WAL mode and the WAL file currently contains one or more
45304** frames, return the size in bytes of the page images stored within the
45305** WAL frames. Otherwise, if this is not a WAL database or the WAL file
45306** is empty, return 0.
45307*/
45308SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
45309  assert( pPager->eState==PAGER_READER );
45310  return sqlite3WalFramesize(pPager->pWal);
45311}
45312#endif
45313
45314#ifdef SQLITE_HAS_CODEC
45315/*
45316** This function is called by the wal module when writing page content
45317** into the log file.
45318**
45319** This function returns a pointer to a buffer containing the encrypted
45320** page content. If a malloc fails, this function may return NULL.
45321*/
45322SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
45323  void *aData = 0;
45324  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
45325  return aData;
45326}
45327#endif /* SQLITE_HAS_CODEC */
45328
45329#endif /* !SQLITE_OMIT_WAL */
45330
45331#endif /* SQLITE_OMIT_DISKIO */
45332
45333/************** End of pager.c ***********************************************/
45334/************** Begin file wal.c *********************************************/
45335/*
45336** 2010 February 1
45337**
45338** The author disclaims copyright to this source code.  In place of
45339** a legal notice, here is a blessing:
45340**
45341**    May you do good and not evil.
45342**    May you find forgiveness for yourself and forgive others.
45343**    May you share freely, never taking more than you give.
45344**
45345*************************************************************************
45346**
45347** This file contains the implementation of a write-ahead log (WAL) used in
45348** "journal_mode=WAL" mode.
45349**
45350** WRITE-AHEAD LOG (WAL) FILE FORMAT
45351**
45352** A WAL file consists of a header followed by zero or more "frames".
45353** Each frame records the revised content of a single page from the
45354** database file.  All changes to the database are recorded by writing
45355** frames into the WAL.  Transactions commit when a frame is written that
45356** contains a commit marker.  A single WAL can and usually does record
45357** multiple transactions.  Periodically, the content of the WAL is
45358** transferred back into the database file in an operation called a
45359** "checkpoint".
45360**
45361** A single WAL file can be used multiple times.  In other words, the
45362** WAL can fill up with frames and then be checkpointed and then new
45363** frames can overwrite the old ones.  A WAL always grows from beginning
45364** toward the end.  Checksums and counters attached to each frame are
45365** used to determine which frames within the WAL are valid and which
45366** are leftovers from prior checkpoints.
45367**
45368** The WAL header is 32 bytes in size and consists of the following eight
45369** big-endian 32-bit unsigned integer values:
45370**
45371**     0: Magic number.  0x377f0682 or 0x377f0683
45372**     4: File format version.  Currently 3007000
45373**     8: Database page size.  Example: 1024
45374**    12: Checkpoint sequence number
45375**    16: Salt-1, random integer incremented with each checkpoint
45376**    20: Salt-2, a different random integer changing with each ckpt
45377**    24: Checksum-1 (first part of checksum for first 24 bytes of header).
45378**    28: Checksum-2 (second part of checksum for first 24 bytes of header).
45379**
45380** Immediately following the wal-header are zero or more frames. Each
45381** frame consists of a 24-byte frame-header followed by a <page-size> bytes
45382** of page data. The frame-header is six big-endian 32-bit unsigned
45383** integer values, as follows:
45384**
45385**     0: Page number.
45386**     4: For commit records, the size of the database image in pages
45387**        after the commit. For all other records, zero.
45388**     8: Salt-1 (copied from the header)
45389**    12: Salt-2 (copied from the header)
45390**    16: Checksum-1.
45391**    20: Checksum-2.
45392**
45393** A frame is considered valid if and only if the following conditions are
45394** true:
45395**
45396**    (1) The salt-1 and salt-2 values in the frame-header match
45397**        salt values in the wal-header
45398**
45399**    (2) The checksum values in the final 8 bytes of the frame-header
45400**        exactly match the checksum computed consecutively on the
45401**        WAL header and the first 8 bytes and the content of all frames
45402**        up to and including the current frame.
45403**
45404** The checksum is computed using 32-bit big-endian integers if the
45405** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
45406** is computed using little-endian if the magic number is 0x377f0682.
45407** The checksum values are always stored in the frame header in a
45408** big-endian format regardless of which byte order is used to compute
45409** the checksum.  The checksum is computed by interpreting the input as
45410** an even number of unsigned 32-bit integers: x[0] through x[N].  The
45411** algorithm used for the checksum is as follows:
45412**
45413**   for i from 0 to n-1 step 2:
45414**     s0 += x[i] + s1;
45415**     s1 += x[i+1] + s0;
45416**   endfor
45417**
45418** Note that s0 and s1 are both weighted checksums using fibonacci weights
45419** in reverse order (the largest fibonacci weight occurs on the first element
45420** of the sequence being summed.)  The s1 value spans all 32-bit
45421** terms of the sequence whereas s0 omits the final term.
45422**
45423** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
45424** WAL is transferred into the database, then the database is VFS.xSync-ed.
45425** The VFS.xSync operations serve as write barriers - all writes launched
45426** before the xSync must complete before any write that launches after the
45427** xSync begins.
45428**
45429** After each checkpoint, the salt-1 value is incremented and the salt-2
45430** value is randomized.  This prevents old and new frames in the WAL from
45431** being considered valid at the same time and being checkpointing together
45432** following a crash.
45433**
45434** READER ALGORITHM
45435**
45436** To read a page from the database (call it page number P), a reader
45437** first checks the WAL to see if it contains page P.  If so, then the
45438** last valid instance of page P that is a followed by a commit frame
45439** or is a commit frame itself becomes the value read.  If the WAL
45440** contains no copies of page P that are valid and which are a commit
45441** frame or are followed by a commit frame, then page P is read from
45442** the database file.
45443**
45444** To start a read transaction, the reader records the index of the last
45445** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
45446** for all subsequent read operations.  New transactions can be appended
45447** to the WAL, but as long as the reader uses its original mxFrame value
45448** and ignores the newly appended content, it will see a consistent snapshot
45449** of the database from a single point in time.  This technique allows
45450** multiple concurrent readers to view different versions of the database
45451** content simultaneously.
45452**
45453** The reader algorithm in the previous paragraphs works correctly, but
45454** because frames for page P can appear anywhere within the WAL, the
45455** reader has to scan the entire WAL looking for page P frames.  If the
45456** WAL is large (multiple megabytes is typical) that scan can be slow,
45457** and read performance suffers.  To overcome this problem, a separate
45458** data structure called the wal-index is maintained to expedite the
45459** search for frames of a particular page.
45460**
45461** WAL-INDEX FORMAT
45462**
45463** Conceptually, the wal-index is shared memory, though VFS implementations
45464** might choose to implement the wal-index using a mmapped file.  Because
45465** the wal-index is shared memory, SQLite does not support journal_mode=WAL
45466** on a network filesystem.  All users of the database must be able to
45467** share memory.
45468**
45469** The wal-index is transient.  After a crash, the wal-index can (and should
45470** be) reconstructed from the original WAL file.  In fact, the VFS is required
45471** to either truncate or zero the header of the wal-index when the last
45472** connection to it closes.  Because the wal-index is transient, it can
45473** use an architecture-specific format; it does not have to be cross-platform.
45474** Hence, unlike the database and WAL file formats which store all values
45475** as big endian, the wal-index can store multi-byte values in the native
45476** byte order of the host computer.
45477**
45478** The purpose of the wal-index is to answer this question quickly:  Given
45479** a page number P, return the index of the last frame for page P in the WAL,
45480** or return NULL if there are no frames for page P in the WAL.
45481**
45482** The wal-index consists of a header region, followed by an one or
45483** more index blocks.
45484**
45485** The wal-index header contains the total number of frames within the WAL
45486** in the the mxFrame field.
45487**
45488** Each index block except for the first contains information on
45489** HASHTABLE_NPAGE frames. The first index block contains information on
45490** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
45491** HASHTABLE_NPAGE are selected so that together the wal-index header and
45492** first index block are the same size as all other index blocks in the
45493** wal-index.
45494**
45495** Each index block contains two sections, a page-mapping that contains the
45496** database page number associated with each wal frame, and a hash-table
45497** that allows readers to query an index block for a specific page number.
45498** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
45499** for the first index block) 32-bit page numbers. The first entry in the
45500** first index-block contains the database page number corresponding to the
45501** first frame in the WAL file. The first entry in the second index block
45502** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
45503** the log, and so on.
45504**
45505** The last index block in a wal-index usually contains less than the full
45506** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
45507** depending on the contents of the WAL file. This does not change the
45508** allocated size of the page-mapping array - the page-mapping array merely
45509** contains unused entries.
45510**
45511** Even without using the hash table, the last frame for page P
45512** can be found by scanning the page-mapping sections of each index block
45513** starting with the last index block and moving toward the first, and
45514** within each index block, starting at the end and moving toward the
45515** beginning.  The first entry that equals P corresponds to the frame
45516** holding the content for that page.
45517**
45518** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
45519** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
45520** hash table for each page number in the mapping section, so the hash
45521** table is never more than half full.  The expected number of collisions
45522** prior to finding a match is 1.  Each entry of the hash table is an
45523** 1-based index of an entry in the mapping section of the same
45524** index block.   Let K be the 1-based index of the largest entry in
45525** the mapping section.  (For index blocks other than the last, K will
45526** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
45527** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
45528** contain a value of 0.
45529**
45530** To look for page P in the hash table, first compute a hash iKey on
45531** P as follows:
45532**
45533**      iKey = (P * 383) % HASHTABLE_NSLOT
45534**
45535** Then start scanning entries of the hash table, starting with iKey
45536** (wrapping around to the beginning when the end of the hash table is
45537** reached) until an unused hash slot is found. Let the first unused slot
45538** be at index iUnused.  (iUnused might be less than iKey if there was
45539** wrap-around.) Because the hash table is never more than half full,
45540** the search is guaranteed to eventually hit an unused entry.  Let
45541** iMax be the value between iKey and iUnused, closest to iUnused,
45542** where aHash[iMax]==P.  If there is no iMax entry (if there exists
45543** no hash slot such that aHash[i]==p) then page P is not in the
45544** current index block.  Otherwise the iMax-th mapping entry of the
45545** current index block corresponds to the last entry that references
45546** page P.
45547**
45548** A hash search begins with the last index block and moves toward the
45549** first index block, looking for entries corresponding to page P.  On
45550** average, only two or three slots in each index block need to be
45551** examined in order to either find the last entry for page P, or to
45552** establish that no such entry exists in the block.  Each index block
45553** holds over 4000 entries.  So two or three index blocks are sufficient
45554** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
45555** comparisons (on average) suffice to either locate a frame in the
45556** WAL or to establish that the frame does not exist in the WAL.  This
45557** is much faster than scanning the entire 10MB WAL.
45558**
45559** Note that entries are added in order of increasing K.  Hence, one
45560** reader might be using some value K0 and a second reader that started
45561** at a later time (after additional transactions were added to the WAL
45562** and to the wal-index) might be using a different value K1, where K1>K0.
45563** Both readers can use the same hash table and mapping section to get
45564** the correct result.  There may be entries in the hash table with
45565** K>K0 but to the first reader, those entries will appear to be unused
45566** slots in the hash table and so the first reader will get an answer as
45567** if no values greater than K0 had ever been inserted into the hash table
45568** in the first place - which is what reader one wants.  Meanwhile, the
45569** second reader using K1 will see additional values that were inserted
45570** later, which is exactly what reader two wants.
45571**
45572** When a rollback occurs, the value of K is decreased. Hash table entries
45573** that correspond to frames greater than the new K value are removed
45574** from the hash table at this point.
45575*/
45576#ifndef SQLITE_OMIT_WAL
45577
45578
45579/*
45580** Trace output macros
45581*/
45582#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45583SQLITE_PRIVATE int sqlite3WalTrace = 0;
45584# define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
45585#else
45586# define WALTRACE(X)
45587#endif
45588
45589/*
45590** The maximum (and only) versions of the wal and wal-index formats
45591** that may be interpreted by this version of SQLite.
45592**
45593** If a client begins recovering a WAL file and finds that (a) the checksum
45594** values in the wal-header are correct and (b) the version field is not
45595** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
45596**
45597** Similarly, if a client successfully reads a wal-index header (i.e. the
45598** checksum test is successful) and finds that the version field is not
45599** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
45600** returns SQLITE_CANTOPEN.
45601*/
45602#define WAL_MAX_VERSION      3007000
45603#define WALINDEX_MAX_VERSION 3007000
45604
45605/*
45606** Indices of various locking bytes.   WAL_NREADER is the number
45607** of available reader locks and should be at least 3.
45608*/
45609#define WAL_WRITE_LOCK         0
45610#define WAL_ALL_BUT_WRITE      1
45611#define WAL_CKPT_LOCK          1
45612#define WAL_RECOVER_LOCK       2
45613#define WAL_READ_LOCK(I)       (3+(I))
45614#define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
45615
45616
45617/* Object declarations */
45618typedef struct WalIndexHdr WalIndexHdr;
45619typedef struct WalIterator WalIterator;
45620typedef struct WalCkptInfo WalCkptInfo;
45621
45622
45623/*
45624** The following object holds a copy of the wal-index header content.
45625**
45626** The actual header in the wal-index consists of two copies of this
45627** object.
45628**
45629** The szPage value can be any power of 2 between 512 and 32768, inclusive.
45630** Or it can be 1 to represent a 65536-byte page.  The latter case was
45631** added in 3.7.1 when support for 64K pages was added.
45632*/
45633struct WalIndexHdr {
45634  u32 iVersion;                   /* Wal-index version */
45635  u32 unused;                     /* Unused (padding) field */
45636  u32 iChange;                    /* Counter incremented each transaction */
45637  u8 isInit;                      /* 1 when initialized */
45638  u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
45639  u16 szPage;                     /* Database page size in bytes. 1==64K */
45640  u32 mxFrame;                    /* Index of last valid frame in the WAL */
45641  u32 nPage;                      /* Size of database in pages */
45642  u32 aFrameCksum[2];             /* Checksum of last frame in log */
45643  u32 aSalt[2];                   /* Two salt values copied from WAL header */
45644  u32 aCksum[2];                  /* Checksum over all prior fields */
45645};
45646
45647/*
45648** A copy of the following object occurs in the wal-index immediately
45649** following the second copy of the WalIndexHdr.  This object stores
45650** information used by checkpoint.
45651**
45652** nBackfill is the number of frames in the WAL that have been written
45653** back into the database. (We call the act of moving content from WAL to
45654** database "backfilling".)  The nBackfill number is never greater than
45655** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
45656** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
45657** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
45658** mxFrame back to zero when the WAL is reset.
45659**
45660** There is one entry in aReadMark[] for each reader lock.  If a reader
45661** holds read-lock K, then the value in aReadMark[K] is no greater than
45662** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
45663** for any aReadMark[] means that entry is unused.  aReadMark[0] is
45664** a special case; its value is never used and it exists as a place-holder
45665** to avoid having to offset aReadMark[] indexs by one.  Readers holding
45666** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
45667** directly from the database.
45668**
45669** The value of aReadMark[K] may only be changed by a thread that
45670** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
45671** aReadMark[K] cannot changed while there is a reader is using that mark
45672** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
45673**
45674** The checkpointer may only transfer frames from WAL to database where
45675** the frame numbers are less than or equal to every aReadMark[] that is
45676** in use (that is, every aReadMark[j] for which there is a corresponding
45677** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
45678** largest value and will increase an unused aReadMark[] to mxFrame if there
45679** is not already an aReadMark[] equal to mxFrame.  The exception to the
45680** previous sentence is when nBackfill equals mxFrame (meaning that everything
45681** in the WAL has been backfilled into the database) then new readers
45682** will choose aReadMark[0] which has value 0 and hence such reader will
45683** get all their all content directly from the database file and ignore
45684** the WAL.
45685**
45686** Writers normally append new frames to the end of the WAL.  However,
45687** if nBackfill equals mxFrame (meaning that all WAL content has been
45688** written back into the database) and if no readers are using the WAL
45689** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
45690** the writer will first "reset" the WAL back to the beginning and start
45691** writing new content beginning at frame 1.
45692**
45693** We assume that 32-bit loads are atomic and so no locks are needed in
45694** order to read from any aReadMark[] entries.
45695*/
45696struct WalCkptInfo {
45697  u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
45698  u32 aReadMark[WAL_NREADER];     /* Reader marks */
45699};
45700#define READMARK_NOT_USED  0xffffffff
45701
45702
45703/* A block of WALINDEX_LOCK_RESERVED bytes beginning at
45704** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
45705** only support mandatory file-locks, we do not read or write data
45706** from the region of the file on which locks are applied.
45707*/
45708#define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
45709#define WALINDEX_LOCK_RESERVED 16
45710#define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
45711
45712/* Size of header before each frame in wal */
45713#define WAL_FRAME_HDRSIZE 24
45714
45715/* Size of write ahead log header, including checksum. */
45716/* #define WAL_HDRSIZE 24 */
45717#define WAL_HDRSIZE 32
45718
45719/* WAL magic value. Either this value, or the same value with the least
45720** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
45721** big-endian format in the first 4 bytes of a WAL file.
45722**
45723** If the LSB is set, then the checksums for each frame within the WAL
45724** file are calculated by treating all data as an array of 32-bit
45725** big-endian words. Otherwise, they are calculated by interpreting
45726** all data as 32-bit little-endian words.
45727*/
45728#define WAL_MAGIC 0x377f0682
45729
45730/*
45731** Return the offset of frame iFrame in the write-ahead log file,
45732** assuming a database page size of szPage bytes. The offset returned
45733** is to the start of the write-ahead log frame-header.
45734*/
45735#define walFrameOffset(iFrame, szPage) (                               \
45736  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
45737)
45738
45739/*
45740** An open write-ahead log file is represented by an instance of the
45741** following object.
45742*/
45743struct Wal {
45744  sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
45745  sqlite3_file *pDbFd;       /* File handle for the database file */
45746  sqlite3_file *pWalFd;      /* File handle for WAL file */
45747  u32 iCallback;             /* Value to pass to log callback (or 0) */
45748  i64 mxWalSize;             /* Truncate WAL to this size upon reset */
45749  int nWiData;               /* Size of array apWiData */
45750  int szFirstBlock;          /* Size of first block written to WAL file */
45751  volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
45752  u32 szPage;                /* Database page size */
45753  i16 readLock;              /* Which read lock is being held.  -1 for none */
45754  u8 syncFlags;              /* Flags to use to sync header writes */
45755  u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
45756  u8 writeLock;              /* True if in a write transaction */
45757  u8 ckptLock;               /* True if holding a checkpoint lock */
45758  u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
45759  u8 truncateOnCommit;       /* True to truncate WAL file on commit */
45760  u8 syncHeader;             /* Fsync the WAL header if true */
45761  u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
45762  WalIndexHdr hdr;           /* Wal-index header for current transaction */
45763  const char *zWalName;      /* Name of WAL file */
45764  u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
45765#ifdef SQLITE_DEBUG
45766  u8 lockError;              /* True if a locking error has occurred */
45767#endif
45768};
45769
45770/*
45771** Candidate values for Wal.exclusiveMode.
45772*/
45773#define WAL_NORMAL_MODE     0
45774#define WAL_EXCLUSIVE_MODE  1
45775#define WAL_HEAPMEMORY_MODE 2
45776
45777/*
45778** Possible values for WAL.readOnly
45779*/
45780#define WAL_RDWR        0    /* Normal read/write connection */
45781#define WAL_RDONLY      1    /* The WAL file is readonly */
45782#define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
45783
45784/*
45785** Each page of the wal-index mapping contains a hash-table made up of
45786** an array of HASHTABLE_NSLOT elements of the following type.
45787*/
45788typedef u16 ht_slot;
45789
45790/*
45791** This structure is used to implement an iterator that loops through
45792** all frames in the WAL in database page order. Where two or more frames
45793** correspond to the same database page, the iterator visits only the
45794** frame most recently written to the WAL (in other words, the frame with
45795** the largest index).
45796**
45797** The internals of this structure are only accessed by:
45798**
45799**   walIteratorInit() - Create a new iterator,
45800**   walIteratorNext() - Step an iterator,
45801**   walIteratorFree() - Free an iterator.
45802**
45803** This functionality is used by the checkpoint code (see walCheckpoint()).
45804*/
45805struct WalIterator {
45806  int iPrior;                     /* Last result returned from the iterator */
45807  int nSegment;                   /* Number of entries in aSegment[] */
45808  struct WalSegment {
45809    int iNext;                    /* Next slot in aIndex[] not yet returned */
45810    ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
45811    u32 *aPgno;                   /* Array of page numbers. */
45812    int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
45813    int iZero;                    /* Frame number associated with aPgno[0] */
45814  } aSegment[1];                  /* One for every 32KB page in the wal-index */
45815};
45816
45817/*
45818** Define the parameters of the hash tables in the wal-index file. There
45819** is a hash-table following every HASHTABLE_NPAGE page numbers in the
45820** wal-index.
45821**
45822** Changing any of these constants will alter the wal-index format and
45823** create incompatibilities.
45824*/
45825#define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
45826#define HASHTABLE_HASH_1     383                  /* Should be prime */
45827#define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
45828
45829/*
45830** The block of page numbers associated with the first hash-table in a
45831** wal-index is smaller than usual. This is so that there is a complete
45832** hash-table on each aligned 32KB page of the wal-index.
45833*/
45834#define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
45835
45836/* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
45837#define WALINDEX_PGSZ   (                                         \
45838    sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
45839)
45840
45841/*
45842** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
45843** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
45844** numbered from zero.
45845**
45846** If this call is successful, *ppPage is set to point to the wal-index
45847** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
45848** then an SQLite error code is returned and *ppPage is set to 0.
45849*/
45850static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
45851  int rc = SQLITE_OK;
45852
45853  /* Enlarge the pWal->apWiData[] array if required */
45854  if( pWal->nWiData<=iPage ){
45855    int nByte = sizeof(u32*)*(iPage+1);
45856    volatile u32 **apNew;
45857    apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
45858    if( !apNew ){
45859      *ppPage = 0;
45860      return SQLITE_NOMEM;
45861    }
45862    memset((void*)&apNew[pWal->nWiData], 0,
45863           sizeof(u32*)*(iPage+1-pWal->nWiData));
45864    pWal->apWiData = apNew;
45865    pWal->nWiData = iPage+1;
45866  }
45867
45868  /* Request a pointer to the required page from the VFS */
45869  if( pWal->apWiData[iPage]==0 ){
45870    if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
45871      pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
45872      if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
45873    }else{
45874      rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
45875          pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
45876      );
45877      if( rc==SQLITE_READONLY ){
45878        pWal->readOnly |= WAL_SHM_RDONLY;
45879        rc = SQLITE_OK;
45880      }
45881    }
45882  }
45883
45884  *ppPage = pWal->apWiData[iPage];
45885  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
45886  return rc;
45887}
45888
45889/*
45890** Return a pointer to the WalCkptInfo structure in the wal-index.
45891*/
45892static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
45893  assert( pWal->nWiData>0 && pWal->apWiData[0] );
45894  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
45895}
45896
45897/*
45898** Return a pointer to the WalIndexHdr structure in the wal-index.
45899*/
45900static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
45901  assert( pWal->nWiData>0 && pWal->apWiData[0] );
45902  return (volatile WalIndexHdr*)pWal->apWiData[0];
45903}
45904
45905/*
45906** The argument to this macro must be of type u32. On a little-endian
45907** architecture, it returns the u32 value that results from interpreting
45908** the 4 bytes as a big-endian value. On a big-endian architecture, it
45909** returns the value that would be produced by intepreting the 4 bytes
45910** of the input value as a little-endian integer.
45911*/
45912#define BYTESWAP32(x) ( \
45913    (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
45914  + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
45915)
45916
45917/*
45918** Generate or extend an 8 byte checksum based on the data in
45919** array aByte[] and the initial values of aIn[0] and aIn[1] (or
45920** initial values of 0 and 0 if aIn==NULL).
45921**
45922** The checksum is written back into aOut[] before returning.
45923**
45924** nByte must be a positive multiple of 8.
45925*/
45926static void walChecksumBytes(
45927  int nativeCksum, /* True for native byte-order, false for non-native */
45928  u8 *a,           /* Content to be checksummed */
45929  int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
45930  const u32 *aIn,  /* Initial checksum value input */
45931  u32 *aOut        /* OUT: Final checksum value output */
45932){
45933  u32 s1, s2;
45934  u32 *aData = (u32 *)a;
45935  u32 *aEnd = (u32 *)&a[nByte];
45936
45937  if( aIn ){
45938    s1 = aIn[0];
45939    s2 = aIn[1];
45940  }else{
45941    s1 = s2 = 0;
45942  }
45943
45944  assert( nByte>=8 );
45945  assert( (nByte&0x00000007)==0 );
45946
45947  if( nativeCksum ){
45948    do {
45949      s1 += *aData++ + s2;
45950      s2 += *aData++ + s1;
45951    }while( aData<aEnd );
45952  }else{
45953    do {
45954      s1 += BYTESWAP32(aData[0]) + s2;
45955      s2 += BYTESWAP32(aData[1]) + s1;
45956      aData += 2;
45957    }while( aData<aEnd );
45958  }
45959
45960  aOut[0] = s1;
45961  aOut[1] = s2;
45962}
45963
45964static void walShmBarrier(Wal *pWal){
45965  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
45966    sqlite3OsShmBarrier(pWal->pDbFd);
45967  }
45968}
45969
45970/*
45971** Write the header information in pWal->hdr into the wal-index.
45972**
45973** The checksum on pWal->hdr is updated before it is written.
45974*/
45975static void walIndexWriteHdr(Wal *pWal){
45976  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
45977  const int nCksum = offsetof(WalIndexHdr, aCksum);
45978
45979  assert( pWal->writeLock );
45980  pWal->hdr.isInit = 1;
45981  pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
45982  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
45983  memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
45984  walShmBarrier(pWal);
45985  memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
45986}
45987
45988/*
45989** This function encodes a single frame header and writes it to a buffer
45990** supplied by the caller. A frame-header is made up of a series of
45991** 4-byte big-endian integers, as follows:
45992**
45993**     0: Page number.
45994**     4: For commit records, the size of the database image in pages
45995**        after the commit. For all other records, zero.
45996**     8: Salt-1 (copied from the wal-header)
45997**    12: Salt-2 (copied from the wal-header)
45998**    16: Checksum-1.
45999**    20: Checksum-2.
46000*/
46001static void walEncodeFrame(
46002  Wal *pWal,                      /* The write-ahead log */
46003  u32 iPage,                      /* Database page number for frame */
46004  u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
46005  u8 *aData,                      /* Pointer to page data */
46006  u8 *aFrame                      /* OUT: Write encoded frame here */
46007){
46008  int nativeCksum;                /* True for native byte-order checksums */
46009  u32 *aCksum = pWal->hdr.aFrameCksum;
46010  assert( WAL_FRAME_HDRSIZE==24 );
46011  sqlite3Put4byte(&aFrame[0], iPage);
46012  sqlite3Put4byte(&aFrame[4], nTruncate);
46013  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
46014
46015  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46016  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46017  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46018
46019  sqlite3Put4byte(&aFrame[16], aCksum[0]);
46020  sqlite3Put4byte(&aFrame[20], aCksum[1]);
46021}
46022
46023/*
46024** Check to see if the frame with header in aFrame[] and content
46025** in aData[] is valid.  If it is a valid frame, fill *piPage and
46026** *pnTruncate and return true.  Return if the frame is not valid.
46027*/
46028static int walDecodeFrame(
46029  Wal *pWal,                      /* The write-ahead log */
46030  u32 *piPage,                    /* OUT: Database page number for frame */
46031  u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
46032  u8 *aData,                      /* Pointer to page data (for checksum) */
46033  u8 *aFrame                      /* Frame data */
46034){
46035  int nativeCksum;                /* True for native byte-order checksums */
46036  u32 *aCksum = pWal->hdr.aFrameCksum;
46037  u32 pgno;                       /* Page number of the frame */
46038  assert( WAL_FRAME_HDRSIZE==24 );
46039
46040  /* A frame is only valid if the salt values in the frame-header
46041  ** match the salt values in the wal-header.
46042  */
46043  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
46044    return 0;
46045  }
46046
46047  /* A frame is only valid if the page number is creater than zero.
46048  */
46049  pgno = sqlite3Get4byte(&aFrame[0]);
46050  if( pgno==0 ){
46051    return 0;
46052  }
46053
46054  /* A frame is only valid if a checksum of the WAL header,
46055  ** all prior frams, the first 16 bytes of this frame-header,
46056  ** and the frame-data matches the checksum in the last 8
46057  ** bytes of this frame-header.
46058  */
46059  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46060  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46061  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46062  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
46063   || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
46064  ){
46065    /* Checksum failed. */
46066    return 0;
46067  }
46068
46069  /* If we reach this point, the frame is valid.  Return the page number
46070  ** and the new database size.
46071  */
46072  *piPage = pgno;
46073  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
46074  return 1;
46075}
46076
46077
46078#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46079/*
46080** Names of locks.  This routine is used to provide debugging output and is not
46081** a part of an ordinary build.
46082*/
46083static const char *walLockName(int lockIdx){
46084  if( lockIdx==WAL_WRITE_LOCK ){
46085    return "WRITE-LOCK";
46086  }else if( lockIdx==WAL_CKPT_LOCK ){
46087    return "CKPT-LOCK";
46088  }else if( lockIdx==WAL_RECOVER_LOCK ){
46089    return "RECOVER-LOCK";
46090  }else{
46091    static char zName[15];
46092    sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
46093                     lockIdx-WAL_READ_LOCK(0));
46094    return zName;
46095  }
46096}
46097#endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
46098
46099
46100/*
46101** Set or release locks on the WAL.  Locks are either shared or exclusive.
46102** A lock cannot be moved directly between shared and exclusive - it must go
46103** through the unlocked state first.
46104**
46105** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
46106*/
46107static int walLockShared(Wal *pWal, int lockIdx){
46108  int rc;
46109  if( pWal->exclusiveMode ) return SQLITE_OK;
46110  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46111                        SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
46112  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
46113            walLockName(lockIdx), rc ? "failed" : "ok"));
46114  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46115  return rc;
46116}
46117static void walUnlockShared(Wal *pWal, int lockIdx){
46118  if( pWal->exclusiveMode ) return;
46119  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46120                         SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
46121  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
46122}
46123static int walLockExclusive(Wal *pWal, int lockIdx, int n){
46124  int rc;
46125  if( pWal->exclusiveMode ) return SQLITE_OK;
46126  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46127                        SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
46128  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
46129            walLockName(lockIdx), n, rc ? "failed" : "ok"));
46130  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46131  return rc;
46132}
46133static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
46134  if( pWal->exclusiveMode ) return;
46135  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46136                         SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
46137  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
46138             walLockName(lockIdx), n));
46139}
46140
46141/*
46142** Compute a hash on a page number.  The resulting hash value must land
46143** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
46144** the hash to the next value in the event of a collision.
46145*/
46146static int walHash(u32 iPage){
46147  assert( iPage>0 );
46148  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
46149  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
46150}
46151static int walNextHash(int iPriorHash){
46152  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
46153}
46154
46155/*
46156** Return pointers to the hash table and page number array stored on
46157** page iHash of the wal-index. The wal-index is broken into 32KB pages
46158** numbered starting from 0.
46159**
46160** Set output variable *paHash to point to the start of the hash table
46161** in the wal-index file. Set *piZero to one less than the frame
46162** number of the first frame indexed by this hash table. If a
46163** slot in the hash table is set to N, it refers to frame number
46164** (*piZero+N) in the log.
46165**
46166** Finally, set *paPgno so that *paPgno[1] is the page number of the
46167** first frame indexed by the hash table, frame (*piZero+1).
46168*/
46169static int walHashGet(
46170  Wal *pWal,                      /* WAL handle */
46171  int iHash,                      /* Find the iHash'th table */
46172  volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
46173  volatile u32 **paPgno,          /* OUT: Pointer to page number array */
46174  u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
46175){
46176  int rc;                         /* Return code */
46177  volatile u32 *aPgno;
46178
46179  rc = walIndexPage(pWal, iHash, &aPgno);
46180  assert( rc==SQLITE_OK || iHash>0 );
46181
46182  if( rc==SQLITE_OK ){
46183    u32 iZero;
46184    volatile ht_slot *aHash;
46185
46186    aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
46187    if( iHash==0 ){
46188      aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
46189      iZero = 0;
46190    }else{
46191      iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
46192    }
46193
46194    *paPgno = &aPgno[-1];
46195    *paHash = aHash;
46196    *piZero = iZero;
46197  }
46198  return rc;
46199}
46200
46201/*
46202** Return the number of the wal-index page that contains the hash-table
46203** and page-number array that contain entries corresponding to WAL frame
46204** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
46205** are numbered starting from 0.
46206*/
46207static int walFramePage(u32 iFrame){
46208  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
46209  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
46210       && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
46211       && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
46212       && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
46213       && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
46214  );
46215  return iHash;
46216}
46217
46218/*
46219** Return the page number associated with frame iFrame in this WAL.
46220*/
46221static u32 walFramePgno(Wal *pWal, u32 iFrame){
46222  int iHash = walFramePage(iFrame);
46223  if( iHash==0 ){
46224    return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
46225  }
46226  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
46227}
46228
46229/*
46230** Remove entries from the hash table that point to WAL slots greater
46231** than pWal->hdr.mxFrame.
46232**
46233** This function is called whenever pWal->hdr.mxFrame is decreased due
46234** to a rollback or savepoint.
46235**
46236** At most only the hash table containing pWal->hdr.mxFrame needs to be
46237** updated.  Any later hash tables will be automatically cleared when
46238** pWal->hdr.mxFrame advances to the point where those hash tables are
46239** actually needed.
46240*/
46241static void walCleanupHash(Wal *pWal){
46242  volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
46243  volatile u32 *aPgno = 0;        /* Page number array for hash table */
46244  u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
46245  int iLimit = 0;                 /* Zero values greater than this */
46246  int nByte;                      /* Number of bytes to zero in aPgno[] */
46247  int i;                          /* Used to iterate through aHash[] */
46248
46249  assert( pWal->writeLock );
46250  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
46251  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
46252  testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
46253
46254  if( pWal->hdr.mxFrame==0 ) return;
46255
46256  /* Obtain pointers to the hash-table and page-number array containing
46257  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
46258  ** that the page said hash-table and array reside on is already mapped.
46259  */
46260  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
46261  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
46262  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
46263
46264  /* Zero all hash-table entries that correspond to frame numbers greater
46265  ** than pWal->hdr.mxFrame.
46266  */
46267  iLimit = pWal->hdr.mxFrame - iZero;
46268  assert( iLimit>0 );
46269  for(i=0; i<HASHTABLE_NSLOT; i++){
46270    if( aHash[i]>iLimit ){
46271      aHash[i] = 0;
46272    }
46273  }
46274
46275  /* Zero the entries in the aPgno array that correspond to frames with
46276  ** frame numbers greater than pWal->hdr.mxFrame.
46277  */
46278  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
46279  memset((void *)&aPgno[iLimit+1], 0, nByte);
46280
46281#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46282  /* Verify that the every entry in the mapping region is still reachable
46283  ** via the hash table even after the cleanup.
46284  */
46285  if( iLimit ){
46286    int i;           /* Loop counter */
46287    int iKey;        /* Hash key */
46288    for(i=1; i<=iLimit; i++){
46289      for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46290        if( aHash[iKey]==i ) break;
46291      }
46292      assert( aHash[iKey]==i );
46293    }
46294  }
46295#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46296}
46297
46298
46299/*
46300** Set an entry in the wal-index that will map database page number
46301** pPage into WAL frame iFrame.
46302*/
46303static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
46304  int rc;                         /* Return code */
46305  u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
46306  volatile u32 *aPgno = 0;        /* Page number array */
46307  volatile ht_slot *aHash = 0;    /* Hash table */
46308
46309  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
46310
46311  /* Assuming the wal-index file was successfully mapped, populate the
46312  ** page number array and hash table entry.
46313  */
46314  if( rc==SQLITE_OK ){
46315    int iKey;                     /* Hash table key */
46316    int idx;                      /* Value to write to hash-table slot */
46317    int nCollide;                 /* Number of hash collisions */
46318
46319    idx = iFrame - iZero;
46320    assert( idx <= HASHTABLE_NSLOT/2 + 1 );
46321
46322    /* If this is the first entry to be added to this hash-table, zero the
46323    ** entire hash table and aPgno[] array before proceding.
46324    */
46325    if( idx==1 ){
46326      int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
46327      memset((void*)&aPgno[1], 0, nByte);
46328    }
46329
46330    /* If the entry in aPgno[] is already set, then the previous writer
46331    ** must have exited unexpectedly in the middle of a transaction (after
46332    ** writing one or more dirty pages to the WAL to free up memory).
46333    ** Remove the remnants of that writers uncommitted transaction from
46334    ** the hash-table before writing any new entries.
46335    */
46336    if( aPgno[idx] ){
46337      walCleanupHash(pWal);
46338      assert( !aPgno[idx] );
46339    }
46340
46341    /* Write the aPgno[] array entry and the hash-table slot. */
46342    nCollide = idx;
46343    for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
46344      if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
46345    }
46346    aPgno[idx] = iPage;
46347    aHash[iKey] = (ht_slot)idx;
46348
46349#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46350    /* Verify that the number of entries in the hash table exactly equals
46351    ** the number of entries in the mapping region.
46352    */
46353    {
46354      int i;           /* Loop counter */
46355      int nEntry = 0;  /* Number of entries in the hash table */
46356      for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
46357      assert( nEntry==idx );
46358    }
46359
46360    /* Verify that the every entry in the mapping region is reachable
46361    ** via the hash table.  This turns out to be a really, really expensive
46362    ** thing to check, so only do this occasionally - not on every
46363    ** iteration.
46364    */
46365    if( (idx&0x3ff)==0 ){
46366      int i;           /* Loop counter */
46367      for(i=1; i<=idx; i++){
46368        for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46369          if( aHash[iKey]==i ) break;
46370        }
46371        assert( aHash[iKey]==i );
46372      }
46373    }
46374#endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46375  }
46376
46377
46378  return rc;
46379}
46380
46381
46382/*
46383** Recover the wal-index by reading the write-ahead log file.
46384**
46385** This routine first tries to establish an exclusive lock on the
46386** wal-index to prevent other threads/processes from doing anything
46387** with the WAL or wal-index while recovery is running.  The
46388** WAL_RECOVER_LOCK is also held so that other threads will know
46389** that this thread is running recovery.  If unable to establish
46390** the necessary locks, this routine returns SQLITE_BUSY.
46391*/
46392static int walIndexRecover(Wal *pWal){
46393  int rc;                         /* Return Code */
46394  i64 nSize;                      /* Size of log file */
46395  u32 aFrameCksum[2] = {0, 0};
46396  int iLock;                      /* Lock offset to lock for checkpoint */
46397  int nLock;                      /* Number of locks to hold */
46398
46399  /* Obtain an exclusive lock on all byte in the locking range not already
46400  ** locked by the caller. The caller is guaranteed to have locked the
46401  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
46402  ** If successful, the same bytes that are locked here are unlocked before
46403  ** this function returns.
46404  */
46405  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
46406  assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
46407  assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
46408  assert( pWal->writeLock );
46409  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
46410  nLock = SQLITE_SHM_NLOCK - iLock;
46411  rc = walLockExclusive(pWal, iLock, nLock);
46412  if( rc ){
46413    return rc;
46414  }
46415  WALTRACE(("WAL%p: recovery begin...\n", pWal));
46416
46417  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46418
46419  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
46420  if( rc!=SQLITE_OK ){
46421    goto recovery_error;
46422  }
46423
46424  if( nSize>WAL_HDRSIZE ){
46425    u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
46426    u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
46427    int szFrame;                  /* Number of bytes in buffer aFrame[] */
46428    u8 *aData;                    /* Pointer to data part of aFrame buffer */
46429    int iFrame;                   /* Index of last frame read */
46430    i64 iOffset;                  /* Next offset to read from log file */
46431    int szPage;                   /* Page size according to the log */
46432    u32 magic;                    /* Magic value read from WAL header */
46433    u32 version;                  /* Magic value read from WAL header */
46434    int isValid;                  /* True if this frame is valid */
46435
46436    /* Read in the WAL header. */
46437    rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
46438    if( rc!=SQLITE_OK ){
46439      goto recovery_error;
46440    }
46441
46442    /* If the database page size is not a power of two, or is greater than
46443    ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
46444    ** data. Similarly, if the 'magic' value is invalid, ignore the whole
46445    ** WAL file.
46446    */
46447    magic = sqlite3Get4byte(&aBuf[0]);
46448    szPage = sqlite3Get4byte(&aBuf[8]);
46449    if( (magic&0xFFFFFFFE)!=WAL_MAGIC
46450     || szPage&(szPage-1)
46451     || szPage>SQLITE_MAX_PAGE_SIZE
46452     || szPage<512
46453    ){
46454      goto finished;
46455    }
46456    pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
46457    pWal->szPage = szPage;
46458    pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
46459    memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
46460
46461    /* Verify that the WAL header checksum is correct */
46462    walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
46463        aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
46464    );
46465    if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
46466     || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
46467    ){
46468      goto finished;
46469    }
46470
46471    /* Verify that the version number on the WAL format is one that
46472    ** are able to understand */
46473    version = sqlite3Get4byte(&aBuf[4]);
46474    if( version!=WAL_MAX_VERSION ){
46475      rc = SQLITE_CANTOPEN_BKPT;
46476      goto finished;
46477    }
46478
46479    /* Malloc a buffer to read frames into. */
46480    szFrame = szPage + WAL_FRAME_HDRSIZE;
46481    aFrame = (u8 *)sqlite3_malloc(szFrame);
46482    if( !aFrame ){
46483      rc = SQLITE_NOMEM;
46484      goto recovery_error;
46485    }
46486    aData = &aFrame[WAL_FRAME_HDRSIZE];
46487
46488    /* Read all frames from the log file. */
46489    iFrame = 0;
46490    for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
46491      u32 pgno;                   /* Database page number for frame */
46492      u32 nTruncate;              /* dbsize field from frame header */
46493
46494      /* Read and decode the next log frame. */
46495      iFrame++;
46496      rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
46497      if( rc!=SQLITE_OK ) break;
46498      isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
46499      if( !isValid ) break;
46500      rc = walIndexAppend(pWal, iFrame, pgno);
46501      if( rc!=SQLITE_OK ) break;
46502
46503      /* If nTruncate is non-zero, this is a commit record. */
46504      if( nTruncate ){
46505        pWal->hdr.mxFrame = iFrame;
46506        pWal->hdr.nPage = nTruncate;
46507        pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46508        testcase( szPage<=32768 );
46509        testcase( szPage>=65536 );
46510        aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
46511        aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
46512      }
46513    }
46514
46515    sqlite3_free(aFrame);
46516  }
46517
46518finished:
46519  if( rc==SQLITE_OK ){
46520    volatile WalCkptInfo *pInfo;
46521    int i;
46522    pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
46523    pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
46524    walIndexWriteHdr(pWal);
46525
46526    /* Reset the checkpoint-header. This is safe because this thread is
46527    ** currently holding locks that exclude all other readers, writers and
46528    ** checkpointers.
46529    */
46530    pInfo = walCkptInfo(pWal);
46531    pInfo->nBackfill = 0;
46532    pInfo->aReadMark[0] = 0;
46533    for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46534
46535    /* If more than one frame was recovered from the log file, report an
46536    ** event via sqlite3_log(). This is to help with identifying performance
46537    ** problems caused by applications routinely shutting down without
46538    ** checkpointing the log file.
46539    */
46540    if( pWal->hdr.nPage ){
46541      sqlite3_log(SQLITE_OK, "Recovered %d frames from WAL file %s",
46542          pWal->hdr.nPage, pWal->zWalName
46543      );
46544    }
46545  }
46546
46547recovery_error:
46548  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
46549  walUnlockExclusive(pWal, iLock, nLock);
46550  return rc;
46551}
46552
46553/*
46554** Close an open wal-index.
46555*/
46556static void walIndexClose(Wal *pWal, int isDelete){
46557  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46558    int i;
46559    for(i=0; i<pWal->nWiData; i++){
46560      sqlite3_free((void *)pWal->apWiData[i]);
46561      pWal->apWiData[i] = 0;
46562    }
46563  }else{
46564    sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
46565  }
46566}
46567
46568/*
46569** Open a connection to the WAL file zWalName. The database file must
46570** already be opened on connection pDbFd. The buffer that zWalName points
46571** to must remain valid for the lifetime of the returned Wal* handle.
46572**
46573** A SHARED lock should be held on the database file when this function
46574** is called. The purpose of this SHARED lock is to prevent any other
46575** client from unlinking the WAL or wal-index file. If another process
46576** were to do this just after this client opened one of these files, the
46577** system would be badly broken.
46578**
46579** If the log file is successfully opened, SQLITE_OK is returned and
46580** *ppWal is set to point to a new WAL handle. If an error occurs,
46581** an SQLite error code is returned and *ppWal is left unmodified.
46582*/
46583SQLITE_PRIVATE int sqlite3WalOpen(
46584  sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
46585  sqlite3_file *pDbFd,            /* The open database file */
46586  const char *zWalName,           /* Name of the WAL file */
46587  int bNoShm,                     /* True to run in heap-memory mode */
46588  i64 mxWalSize,                  /* Truncate WAL to this size on reset */
46589  Wal **ppWal                     /* OUT: Allocated Wal handle */
46590){
46591  int rc;                         /* Return Code */
46592  Wal *pRet;                      /* Object to allocate and return */
46593  int flags;                      /* Flags passed to OsOpen() */
46594
46595  assert( zWalName && zWalName[0] );
46596  assert( pDbFd );
46597
46598  /* In the amalgamation, the os_unix.c and os_win.c source files come before
46599  ** this source file.  Verify that the #defines of the locking byte offsets
46600  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
46601  */
46602#ifdef WIN_SHM_BASE
46603  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
46604#endif
46605#ifdef UNIX_SHM_BASE
46606  assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
46607#endif
46608
46609
46610  /* Allocate an instance of struct Wal to return. */
46611  *ppWal = 0;
46612  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
46613  if( !pRet ){
46614    return SQLITE_NOMEM;
46615  }
46616
46617  pRet->pVfs = pVfs;
46618  pRet->pWalFd = (sqlite3_file *)&pRet[1];
46619  pRet->pDbFd = pDbFd;
46620  pRet->readLock = -1;
46621  pRet->mxWalSize = mxWalSize;
46622  pRet->zWalName = zWalName;
46623  pRet->syncHeader = 1;
46624  pRet->padToSectorBoundary = 1;
46625  pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
46626
46627  /* Open file handle on the write-ahead log file. */
46628  flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
46629  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
46630  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
46631    pRet->readOnly = WAL_RDONLY;
46632  }
46633
46634  if( rc!=SQLITE_OK ){
46635    walIndexClose(pRet, 0);
46636    sqlite3OsClose(pRet->pWalFd);
46637    sqlite3_free(pRet);
46638  }else{
46639    int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
46640    if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
46641    if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
46642      pRet->padToSectorBoundary = 0;
46643    }
46644    *ppWal = pRet;
46645    WALTRACE(("WAL%d: opened\n", pRet));
46646  }
46647  return rc;
46648}
46649
46650/*
46651** Change the size to which the WAL file is trucated on each reset.
46652*/
46653SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
46654  if( pWal ) pWal->mxWalSize = iLimit;
46655}
46656
46657/*
46658** Find the smallest page number out of all pages held in the WAL that
46659** has not been returned by any prior invocation of this method on the
46660** same WalIterator object.   Write into *piFrame the frame index where
46661** that page was last written into the WAL.  Write into *piPage the page
46662** number.
46663**
46664** Return 0 on success.  If there are no pages in the WAL with a page
46665** number larger than *piPage, then return 1.
46666*/
46667static int walIteratorNext(
46668  WalIterator *p,               /* Iterator */
46669  u32 *piPage,                  /* OUT: The page number of the next page */
46670  u32 *piFrame                  /* OUT: Wal frame index of next page */
46671){
46672  u32 iMin;                     /* Result pgno must be greater than iMin */
46673  u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
46674  int i;                        /* For looping through segments */
46675
46676  iMin = p->iPrior;
46677  assert( iMin<0xffffffff );
46678  for(i=p->nSegment-1; i>=0; i--){
46679    struct WalSegment *pSegment = &p->aSegment[i];
46680    while( pSegment->iNext<pSegment->nEntry ){
46681      u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
46682      if( iPg>iMin ){
46683        if( iPg<iRet ){
46684          iRet = iPg;
46685          *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
46686        }
46687        break;
46688      }
46689      pSegment->iNext++;
46690    }
46691  }
46692
46693  *piPage = p->iPrior = iRet;
46694  return (iRet==0xFFFFFFFF);
46695}
46696
46697/*
46698** This function merges two sorted lists into a single sorted list.
46699**
46700** aLeft[] and aRight[] are arrays of indices.  The sort key is
46701** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
46702** is guaranteed for all J<K:
46703**
46704**        aContent[aLeft[J]] < aContent[aLeft[K]]
46705**        aContent[aRight[J]] < aContent[aRight[K]]
46706**
46707** This routine overwrites aRight[] with a new (probably longer) sequence
46708** of indices such that the aRight[] contains every index that appears in
46709** either aLeft[] or the old aRight[] and such that the second condition
46710** above is still met.
46711**
46712** The aContent[aLeft[X]] values will be unique for all X.  And the
46713** aContent[aRight[X]] values will be unique too.  But there might be
46714** one or more combinations of X and Y such that
46715**
46716**      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
46717**
46718** When that happens, omit the aLeft[X] and use the aRight[Y] index.
46719*/
46720static void walMerge(
46721  const u32 *aContent,            /* Pages in wal - keys for the sort */
46722  ht_slot *aLeft,                 /* IN: Left hand input list */
46723  int nLeft,                      /* IN: Elements in array *paLeft */
46724  ht_slot **paRight,              /* IN/OUT: Right hand input list */
46725  int *pnRight,                   /* IN/OUT: Elements in *paRight */
46726  ht_slot *aTmp                   /* Temporary buffer */
46727){
46728  int iLeft = 0;                  /* Current index in aLeft */
46729  int iRight = 0;                 /* Current index in aRight */
46730  int iOut = 0;                   /* Current index in output buffer */
46731  int nRight = *pnRight;
46732  ht_slot *aRight = *paRight;
46733
46734  assert( nLeft>0 && nRight>0 );
46735  while( iRight<nRight || iLeft<nLeft ){
46736    ht_slot logpage;
46737    Pgno dbpage;
46738
46739    if( (iLeft<nLeft)
46740     && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
46741    ){
46742      logpage = aLeft[iLeft++];
46743    }else{
46744      logpage = aRight[iRight++];
46745    }
46746    dbpage = aContent[logpage];
46747
46748    aTmp[iOut++] = logpage;
46749    if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
46750
46751    assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
46752    assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
46753  }
46754
46755  *paRight = aLeft;
46756  *pnRight = iOut;
46757  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
46758}
46759
46760/*
46761** Sort the elements in list aList using aContent[] as the sort key.
46762** Remove elements with duplicate keys, preferring to keep the
46763** larger aList[] values.
46764**
46765** The aList[] entries are indices into aContent[].  The values in
46766** aList[] are to be sorted so that for all J<K:
46767**
46768**      aContent[aList[J]] < aContent[aList[K]]
46769**
46770** For any X and Y such that
46771**
46772**      aContent[aList[X]] == aContent[aList[Y]]
46773**
46774** Keep the larger of the two values aList[X] and aList[Y] and discard
46775** the smaller.
46776*/
46777static void walMergesort(
46778  const u32 *aContent,            /* Pages in wal */
46779  ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
46780  ht_slot *aList,                 /* IN/OUT: List to sort */
46781  int *pnList                     /* IN/OUT: Number of elements in aList[] */
46782){
46783  struct Sublist {
46784    int nList;                    /* Number of elements in aList */
46785    ht_slot *aList;               /* Pointer to sub-list content */
46786  };
46787
46788  const int nList = *pnList;      /* Size of input list */
46789  int nMerge = 0;                 /* Number of elements in list aMerge */
46790  ht_slot *aMerge = 0;            /* List to be merged */
46791  int iList;                      /* Index into input list */
46792  int iSub = 0;                   /* Index into aSub array */
46793  struct Sublist aSub[13];        /* Array of sub-lists */
46794
46795  memset(aSub, 0, sizeof(aSub));
46796  assert( nList<=HASHTABLE_NPAGE && nList>0 );
46797  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
46798
46799  for(iList=0; iList<nList; iList++){
46800    nMerge = 1;
46801    aMerge = &aList[iList];
46802    for(iSub=0; iList & (1<<iSub); iSub++){
46803      struct Sublist *p = &aSub[iSub];
46804      assert( p->aList && p->nList<=(1<<iSub) );
46805      assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
46806      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
46807    }
46808    aSub[iSub].aList = aMerge;
46809    aSub[iSub].nList = nMerge;
46810  }
46811
46812  for(iSub++; iSub<ArraySize(aSub); iSub++){
46813    if( nList & (1<<iSub) ){
46814      struct Sublist *p = &aSub[iSub];
46815      assert( p->nList<=(1<<iSub) );
46816      assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
46817      walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
46818    }
46819  }
46820  assert( aMerge==aList );
46821  *pnList = nMerge;
46822
46823#ifdef SQLITE_DEBUG
46824  {
46825    int i;
46826    for(i=1; i<*pnList; i++){
46827      assert( aContent[aList[i]] > aContent[aList[i-1]] );
46828    }
46829  }
46830#endif
46831}
46832
46833/*
46834** Free an iterator allocated by walIteratorInit().
46835*/
46836static void walIteratorFree(WalIterator *p){
46837  sqlite3ScratchFree(p);
46838}
46839
46840/*
46841** Construct a WalInterator object that can be used to loop over all
46842** pages in the WAL in ascending order. The caller must hold the checkpoint
46843** lock.
46844**
46845** On success, make *pp point to the newly allocated WalInterator object
46846** return SQLITE_OK. Otherwise, return an error code. If this routine
46847** returns an error, the value of *pp is undefined.
46848**
46849** The calling routine should invoke walIteratorFree() to destroy the
46850** WalIterator object when it has finished with it.
46851*/
46852static int walIteratorInit(Wal *pWal, WalIterator **pp){
46853  WalIterator *p;                 /* Return value */
46854  int nSegment;                   /* Number of segments to merge */
46855  u32 iLast;                      /* Last frame in log */
46856  int nByte;                      /* Number of bytes to allocate */
46857  int i;                          /* Iterator variable */
46858  ht_slot *aTmp;                  /* Temp space used by merge-sort */
46859  int rc = SQLITE_OK;             /* Return Code */
46860
46861  /* This routine only runs while holding the checkpoint lock. And
46862  ** it only runs if there is actually content in the log (mxFrame>0).
46863  */
46864  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
46865  iLast = pWal->hdr.mxFrame;
46866
46867  /* Allocate space for the WalIterator object. */
46868  nSegment = walFramePage(iLast) + 1;
46869  nByte = sizeof(WalIterator)
46870        + (nSegment-1)*sizeof(struct WalSegment)
46871        + iLast*sizeof(ht_slot);
46872  p = (WalIterator *)sqlite3ScratchMalloc(nByte);
46873  if( !p ){
46874    return SQLITE_NOMEM;
46875  }
46876  memset(p, 0, nByte);
46877  p->nSegment = nSegment;
46878
46879  /* Allocate temporary space used by the merge-sort routine. This block
46880  ** of memory will be freed before this function returns.
46881  */
46882  aTmp = (ht_slot *)sqlite3ScratchMalloc(
46883      sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
46884  );
46885  if( !aTmp ){
46886    rc = SQLITE_NOMEM;
46887  }
46888
46889  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
46890    volatile ht_slot *aHash;
46891    u32 iZero;
46892    volatile u32 *aPgno;
46893
46894    rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
46895    if( rc==SQLITE_OK ){
46896      int j;                      /* Counter variable */
46897      int nEntry;                 /* Number of entries in this segment */
46898      ht_slot *aIndex;            /* Sorted index for this segment */
46899
46900      aPgno++;
46901      if( (i+1)==nSegment ){
46902        nEntry = (int)(iLast - iZero);
46903      }else{
46904        nEntry = (int)((u32*)aHash - (u32*)aPgno);
46905      }
46906      aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
46907      iZero++;
46908
46909      for(j=0; j<nEntry; j++){
46910        aIndex[j] = (ht_slot)j;
46911      }
46912      walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
46913      p->aSegment[i].iZero = iZero;
46914      p->aSegment[i].nEntry = nEntry;
46915      p->aSegment[i].aIndex = aIndex;
46916      p->aSegment[i].aPgno = (u32 *)aPgno;
46917    }
46918  }
46919  sqlite3ScratchFree(aTmp);
46920
46921  if( rc!=SQLITE_OK ){
46922    walIteratorFree(p);
46923  }
46924  *pp = p;
46925  return rc;
46926}
46927
46928/*
46929** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
46930** n. If the attempt fails and parameter xBusy is not NULL, then it is a
46931** busy-handler function. Invoke it and retry the lock until either the
46932** lock is successfully obtained or the busy-handler returns 0.
46933*/
46934static int walBusyLock(
46935  Wal *pWal,                      /* WAL connection */
46936  int (*xBusy)(void*),            /* Function to call when busy */
46937  void *pBusyArg,                 /* Context argument for xBusyHandler */
46938  int lockIdx,                    /* Offset of first byte to lock */
46939  int n                           /* Number of bytes to lock */
46940){
46941  int rc;
46942  do {
46943    rc = walLockExclusive(pWal, lockIdx, n);
46944  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
46945  return rc;
46946}
46947
46948/*
46949** The cache of the wal-index header must be valid to call this function.
46950** Return the page-size in bytes used by the database.
46951*/
46952static int walPagesize(Wal *pWal){
46953  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
46954}
46955
46956/*
46957** Copy as much content as we can from the WAL back into the database file
46958** in response to an sqlite3_wal_checkpoint() request or the equivalent.
46959**
46960** The amount of information copies from WAL to database might be limited
46961** by active readers.  This routine will never overwrite a database page
46962** that a concurrent reader might be using.
46963**
46964** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
46965** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if
46966** checkpoints are always run by a background thread or background
46967** process, foreground threads will never block on a lengthy fsync call.
46968**
46969** Fsync is called on the WAL before writing content out of the WAL and
46970** into the database.  This ensures that if the new content is persistent
46971** in the WAL and can be recovered following a power-loss or hard reset.
46972**
46973** Fsync is also called on the database file if (and only if) the entire
46974** WAL content is copied into the database file.  This second fsync makes
46975** it safe to delete the WAL since the new content will persist in the
46976** database file.
46977**
46978** This routine uses and updates the nBackfill field of the wal-index header.
46979** This is the only routine tha will increase the value of nBackfill.
46980** (A WAL reset or recovery will revert nBackfill to zero, but not increase
46981** its value.)
46982**
46983** The caller must be holding sufficient locks to ensure that no other
46984** checkpoint is running (in any other thread or process) at the same
46985** time.
46986*/
46987static int walCheckpoint(
46988  Wal *pWal,                      /* Wal connection */
46989  int eMode,                      /* One of PASSIVE, FULL or RESTART */
46990  int (*xBusyCall)(void*),        /* Function to call when busy */
46991  void *pBusyArg,                 /* Context argument for xBusyHandler */
46992  int sync_flags,                 /* Flags for OsSync() (or 0) */
46993  u8 *zBuf                        /* Temporary buffer to use */
46994){
46995  int rc;                         /* Return code */
46996  int szPage;                     /* Database page-size */
46997  WalIterator *pIter = 0;         /* Wal iterator context */
46998  u32 iDbpage = 0;                /* Next database page to write */
46999  u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
47000  u32 mxSafeFrame;                /* Max frame that can be backfilled */
47001  u32 mxPage;                     /* Max database page to write */
47002  int i;                          /* Loop counter */
47003  volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
47004  int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
47005
47006  szPage = walPagesize(pWal);
47007  testcase( szPage<=32768 );
47008  testcase( szPage>=65536 );
47009  pInfo = walCkptInfo(pWal);
47010  if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
47011
47012  /* Allocate the iterator */
47013  rc = walIteratorInit(pWal, &pIter);
47014  if( rc!=SQLITE_OK ){
47015    return rc;
47016  }
47017  assert( pIter );
47018
47019  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
47020
47021  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
47022  ** safe to write into the database.  Frames beyond mxSafeFrame might
47023  ** overwrite database pages that are in use by active readers and thus
47024  ** cannot be backfilled from the WAL.
47025  */
47026  mxSafeFrame = pWal->hdr.mxFrame;
47027  mxPage = pWal->hdr.nPage;
47028  for(i=1; i<WAL_NREADER; i++){
47029    u32 y = pInfo->aReadMark[i];
47030    if( mxSafeFrame>y ){
47031      assert( y<=pWal->hdr.mxFrame );
47032      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
47033      if( rc==SQLITE_OK ){
47034        pInfo->aReadMark[i] = READMARK_NOT_USED;
47035        walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47036      }else if( rc==SQLITE_BUSY ){
47037        mxSafeFrame = y;
47038        xBusy = 0;
47039      }else{
47040        goto walcheckpoint_out;
47041      }
47042    }
47043  }
47044
47045  if( pInfo->nBackfill<mxSafeFrame
47046   && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
47047  ){
47048    i64 nSize;                    /* Current size of database file */
47049    u32 nBackfill = pInfo->nBackfill;
47050
47051    /* Sync the WAL to disk */
47052    if( sync_flags ){
47053      rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
47054    }
47055
47056    /* If the database file may grow as a result of this checkpoint, hint
47057    ** about the eventual size of the db file to the VFS layer.
47058    */
47059    if( rc==SQLITE_OK ){
47060      i64 nReq = ((i64)mxPage * szPage);
47061      rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
47062      if( rc==SQLITE_OK && nSize<nReq ){
47063        sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
47064      }
47065    }
47066
47067    /* Iterate through the contents of the WAL, copying data to the db file. */
47068    while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
47069      i64 iOffset;
47070      assert( walFramePgno(pWal, iFrame)==iDbpage );
47071      if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
47072      iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
47073      /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
47074      rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
47075      if( rc!=SQLITE_OK ) break;
47076      iOffset = (iDbpage-1)*(i64)szPage;
47077      testcase( IS_BIG_INT(iOffset) );
47078      rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
47079      if( rc!=SQLITE_OK ) break;
47080    }
47081
47082    /* If work was actually accomplished... */
47083    if( rc==SQLITE_OK ){
47084      if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
47085        i64 szDb = pWal->hdr.nPage*(i64)szPage;
47086        testcase( IS_BIG_INT(szDb) );
47087        rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
47088        if( rc==SQLITE_OK && sync_flags ){
47089          rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
47090        }
47091      }
47092      if( rc==SQLITE_OK ){
47093        pInfo->nBackfill = mxSafeFrame;
47094      }
47095    }
47096
47097    /* Release the reader lock held while backfilling */
47098    walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
47099  }
47100
47101  if( rc==SQLITE_BUSY ){
47102    /* Reset the return code so as not to report a checkpoint failure
47103    ** just because there are active readers.  */
47104    rc = SQLITE_OK;
47105  }
47106
47107  /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
47108  ** file has been copied into the database file, then block until all
47109  ** readers have finished using the wal file. This ensures that the next
47110  ** process to write to the database restarts the wal file.
47111  */
47112  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47113    assert( pWal->writeLock );
47114    if( pInfo->nBackfill<pWal->hdr.mxFrame ){
47115      rc = SQLITE_BUSY;
47116    }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
47117      assert( mxSafeFrame==pWal->hdr.mxFrame );
47118      rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
47119      if( rc==SQLITE_OK ){
47120        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47121      }
47122    }
47123  }
47124
47125 walcheckpoint_out:
47126  walIteratorFree(pIter);
47127  return rc;
47128}
47129
47130/*
47131** If the WAL file is currently larger than nMax bytes in size, truncate
47132** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
47133*/
47134static void walLimitSize(Wal *pWal, i64 nMax){
47135  i64 sz;
47136  int rx;
47137  sqlite3BeginBenignMalloc();
47138  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
47139  if( rx==SQLITE_OK && (sz > nMax ) ){
47140    rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
47141  }
47142  sqlite3EndBenignMalloc();
47143  if( rx ){
47144    sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
47145  }
47146}
47147
47148/*
47149** Close a connection to a log file.
47150*/
47151SQLITE_PRIVATE int sqlite3WalClose(
47152  Wal *pWal,                      /* Wal to close */
47153  int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
47154  int nBuf,
47155  u8 *zBuf                        /* Buffer of at least nBuf bytes */
47156){
47157  int rc = SQLITE_OK;
47158  if( pWal ){
47159    int isDelete = 0;             /* True to unlink wal and wal-index files */
47160
47161    /* If an EXCLUSIVE lock can be obtained on the database file (using the
47162    ** ordinary, rollback-mode locking methods, this guarantees that the
47163    ** connection associated with this log file is the only connection to
47164    ** the database. In this case checkpoint the database and unlink both
47165    ** the wal and wal-index files.
47166    **
47167    ** The EXCLUSIVE lock is not released before returning.
47168    */
47169    rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
47170    if( rc==SQLITE_OK ){
47171      if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
47172        pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
47173      }
47174      rc = sqlite3WalCheckpoint(
47175          pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
47176      );
47177      if( rc==SQLITE_OK ){
47178        int bPersist = -1;
47179        sqlite3OsFileControlHint(
47180            pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
47181        );
47182        if( bPersist!=1 ){
47183          /* Try to delete the WAL file if the checkpoint completed and
47184          ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
47185          ** mode (!bPersist) */
47186          isDelete = 1;
47187        }else if( pWal->mxWalSize>=0 ){
47188          /* Try to truncate the WAL file to zero bytes if the checkpoint
47189          ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
47190          ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
47191          ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
47192          ** to zero bytes as truncating to the journal_size_limit might
47193          ** leave a corrupt WAL file on disk. */
47194          walLimitSize(pWal, 0);
47195        }
47196      }
47197    }
47198
47199    walIndexClose(pWal, isDelete);
47200    sqlite3OsClose(pWal->pWalFd);
47201    if( isDelete ){
47202      sqlite3BeginBenignMalloc();
47203      sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
47204      sqlite3EndBenignMalloc();
47205    }
47206    WALTRACE(("WAL%p: closed\n", pWal));
47207    sqlite3_free((void *)pWal->apWiData);
47208    sqlite3_free(pWal);
47209  }
47210  return rc;
47211}
47212
47213/*
47214** Try to read the wal-index header.  Return 0 on success and 1 if
47215** there is a problem.
47216**
47217** The wal-index is in shared memory.  Another thread or process might
47218** be writing the header at the same time this procedure is trying to
47219** read it, which might result in inconsistency.  A dirty read is detected
47220** by verifying that both copies of the header are the same and also by
47221** a checksum on the header.
47222**
47223** If and only if the read is consistent and the header is different from
47224** pWal->hdr, then pWal->hdr is updated to the content of the new header
47225** and *pChanged is set to 1.
47226**
47227** If the checksum cannot be verified return non-zero. If the header
47228** is read successfully and the checksum verified, return zero.
47229*/
47230static int walIndexTryHdr(Wal *pWal, int *pChanged){
47231  u32 aCksum[2];                  /* Checksum on the header content */
47232  WalIndexHdr h1, h2;             /* Two copies of the header content */
47233  WalIndexHdr volatile *aHdr;     /* Header in shared memory */
47234
47235  /* The first page of the wal-index must be mapped at this point. */
47236  assert( pWal->nWiData>0 && pWal->apWiData[0] );
47237
47238  /* Read the header. This might happen concurrently with a write to the
47239  ** same area of shared memory on a different CPU in a SMP,
47240  ** meaning it is possible that an inconsistent snapshot is read
47241  ** from the file. If this happens, return non-zero.
47242  **
47243  ** There are two copies of the header at the beginning of the wal-index.
47244  ** When reading, read [0] first then [1].  Writes are in the reverse order.
47245  ** Memory barriers are used to prevent the compiler or the hardware from
47246  ** reordering the reads and writes.
47247  */
47248  aHdr = walIndexHdr(pWal);
47249  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
47250  walShmBarrier(pWal);
47251  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
47252
47253  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
47254    return 1;   /* Dirty read */
47255  }
47256  if( h1.isInit==0 ){
47257    return 1;   /* Malformed header - probably all zeros */
47258  }
47259  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
47260  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
47261    return 1;   /* Checksum does not match */
47262  }
47263
47264  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
47265    *pChanged = 1;
47266    memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
47267    pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47268    testcase( pWal->szPage<=32768 );
47269    testcase( pWal->szPage>=65536 );
47270  }
47271
47272  /* The header was successfully read. Return zero. */
47273  return 0;
47274}
47275
47276/*
47277** Read the wal-index header from the wal-index and into pWal->hdr.
47278** If the wal-header appears to be corrupt, try to reconstruct the
47279** wal-index from the WAL before returning.
47280**
47281** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
47282** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
47283** to 0.
47284**
47285** If the wal-index header is successfully read, return SQLITE_OK.
47286** Otherwise an SQLite error code.
47287*/
47288static int walIndexReadHdr(Wal *pWal, int *pChanged){
47289  int rc;                         /* Return code */
47290  int badHdr;                     /* True if a header read failed */
47291  volatile u32 *page0;            /* Chunk of wal-index containing header */
47292
47293  /* Ensure that page 0 of the wal-index (the page that contains the
47294  ** wal-index header) is mapped. Return early if an error occurs here.
47295  */
47296  assert( pChanged );
47297  rc = walIndexPage(pWal, 0, &page0);
47298  if( rc!=SQLITE_OK ){
47299    return rc;
47300  };
47301  assert( page0 || pWal->writeLock==0 );
47302
47303  /* If the first page of the wal-index has been mapped, try to read the
47304  ** wal-index header immediately, without holding any lock. This usually
47305  ** works, but may fail if the wal-index header is corrupt or currently
47306  ** being modified by another thread or process.
47307  */
47308  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
47309
47310  /* If the first attempt failed, it might have been due to a race
47311  ** with a writer.  So get a WRITE lock and try again.
47312  */
47313  assert( badHdr==0 || pWal->writeLock==0 );
47314  if( badHdr ){
47315    if( pWal->readOnly & WAL_SHM_RDONLY ){
47316      if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
47317        walUnlockShared(pWal, WAL_WRITE_LOCK);
47318        rc = SQLITE_READONLY_RECOVERY;
47319      }
47320    }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
47321      pWal->writeLock = 1;
47322      if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
47323        badHdr = walIndexTryHdr(pWal, pChanged);
47324        if( badHdr ){
47325          /* If the wal-index header is still malformed even while holding
47326          ** a WRITE lock, it can only mean that the header is corrupted and
47327          ** needs to be reconstructed.  So run recovery to do exactly that.
47328          */
47329          rc = walIndexRecover(pWal);
47330          *pChanged = 1;
47331        }
47332      }
47333      pWal->writeLock = 0;
47334      walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47335    }
47336  }
47337
47338  /* If the header is read successfully, check the version number to make
47339  ** sure the wal-index was not constructed with some future format that
47340  ** this version of SQLite cannot understand.
47341  */
47342  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
47343    rc = SQLITE_CANTOPEN_BKPT;
47344  }
47345
47346  return rc;
47347}
47348
47349/*
47350** This is the value that walTryBeginRead returns when it needs to
47351** be retried.
47352*/
47353#define WAL_RETRY  (-1)
47354
47355/*
47356** Attempt to start a read transaction.  This might fail due to a race or
47357** other transient condition.  When that happens, it returns WAL_RETRY to
47358** indicate to the caller that it is safe to retry immediately.
47359**
47360** On success return SQLITE_OK.  On a permanent failure (such an
47361** I/O error or an SQLITE_BUSY because another process is running
47362** recovery) return a positive error code.
47363**
47364** The useWal parameter is true to force the use of the WAL and disable
47365** the case where the WAL is bypassed because it has been completely
47366** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr()
47367** to make a copy of the wal-index header into pWal->hdr.  If the
47368** wal-index header has changed, *pChanged is set to 1 (as an indication
47369** to the caller that the local paget cache is obsolete and needs to be
47370** flushed.)  When useWal==1, the wal-index header is assumed to already
47371** be loaded and the pChanged parameter is unused.
47372**
47373** The caller must set the cnt parameter to the number of prior calls to
47374** this routine during the current read attempt that returned WAL_RETRY.
47375** This routine will start taking more aggressive measures to clear the
47376** race conditions after multiple WAL_RETRY returns, and after an excessive
47377** number of errors will ultimately return SQLITE_PROTOCOL.  The
47378** SQLITE_PROTOCOL return indicates that some other process has gone rogue
47379** and is not honoring the locking protocol.  There is a vanishingly small
47380** chance that SQLITE_PROTOCOL could be returned because of a run of really
47381** bad luck when there is lots of contention for the wal-index, but that
47382** possibility is so small that it can be safely neglected, we believe.
47383**
47384** On success, this routine obtains a read lock on
47385** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
47386** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
47387** that means the Wal does not hold any read lock.  The reader must not
47388** access any database page that is modified by a WAL frame up to and
47389** including frame number aReadMark[pWal->readLock].  The reader will
47390** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
47391** Or if pWal->readLock==0, then the reader will ignore the WAL
47392** completely and get all content directly from the database file.
47393** If the useWal parameter is 1 then the WAL will never be ignored and
47394** this routine will always set pWal->readLock>0 on success.
47395** When the read transaction is completed, the caller must release the
47396** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
47397**
47398** This routine uses the nBackfill and aReadMark[] fields of the header
47399** to select a particular WAL_READ_LOCK() that strives to let the
47400** checkpoint process do as much work as possible.  This routine might
47401** update values of the aReadMark[] array in the header, but if it does
47402** so it takes care to hold an exclusive lock on the corresponding
47403** WAL_READ_LOCK() while changing values.
47404*/
47405static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
47406  volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
47407  u32 mxReadMark;                 /* Largest aReadMark[] value */
47408  int mxI;                        /* Index of largest aReadMark[] value */
47409  int i;                          /* Loop counter */
47410  int rc = SQLITE_OK;             /* Return code  */
47411
47412  assert( pWal->readLock<0 );     /* Not currently locked */
47413
47414  /* Take steps to avoid spinning forever if there is a protocol error.
47415  **
47416  ** Circumstances that cause a RETRY should only last for the briefest
47417  ** instances of time.  No I/O or other system calls are done while the
47418  ** locks are held, so the locks should not be held for very long. But
47419  ** if we are unlucky, another process that is holding a lock might get
47420  ** paged out or take a page-fault that is time-consuming to resolve,
47421  ** during the few nanoseconds that it is holding the lock.  In that case,
47422  ** it might take longer than normal for the lock to free.
47423  **
47424  ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
47425  ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
47426  ** is more of a scheduler yield than an actual delay.  But on the 10th
47427  ** an subsequent retries, the delays start becoming longer and longer,
47428  ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
47429  ** The total delay time before giving up is less than 1 second.
47430  */
47431  if( cnt>5 ){
47432    int nDelay = 1;                      /* Pause time in microseconds */
47433    if( cnt>100 ){
47434      VVA_ONLY( pWal->lockError = 1; )
47435      return SQLITE_PROTOCOL;
47436    }
47437    if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
47438    sqlite3OsSleep(pWal->pVfs, nDelay);
47439  }
47440
47441  if( !useWal ){
47442    rc = walIndexReadHdr(pWal, pChanged);
47443    if( rc==SQLITE_BUSY ){
47444      /* If there is not a recovery running in another thread or process
47445      ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
47446      ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
47447      ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
47448      ** would be technically correct.  But the race is benign since with
47449      ** WAL_RETRY this routine will be called again and will probably be
47450      ** right on the second iteration.
47451      */
47452      if( pWal->apWiData[0]==0 ){
47453        /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
47454        ** We assume this is a transient condition, so return WAL_RETRY. The
47455        ** xShmMap() implementation used by the default unix and win32 VFS
47456        ** modules may return SQLITE_BUSY due to a race condition in the
47457        ** code that determines whether or not the shared-memory region
47458        ** must be zeroed before the requested page is returned.
47459        */
47460        rc = WAL_RETRY;
47461      }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
47462        walUnlockShared(pWal, WAL_RECOVER_LOCK);
47463        rc = WAL_RETRY;
47464      }else if( rc==SQLITE_BUSY ){
47465        rc = SQLITE_BUSY_RECOVERY;
47466      }
47467    }
47468    if( rc!=SQLITE_OK ){
47469      return rc;
47470    }
47471  }
47472
47473  pInfo = walCkptInfo(pWal);
47474  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
47475    /* The WAL has been completely backfilled (or it is empty).
47476    ** and can be safely ignored.
47477    */
47478    rc = walLockShared(pWal, WAL_READ_LOCK(0));
47479    walShmBarrier(pWal);
47480    if( rc==SQLITE_OK ){
47481      if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
47482        /* It is not safe to allow the reader to continue here if frames
47483        ** may have been appended to the log before READ_LOCK(0) was obtained.
47484        ** When holding READ_LOCK(0), the reader ignores the entire log file,
47485        ** which implies that the database file contains a trustworthy
47486        ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
47487        ** happening, this is usually correct.
47488        **
47489        ** However, if frames have been appended to the log (or if the log
47490        ** is wrapped and written for that matter) before the READ_LOCK(0)
47491        ** is obtained, that is not necessarily true. A checkpointer may
47492        ** have started to backfill the appended frames but crashed before
47493        ** it finished. Leaving a corrupt image in the database file.
47494        */
47495        walUnlockShared(pWal, WAL_READ_LOCK(0));
47496        return WAL_RETRY;
47497      }
47498      pWal->readLock = 0;
47499      return SQLITE_OK;
47500    }else if( rc!=SQLITE_BUSY ){
47501      return rc;
47502    }
47503  }
47504
47505  /* If we get this far, it means that the reader will want to use
47506  ** the WAL to get at content from recent commits.  The job now is
47507  ** to select one of the aReadMark[] entries that is closest to
47508  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
47509  */
47510  mxReadMark = 0;
47511  mxI = 0;
47512  for(i=1; i<WAL_NREADER; i++){
47513    u32 thisMark = pInfo->aReadMark[i];
47514    if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
47515      assert( thisMark!=READMARK_NOT_USED );
47516      mxReadMark = thisMark;
47517      mxI = i;
47518    }
47519  }
47520  /* There was once an "if" here. The extra "{" is to preserve indentation. */
47521  {
47522    if( (pWal->readOnly & WAL_SHM_RDONLY)==0
47523     && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
47524    ){
47525      for(i=1; i<WAL_NREADER; i++){
47526        rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
47527        if( rc==SQLITE_OK ){
47528          mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
47529          mxI = i;
47530          walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47531          break;
47532        }else if( rc!=SQLITE_BUSY ){
47533          return rc;
47534        }
47535      }
47536    }
47537    if( mxI==0 ){
47538      assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
47539      return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
47540    }
47541
47542    rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
47543    if( rc ){
47544      return rc==SQLITE_BUSY ? WAL_RETRY : rc;
47545    }
47546    /* Now that the read-lock has been obtained, check that neither the
47547    ** value in the aReadMark[] array or the contents of the wal-index
47548    ** header have changed.
47549    **
47550    ** It is necessary to check that the wal-index header did not change
47551    ** between the time it was read and when the shared-lock was obtained
47552    ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
47553    ** that the log file may have been wrapped by a writer, or that frames
47554    ** that occur later in the log than pWal->hdr.mxFrame may have been
47555    ** copied into the database by a checkpointer. If either of these things
47556    ** happened, then reading the database with the current value of
47557    ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
47558    ** instead.
47559    **
47560    ** This does not guarantee that the copy of the wal-index header is up to
47561    ** date before proceeding. That would not be possible without somehow
47562    ** blocking writers. It only guarantees that a dangerous checkpoint or
47563    ** log-wrap (either of which would require an exclusive lock on
47564    ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
47565    */
47566    walShmBarrier(pWal);
47567    if( pInfo->aReadMark[mxI]!=mxReadMark
47568     || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
47569    ){
47570      walUnlockShared(pWal, WAL_READ_LOCK(mxI));
47571      return WAL_RETRY;
47572    }else{
47573      assert( mxReadMark<=pWal->hdr.mxFrame );
47574      pWal->readLock = (i16)mxI;
47575    }
47576  }
47577  return rc;
47578}
47579
47580/*
47581** Begin a read transaction on the database.
47582**
47583** This routine used to be called sqlite3OpenSnapshot() and with good reason:
47584** it takes a snapshot of the state of the WAL and wal-index for the current
47585** instant in time.  The current thread will continue to use this snapshot.
47586** Other threads might append new content to the WAL and wal-index but
47587** that extra content is ignored by the current thread.
47588**
47589** If the database contents have changes since the previous read
47590** transaction, then *pChanged is set to 1 before returning.  The
47591** Pager layer will use this to know that is cache is stale and
47592** needs to be flushed.
47593*/
47594SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
47595  int rc;                         /* Return code */
47596  int cnt = 0;                    /* Number of TryBeginRead attempts */
47597
47598  do{
47599    rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
47600  }while( rc==WAL_RETRY );
47601  testcase( (rc&0xff)==SQLITE_BUSY );
47602  testcase( (rc&0xff)==SQLITE_IOERR );
47603  testcase( rc==SQLITE_PROTOCOL );
47604  testcase( rc==SQLITE_OK );
47605  return rc;
47606}
47607
47608/*
47609** Finish with a read transaction.  All this does is release the
47610** read-lock.
47611*/
47612SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
47613  sqlite3WalEndWriteTransaction(pWal);
47614  if( pWal->readLock>=0 ){
47615    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47616    pWal->readLock = -1;
47617  }
47618}
47619
47620/*
47621** Read a page from the WAL, if it is present in the WAL and if the
47622** current read transaction is configured to use the WAL.
47623**
47624** The *pInWal is set to 1 if the requested page is in the WAL and
47625** has been loaded.  Or *pInWal is set to 0 if the page was not in
47626** the WAL and needs to be read out of the database.
47627*/
47628SQLITE_PRIVATE int sqlite3WalRead(
47629  Wal *pWal,                      /* WAL handle */
47630  Pgno pgno,                      /* Database page number to read data for */
47631  int *pInWal,                    /* OUT: True if data is read from WAL */
47632  int nOut,                       /* Size of buffer pOut in bytes */
47633  u8 *pOut                        /* Buffer to write page data to */
47634){
47635  u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
47636  u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
47637  int iHash;                      /* Used to loop through N hash tables */
47638
47639  /* This routine is only be called from within a read transaction. */
47640  assert( pWal->readLock>=0 || pWal->lockError );
47641
47642  /* If the "last page" field of the wal-index header snapshot is 0, then
47643  ** no data will be read from the wal under any circumstances. Return early
47644  ** in this case as an optimization.  Likewise, if pWal->readLock==0,
47645  ** then the WAL is ignored by the reader so return early, as if the
47646  ** WAL were empty.
47647  */
47648  if( iLast==0 || pWal->readLock==0 ){
47649    *pInWal = 0;
47650    return SQLITE_OK;
47651  }
47652
47653  /* Search the hash table or tables for an entry matching page number
47654  ** pgno. Each iteration of the following for() loop searches one
47655  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
47656  **
47657  ** This code might run concurrently to the code in walIndexAppend()
47658  ** that adds entries to the wal-index (and possibly to this hash
47659  ** table). This means the value just read from the hash
47660  ** slot (aHash[iKey]) may have been added before or after the
47661  ** current read transaction was opened. Values added after the
47662  ** read transaction was opened may have been written incorrectly -
47663  ** i.e. these slots may contain garbage data. However, we assume
47664  ** that any slots written before the current read transaction was
47665  ** opened remain unmodified.
47666  **
47667  ** For the reasons above, the if(...) condition featured in the inner
47668  ** loop of the following block is more stringent that would be required
47669  ** if we had exclusive access to the hash-table:
47670  **
47671  **   (aPgno[iFrame]==pgno):
47672  **     This condition filters out normal hash-table collisions.
47673  **
47674  **   (iFrame<=iLast):
47675  **     This condition filters out entries that were added to the hash
47676  **     table after the current read-transaction had started.
47677  */
47678  for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
47679    volatile ht_slot *aHash;      /* Pointer to hash table */
47680    volatile u32 *aPgno;          /* Pointer to array of page numbers */
47681    u32 iZero;                    /* Frame number corresponding to aPgno[0] */
47682    int iKey;                     /* Hash slot index */
47683    int nCollide;                 /* Number of hash collisions remaining */
47684    int rc;                       /* Error code */
47685
47686    rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
47687    if( rc!=SQLITE_OK ){
47688      return rc;
47689    }
47690    nCollide = HASHTABLE_NSLOT;
47691    for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
47692      u32 iFrame = aHash[iKey] + iZero;
47693      if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
47694        /* assert( iFrame>iRead ); -- not true if there is corruption */
47695        iRead = iFrame;
47696      }
47697      if( (nCollide--)==0 ){
47698        return SQLITE_CORRUPT_BKPT;
47699      }
47700    }
47701  }
47702
47703#ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47704  /* If expensive assert() statements are available, do a linear search
47705  ** of the wal-index file content. Make sure the results agree with the
47706  ** result obtained using the hash indexes above.  */
47707  {
47708    u32 iRead2 = 0;
47709    u32 iTest;
47710    for(iTest=iLast; iTest>0; iTest--){
47711      if( walFramePgno(pWal, iTest)==pgno ){
47712        iRead2 = iTest;
47713        break;
47714      }
47715    }
47716    assert( iRead==iRead2 );
47717  }
47718#endif
47719
47720  /* If iRead is non-zero, then it is the log frame number that contains the
47721  ** required page. Read and return data from the log file.
47722  */
47723  if( iRead ){
47724    int sz;
47725    i64 iOffset;
47726    sz = pWal->hdr.szPage;
47727    sz = (sz&0xfe00) + ((sz&0x0001)<<16);
47728    testcase( sz<=32768 );
47729    testcase( sz>=65536 );
47730    iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
47731    *pInWal = 1;
47732    /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
47733    return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
47734  }
47735
47736  *pInWal = 0;
47737  return SQLITE_OK;
47738}
47739
47740
47741/*
47742** Return the size of the database in pages (or zero, if unknown).
47743*/
47744SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
47745  if( pWal && ALWAYS(pWal->readLock>=0) ){
47746    return pWal->hdr.nPage;
47747  }
47748  return 0;
47749}
47750
47751
47752/*
47753** This function starts a write transaction on the WAL.
47754**
47755** A read transaction must have already been started by a prior call
47756** to sqlite3WalBeginReadTransaction().
47757**
47758** If another thread or process has written into the database since
47759** the read transaction was started, then it is not possible for this
47760** thread to write as doing so would cause a fork.  So this routine
47761** returns SQLITE_BUSY in that case and no write transaction is started.
47762**
47763** There can only be a single writer active at a time.
47764*/
47765SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
47766  int rc;
47767
47768  /* Cannot start a write transaction without first holding a read
47769  ** transaction. */
47770  assert( pWal->readLock>=0 );
47771
47772  if( pWal->readOnly ){
47773    return SQLITE_READONLY;
47774  }
47775
47776  /* Only one writer allowed at a time.  Get the write lock.  Return
47777  ** SQLITE_BUSY if unable.
47778  */
47779  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
47780  if( rc ){
47781    return rc;
47782  }
47783  pWal->writeLock = 1;
47784
47785  /* If another connection has written to the database file since the
47786  ** time the read transaction on this connection was started, then
47787  ** the write is disallowed.
47788  */
47789  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
47790    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47791    pWal->writeLock = 0;
47792    rc = SQLITE_BUSY;
47793  }
47794
47795  return rc;
47796}
47797
47798/*
47799** End a write transaction.  The commit has already been done.  This
47800** routine merely releases the lock.
47801*/
47802SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
47803  if( pWal->writeLock ){
47804    walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47805    pWal->writeLock = 0;
47806    pWal->truncateOnCommit = 0;
47807  }
47808  return SQLITE_OK;
47809}
47810
47811/*
47812** If any data has been written (but not committed) to the log file, this
47813** function moves the write-pointer back to the start of the transaction.
47814**
47815** Additionally, the callback function is invoked for each frame written
47816** to the WAL since the start of the transaction. If the callback returns
47817** other than SQLITE_OK, it is not invoked again and the error code is
47818** returned to the caller.
47819**
47820** Otherwise, if the callback function does not return an error, this
47821** function returns SQLITE_OK.
47822*/
47823SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
47824  int rc = SQLITE_OK;
47825  if( ALWAYS(pWal->writeLock) ){
47826    Pgno iMax = pWal->hdr.mxFrame;
47827    Pgno iFrame;
47828
47829    /* Restore the clients cache of the wal-index header to the state it
47830    ** was in before the client began writing to the database.
47831    */
47832    memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
47833
47834    for(iFrame=pWal->hdr.mxFrame+1;
47835        ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
47836        iFrame++
47837    ){
47838      /* This call cannot fail. Unless the page for which the page number
47839      ** is passed as the second argument is (a) in the cache and
47840      ** (b) has an outstanding reference, then xUndo is either a no-op
47841      ** (if (a) is false) or simply expels the page from the cache (if (b)
47842      ** is false).
47843      **
47844      ** If the upper layer is doing a rollback, it is guaranteed that there
47845      ** are no outstanding references to any page other than page 1. And
47846      ** page 1 is never written to the log until the transaction is
47847      ** committed. As a result, the call to xUndo may not fail.
47848      */
47849      assert( walFramePgno(pWal, iFrame)!=1 );
47850      rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
47851    }
47852    walCleanupHash(pWal);
47853  }
47854  assert( rc==SQLITE_OK );
47855  return rc;
47856}
47857
47858/*
47859** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
47860** values. This function populates the array with values required to
47861** "rollback" the write position of the WAL handle back to the current
47862** point in the event of a savepoint rollback (via WalSavepointUndo()).
47863*/
47864SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
47865  assert( pWal->writeLock );
47866  aWalData[0] = pWal->hdr.mxFrame;
47867  aWalData[1] = pWal->hdr.aFrameCksum[0];
47868  aWalData[2] = pWal->hdr.aFrameCksum[1];
47869  aWalData[3] = pWal->nCkpt;
47870}
47871
47872/*
47873** Move the write position of the WAL back to the point identified by
47874** the values in the aWalData[] array. aWalData must point to an array
47875** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
47876** by a call to WalSavepoint().
47877*/
47878SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
47879  int rc = SQLITE_OK;
47880
47881  assert( pWal->writeLock );
47882  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
47883
47884  if( aWalData[3]!=pWal->nCkpt ){
47885    /* This savepoint was opened immediately after the write-transaction
47886    ** was started. Right after that, the writer decided to wrap around
47887    ** to the start of the log. Update the savepoint values to match.
47888    */
47889    aWalData[0] = 0;
47890    aWalData[3] = pWal->nCkpt;
47891  }
47892
47893  if( aWalData[0]<pWal->hdr.mxFrame ){
47894    pWal->hdr.mxFrame = aWalData[0];
47895    pWal->hdr.aFrameCksum[0] = aWalData[1];
47896    pWal->hdr.aFrameCksum[1] = aWalData[2];
47897    walCleanupHash(pWal);
47898  }
47899
47900  return rc;
47901}
47902
47903
47904/*
47905** This function is called just before writing a set of frames to the log
47906** file (see sqlite3WalFrames()). It checks to see if, instead of appending
47907** to the current log file, it is possible to overwrite the start of the
47908** existing log file with the new frames (i.e. "reset" the log). If so,
47909** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
47910** unchanged.
47911**
47912** SQLITE_OK is returned if no error is encountered (regardless of whether
47913** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
47914** if an error occurs.
47915*/
47916static int walRestartLog(Wal *pWal){
47917  int rc = SQLITE_OK;
47918  int cnt;
47919
47920  if( pWal->readLock==0 ){
47921    volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
47922    assert( pInfo->nBackfill==pWal->hdr.mxFrame );
47923    if( pInfo->nBackfill>0 ){
47924      u32 salt1;
47925      sqlite3_randomness(4, &salt1);
47926      rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47927      if( rc==SQLITE_OK ){
47928        /* If all readers are using WAL_READ_LOCK(0) (in other words if no
47929        ** readers are currently using the WAL), then the transactions
47930        ** frames will overwrite the start of the existing log. Update the
47931        ** wal-index header to reflect this.
47932        **
47933        ** In theory it would be Ok to update the cache of the header only
47934        ** at this point. But updating the actual wal-index header is also
47935        ** safe and means there is no special case for sqlite3WalUndo()
47936        ** to handle if this transaction is rolled back.
47937        */
47938        int i;                    /* Loop counter */
47939        u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
47940
47941        pWal->nCkpt++;
47942        pWal->hdr.mxFrame = 0;
47943        sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
47944        aSalt[1] = salt1;
47945        walIndexWriteHdr(pWal);
47946        pInfo->nBackfill = 0;
47947        for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
47948        assert( pInfo->aReadMark[0]==0 );
47949        walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47950      }else if( rc!=SQLITE_BUSY ){
47951        return rc;
47952      }
47953    }
47954    walUnlockShared(pWal, WAL_READ_LOCK(0));
47955    pWal->readLock = -1;
47956    cnt = 0;
47957    do{
47958      int notUsed;
47959      rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
47960    }while( rc==WAL_RETRY );
47961    assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
47962    testcase( (rc&0xff)==SQLITE_IOERR );
47963    testcase( rc==SQLITE_PROTOCOL );
47964    testcase( rc==SQLITE_OK );
47965  }
47966  return rc;
47967}
47968
47969/*
47970** Information about the current state of the WAL file and where
47971** the next fsync should occur - passed from sqlite3WalFrames() into
47972** walWriteToLog().
47973*/
47974typedef struct WalWriter {
47975  Wal *pWal;                   /* The complete WAL information */
47976  sqlite3_file *pFd;           /* The WAL file to which we write */
47977  sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
47978  int syncFlags;               /* Flags for the fsync */
47979  int szPage;                  /* Size of one page */
47980} WalWriter;
47981
47982/*
47983** Write iAmt bytes of content into the WAL file beginning at iOffset.
47984** Do a sync when crossing the p->iSyncPoint boundary.
47985**
47986** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
47987** first write the part before iSyncPoint, then sync, then write the
47988** rest.
47989*/
47990static int walWriteToLog(
47991  WalWriter *p,              /* WAL to write to */
47992  void *pContent,            /* Content to be written */
47993  int iAmt,                  /* Number of bytes to write */
47994  sqlite3_int64 iOffset      /* Start writing at this offset */
47995){
47996  int rc;
47997  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
47998    int iFirstAmt = (int)(p->iSyncPoint - iOffset);
47999    rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
48000    if( rc ) return rc;
48001    iOffset += iFirstAmt;
48002    iAmt -= iFirstAmt;
48003    pContent = (void*)(iFirstAmt + (char*)pContent);
48004    assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
48005    rc = sqlite3OsSync(p->pFd, p->syncFlags);
48006    if( iAmt==0 || rc ) return rc;
48007  }
48008  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
48009  return rc;
48010}
48011
48012/*
48013** Write out a single frame of the WAL
48014*/
48015static int walWriteOneFrame(
48016  WalWriter *p,               /* Where to write the frame */
48017  PgHdr *pPage,               /* The page of the frame to be written */
48018  int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
48019  sqlite3_int64 iOffset       /* Byte offset at which to write */
48020){
48021  int rc;                         /* Result code from subfunctions */
48022  void *pData;                    /* Data actually written */
48023  u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
48024#if defined(SQLITE_HAS_CODEC)
48025  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
48026#else
48027  pData = pPage->pData;
48028#endif
48029  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
48030  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
48031  if( rc ) return rc;
48032  /* Write the page data */
48033  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
48034  return rc;
48035}
48036
48037/*
48038** Write a set of frames to the log. The caller must hold the write-lock
48039** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
48040*/
48041SQLITE_PRIVATE int sqlite3WalFrames(
48042  Wal *pWal,                      /* Wal handle to write to */
48043  int szPage,                     /* Database page-size in bytes */
48044  PgHdr *pList,                   /* List of dirty pages to write */
48045  Pgno nTruncate,                 /* Database size after this commit */
48046  int isCommit,                   /* True if this is a commit */
48047  int sync_flags                  /* Flags to pass to OsSync() (or 0) */
48048){
48049  int rc;                         /* Used to catch return codes */
48050  u32 iFrame;                     /* Next frame address */
48051  PgHdr *p;                       /* Iterator to run through pList with. */
48052  PgHdr *pLast = 0;               /* Last frame in list */
48053  int nExtra = 0;                 /* Number of extra copies of last page */
48054  int szFrame;                    /* The size of a single frame */
48055  i64 iOffset;                    /* Next byte to write in WAL file */
48056  WalWriter w;                    /* The writer */
48057
48058  assert( pList );
48059  assert( pWal->writeLock );
48060
48061  /* If this frame set completes a transaction, then nTruncate>0.  If
48062  ** nTruncate==0 then this frame set does not complete the transaction. */
48063  assert( (isCommit!=0)==(nTruncate!=0) );
48064
48065#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48066  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
48067    WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
48068              pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
48069  }
48070#endif
48071
48072  /* See if it is possible to write these frames into the start of the
48073  ** log file, instead of appending to it at pWal->hdr.mxFrame.
48074  */
48075  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
48076    return rc;
48077  }
48078
48079  /* If this is the first frame written into the log, write the WAL
48080  ** header to the start of the WAL file. See comments at the top of
48081  ** this source file for a description of the WAL header format.
48082  */
48083  iFrame = pWal->hdr.mxFrame;
48084  if( iFrame==0 ){
48085    u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
48086    u32 aCksum[2];                /* Checksum for wal-header */
48087
48088    sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
48089    sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
48090    sqlite3Put4byte(&aWalHdr[8], szPage);
48091    sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
48092    if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
48093    memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
48094    walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
48095    sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
48096    sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
48097
48098    pWal->szPage = szPage;
48099    pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
48100    pWal->hdr.aFrameCksum[0] = aCksum[0];
48101    pWal->hdr.aFrameCksum[1] = aCksum[1];
48102    pWal->truncateOnCommit = 1;
48103
48104    rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
48105    WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
48106    if( rc!=SQLITE_OK ){
48107      return rc;
48108    }
48109
48110    /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
48111    ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
48112    ** an out-of-order write following a WAL restart could result in
48113    ** database corruption.  See the ticket:
48114    **
48115    **     http://localhost:591/sqlite/info/ff5be73dee
48116    */
48117    if( pWal->syncHeader && sync_flags ){
48118      rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
48119      if( rc ) return rc;
48120    }
48121  }
48122  assert( (int)pWal->szPage==szPage );
48123
48124  /* Setup information needed to write frames into the WAL */
48125  w.pWal = pWal;
48126  w.pFd = pWal->pWalFd;
48127  w.iSyncPoint = 0;
48128  w.syncFlags = sync_flags;
48129  w.szPage = szPage;
48130  iOffset = walFrameOffset(iFrame+1, szPage);
48131  szFrame = szPage + WAL_FRAME_HDRSIZE;
48132
48133  /* Write all frames into the log file exactly once */
48134  for(p=pList; p; p=p->pDirty){
48135    int nDbSize;   /* 0 normally.  Positive == commit flag */
48136    iFrame++;
48137    assert( iOffset==walFrameOffset(iFrame, szPage) );
48138    nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
48139    rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
48140    if( rc ) return rc;
48141    pLast = p;
48142    iOffset += szFrame;
48143  }
48144
48145  /* If this is the end of a transaction, then we might need to pad
48146  ** the transaction and/or sync the WAL file.
48147  **
48148  ** Padding and syncing only occur if this set of frames complete a
48149  ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
48150  ** or synchonous==OFF, then no padding or syncing are needed.
48151  **
48152  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
48153  ** needed and only the sync is done.  If padding is needed, then the
48154  ** final frame is repeated (with its commit mark) until the next sector
48155  ** boundary is crossed.  Only the part of the WAL prior to the last
48156  ** sector boundary is synced; the part of the last frame that extends
48157  ** past the sector boundary is written after the sync.
48158  */
48159  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
48160    if( pWal->padToSectorBoundary ){
48161      int sectorSize = sqlite3OsSectorSize(pWal->pWalFd);
48162      w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
48163      while( iOffset<w.iSyncPoint ){
48164        rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
48165        if( rc ) return rc;
48166        iOffset += szFrame;
48167        nExtra++;
48168      }
48169    }else{
48170      rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
48171    }
48172  }
48173
48174  /* If this frame set completes the first transaction in the WAL and
48175  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
48176  ** journal size limit, if possible.
48177  */
48178  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
48179    i64 sz = pWal->mxWalSize;
48180    if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
48181      sz = walFrameOffset(iFrame+nExtra+1, szPage);
48182    }
48183    walLimitSize(pWal, sz);
48184    pWal->truncateOnCommit = 0;
48185  }
48186
48187  /* Append data to the wal-index. It is not necessary to lock the
48188  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
48189  ** guarantees that there are no other writers, and no data that may
48190  ** be in use by existing readers is being overwritten.
48191  */
48192  iFrame = pWal->hdr.mxFrame;
48193  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
48194    iFrame++;
48195    rc = walIndexAppend(pWal, iFrame, p->pgno);
48196  }
48197  while( rc==SQLITE_OK && nExtra>0 ){
48198    iFrame++;
48199    nExtra--;
48200    rc = walIndexAppend(pWal, iFrame, pLast->pgno);
48201  }
48202
48203  if( rc==SQLITE_OK ){
48204    /* Update the private copy of the header. */
48205    pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
48206    testcase( szPage<=32768 );
48207    testcase( szPage>=65536 );
48208    pWal->hdr.mxFrame = iFrame;
48209    if( isCommit ){
48210      pWal->hdr.iChange++;
48211      pWal->hdr.nPage = nTruncate;
48212    }
48213    /* If this is a commit, update the wal-index header too. */
48214    if( isCommit ){
48215      walIndexWriteHdr(pWal);
48216      pWal->iCallback = iFrame;
48217    }
48218  }
48219
48220  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
48221  return rc;
48222}
48223
48224/*
48225** This routine is called to implement sqlite3_wal_checkpoint() and
48226** related interfaces.
48227**
48228** Obtain a CHECKPOINT lock and then backfill as much information as
48229** we can from WAL into the database.
48230**
48231** If parameter xBusy is not NULL, it is a pointer to a busy-handler
48232** callback. In this case this function runs a blocking checkpoint.
48233*/
48234SQLITE_PRIVATE int sqlite3WalCheckpoint(
48235  Wal *pWal,                      /* Wal connection */
48236  int eMode,                      /* PASSIVE, FULL or RESTART */
48237  int (*xBusy)(void*),            /* Function to call when busy */
48238  void *pBusyArg,                 /* Context argument for xBusyHandler */
48239  int sync_flags,                 /* Flags to sync db file with (or 0) */
48240  int nBuf,                       /* Size of temporary buffer */
48241  u8 *zBuf,                       /* Temporary buffer to use */
48242  int *pnLog,                     /* OUT: Number of frames in WAL */
48243  int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
48244){
48245  int rc;                         /* Return code */
48246  int isChanged = 0;              /* True if a new wal-index header is loaded */
48247  int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
48248
48249  assert( pWal->ckptLock==0 );
48250  assert( pWal->writeLock==0 );
48251
48252  if( pWal->readOnly ) return SQLITE_READONLY;
48253  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
48254  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
48255  if( rc ){
48256    /* Usually this is SQLITE_BUSY meaning that another thread or process
48257    ** is already running a checkpoint, or maybe a recovery.  But it might
48258    ** also be SQLITE_IOERR. */
48259    return rc;
48260  }
48261  pWal->ckptLock = 1;
48262
48263  /* If this is a blocking-checkpoint, then obtain the write-lock as well
48264  ** to prevent any writers from running while the checkpoint is underway.
48265  ** This has to be done before the call to walIndexReadHdr() below.
48266  **
48267  ** If the writer lock cannot be obtained, then a passive checkpoint is
48268  ** run instead. Since the checkpointer is not holding the writer lock,
48269  ** there is no point in blocking waiting for any readers. Assuming no
48270  ** other error occurs, this function will return SQLITE_BUSY to the caller.
48271  */
48272  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
48273    rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
48274    if( rc==SQLITE_OK ){
48275      pWal->writeLock = 1;
48276    }else if( rc==SQLITE_BUSY ){
48277      eMode2 = SQLITE_CHECKPOINT_PASSIVE;
48278      rc = SQLITE_OK;
48279    }
48280  }
48281
48282  /* Read the wal-index header. */
48283  if( rc==SQLITE_OK ){
48284    rc = walIndexReadHdr(pWal, &isChanged);
48285  }
48286
48287  /* Copy data from the log to the database file. */
48288  if( rc==SQLITE_OK ){
48289    if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
48290      rc = SQLITE_CORRUPT_BKPT;
48291    }else{
48292      rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
48293    }
48294
48295    /* If no error occurred, set the output variables. */
48296    if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
48297      if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
48298      if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
48299    }
48300  }
48301
48302  if( isChanged ){
48303    /* If a new wal-index header was loaded before the checkpoint was
48304    ** performed, then the pager-cache associated with pWal is now
48305    ** out of date. So zero the cached wal-index header to ensure that
48306    ** next time the pager opens a snapshot on this database it knows that
48307    ** the cache needs to be reset.
48308    */
48309    memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
48310  }
48311
48312  /* Release the locks. */
48313  sqlite3WalEndWriteTransaction(pWal);
48314  walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
48315  pWal->ckptLock = 0;
48316  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
48317  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
48318}
48319
48320/* Return the value to pass to a sqlite3_wal_hook callback, the
48321** number of frames in the WAL at the point of the last commit since
48322** sqlite3WalCallback() was called.  If no commits have occurred since
48323** the last call, then return 0.
48324*/
48325SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
48326  u32 ret = 0;
48327  if( pWal ){
48328    ret = pWal->iCallback;
48329    pWal->iCallback = 0;
48330  }
48331  return (int)ret;
48332}
48333
48334/*
48335** This function is called to change the WAL subsystem into or out
48336** of locking_mode=EXCLUSIVE.
48337**
48338** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
48339** into locking_mode=NORMAL.  This means that we must acquire a lock
48340** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
48341** or if the acquisition of the lock fails, then return 0.  If the
48342** transition out of exclusive-mode is successful, return 1.  This
48343** operation must occur while the pager is still holding the exclusive
48344** lock on the main database file.
48345**
48346** If op is one, then change from locking_mode=NORMAL into
48347** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
48348** be released.  Return 1 if the transition is made and 0 if the
48349** WAL is already in exclusive-locking mode - meaning that this
48350** routine is a no-op.  The pager must already hold the exclusive lock
48351** on the main database file before invoking this operation.
48352**
48353** If op is negative, then do a dry-run of the op==1 case but do
48354** not actually change anything. The pager uses this to see if it
48355** should acquire the database exclusive lock prior to invoking
48356** the op==1 case.
48357*/
48358SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
48359  int rc;
48360  assert( pWal->writeLock==0 );
48361  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
48362
48363  /* pWal->readLock is usually set, but might be -1 if there was a
48364  ** prior error while attempting to acquire are read-lock. This cannot
48365  ** happen if the connection is actually in exclusive mode (as no xShmLock
48366  ** locks are taken in this case). Nor should the pager attempt to
48367  ** upgrade to exclusive-mode following such an error.
48368  */
48369  assert( pWal->readLock>=0 || pWal->lockError );
48370  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
48371
48372  if( op==0 ){
48373    if( pWal->exclusiveMode ){
48374      pWal->exclusiveMode = 0;
48375      if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
48376        pWal->exclusiveMode = 1;
48377      }
48378      rc = pWal->exclusiveMode==0;
48379    }else{
48380      /* Already in locking_mode=NORMAL */
48381      rc = 0;
48382    }
48383  }else if( op>0 ){
48384    assert( pWal->exclusiveMode==0 );
48385    assert( pWal->readLock>=0 );
48386    walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48387    pWal->exclusiveMode = 1;
48388    rc = 1;
48389  }else{
48390    rc = pWal->exclusiveMode==0;
48391  }
48392  return rc;
48393}
48394
48395/*
48396** Return true if the argument is non-NULL and the WAL module is using
48397** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
48398** WAL module is using shared-memory, return false.
48399*/
48400SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
48401  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
48402}
48403
48404#ifdef SQLITE_ENABLE_ZIPVFS
48405/*
48406** If the argument is not NULL, it points to a Wal object that holds a
48407** read-lock. This function returns the database page-size if it is known,
48408** or zero if it is not (or if pWal is NULL).
48409*/
48410SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
48411  assert( pWal==0 || pWal->readLock>=0 );
48412  return (pWal ? pWal->szPage : 0);
48413}
48414#endif
48415
48416#endif /* #ifndef SQLITE_OMIT_WAL */
48417
48418/************** End of wal.c *************************************************/
48419/************** Begin file btmutex.c *****************************************/
48420/*
48421** 2007 August 27
48422**
48423** The author disclaims copyright to this source code.  In place of
48424** a legal notice, here is a blessing:
48425**
48426**    May you do good and not evil.
48427**    May you find forgiveness for yourself and forgive others.
48428**    May you share freely, never taking more than you give.
48429**
48430*************************************************************************
48431**
48432** This file contains code used to implement mutexes on Btree objects.
48433** This code really belongs in btree.c.  But btree.c is getting too
48434** big and we want to break it down some.  This packaged seemed like
48435** a good breakout.
48436*/
48437/************** Include btreeInt.h in the middle of btmutex.c ****************/
48438/************** Begin file btreeInt.h ****************************************/
48439/*
48440** 2004 April 6
48441**
48442** The author disclaims copyright to this source code.  In place of
48443** a legal notice, here is a blessing:
48444**
48445**    May you do good and not evil.
48446**    May you find forgiveness for yourself and forgive others.
48447**    May you share freely, never taking more than you give.
48448**
48449*************************************************************************
48450** This file implements a external (disk-based) database using BTrees.
48451** For a detailed discussion of BTrees, refer to
48452**
48453**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
48454**     "Sorting And Searching", pages 473-480. Addison-Wesley
48455**     Publishing Company, Reading, Massachusetts.
48456**
48457** The basic idea is that each page of the file contains N database
48458** entries and N+1 pointers to subpages.
48459**
48460**   ----------------------------------------------------------------
48461**   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
48462**   ----------------------------------------------------------------
48463**
48464** All of the keys on the page that Ptr(0) points to have values less
48465** than Key(0).  All of the keys on page Ptr(1) and its subpages have
48466** values greater than Key(0) and less than Key(1).  All of the keys
48467** on Ptr(N) and its subpages have values greater than Key(N-1).  And
48468** so forth.
48469**
48470** Finding a particular key requires reading O(log(M)) pages from the
48471** disk where M is the number of entries in the tree.
48472**
48473** In this implementation, a single file can hold one or more separate
48474** BTrees.  Each BTree is identified by the index of its root page.  The
48475** key and data for any entry are combined to form the "payload".  A
48476** fixed amount of payload can be carried directly on the database
48477** page.  If the payload is larger than the preset amount then surplus
48478** bytes are stored on overflow pages.  The payload for an entry
48479** and the preceding pointer are combined to form a "Cell".  Each
48480** page has a small header which contains the Ptr(N) pointer and other
48481** information such as the size of key and data.
48482**
48483** FORMAT DETAILS
48484**
48485** The file is divided into pages.  The first page is called page 1,
48486** the second is page 2, and so forth.  A page number of zero indicates
48487** "no such page".  The page size can be any power of 2 between 512 and 65536.
48488** Each page can be either a btree page, a freelist page, an overflow
48489** page, or a pointer-map page.
48490**
48491** The first page is always a btree page.  The first 100 bytes of the first
48492** page contain a special header (the "file header") that describes the file.
48493** The format of the file header is as follows:
48494**
48495**   OFFSET   SIZE    DESCRIPTION
48496**      0      16     Header string: "SQLite format 3\000"
48497**     16       2     Page size in bytes.
48498**     18       1     File format write version
48499**     19       1     File format read version
48500**     20       1     Bytes of unused space at the end of each page
48501**     21       1     Max embedded payload fraction
48502**     22       1     Min embedded payload fraction
48503**     23       1     Min leaf payload fraction
48504**     24       4     File change counter
48505**     28       4     Reserved for future use
48506**     32       4     First freelist page
48507**     36       4     Number of freelist pages in the file
48508**     40      60     15 4-byte meta values passed to higher layers
48509**
48510**     40       4     Schema cookie
48511**     44       4     File format of schema layer
48512**     48       4     Size of page cache
48513**     52       4     Largest root-page (auto/incr_vacuum)
48514**     56       4     1=UTF-8 2=UTF16le 3=UTF16be
48515**     60       4     User version
48516**     64       4     Incremental vacuum mode
48517**     68       4     unused
48518**     72       4     unused
48519**     76       4     unused
48520**
48521** All of the integer values are big-endian (most significant byte first).
48522**
48523** The file change counter is incremented when the database is changed
48524** This counter allows other processes to know when the file has changed
48525** and thus when they need to flush their cache.
48526**
48527** The max embedded payload fraction is the amount of the total usable
48528** space in a page that can be consumed by a single cell for standard
48529** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
48530** is to limit the maximum cell size so that at least 4 cells will fit
48531** on one page.  Thus the default max embedded payload fraction is 64.
48532**
48533** If the payload for a cell is larger than the max payload, then extra
48534** payload is spilled to overflow pages.  Once an overflow page is allocated,
48535** as many bytes as possible are moved into the overflow pages without letting
48536** the cell size drop below the min embedded payload fraction.
48537**
48538** The min leaf payload fraction is like the min embedded payload fraction
48539** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
48540** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
48541** not specified in the header.
48542**
48543** Each btree pages is divided into three sections:  The header, the
48544** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
48545** file header that occurs before the page header.
48546**
48547**      |----------------|
48548**      | file header    |   100 bytes.  Page 1 only.
48549**      |----------------|
48550**      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
48551**      |----------------|
48552**      | cell pointer   |   |  2 bytes per cell.  Sorted order.
48553**      | array          |   |  Grows downward
48554**      |                |   v
48555**      |----------------|
48556**      | unallocated    |
48557**      | space          |
48558**      |----------------|   ^  Grows upwards
48559**      | cell content   |   |  Arbitrary order interspersed with freeblocks.
48560**      | area           |   |  and free space fragments.
48561**      |----------------|
48562**
48563** The page headers looks like this:
48564**
48565**   OFFSET   SIZE     DESCRIPTION
48566**      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
48567**      1       2      byte offset to the first freeblock
48568**      3       2      number of cells on this page
48569**      5       2      first byte of the cell content area
48570**      7       1      number of fragmented free bytes
48571**      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
48572**
48573** The flags define the format of this btree page.  The leaf flag means that
48574** this page has no children.  The zerodata flag means that this page carries
48575** only keys and no data.  The intkey flag means that the key is a integer
48576** which is stored in the key size entry of the cell header rather than in
48577** the payload area.
48578**
48579** The cell pointer array begins on the first byte after the page header.
48580** The cell pointer array contains zero or more 2-byte numbers which are
48581** offsets from the beginning of the page to the cell content in the cell
48582** content area.  The cell pointers occur in sorted order.  The system strives
48583** to keep free space after the last cell pointer so that new cells can
48584** be easily added without having to defragment the page.
48585**
48586** Cell content is stored at the very end of the page and grows toward the
48587** beginning of the page.
48588**
48589** Unused space within the cell content area is collected into a linked list of
48590** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
48591** to the first freeblock is given in the header.  Freeblocks occur in
48592** increasing order.  Because a freeblock must be at least 4 bytes in size,
48593** any group of 3 or fewer unused bytes in the cell content area cannot
48594** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
48595** a fragment.  The total number of bytes in all fragments is recorded.
48596** in the page header at offset 7.
48597**
48598**    SIZE    DESCRIPTION
48599**      2     Byte offset of the next freeblock
48600**      2     Bytes in this freeblock
48601**
48602** Cells are of variable length.  Cells are stored in the cell content area at
48603** the end of the page.  Pointers to the cells are in the cell pointer array
48604** that immediately follows the page header.  Cells is not necessarily
48605** contiguous or in order, but cell pointers are contiguous and in order.
48606**
48607** Cell content makes use of variable length integers.  A variable
48608** length integer is 1 to 9 bytes where the lower 7 bits of each
48609** byte are used.  The integer consists of all bytes that have bit 8 set and
48610** the first byte with bit 8 clear.  The most significant byte of the integer
48611** appears first.  A variable-length integer may not be more than 9 bytes long.
48612** As a special case, all 8 bytes of the 9th byte are used as data.  This
48613** allows a 64-bit integer to be encoded in 9 bytes.
48614**
48615**    0x00                      becomes  0x00000000
48616**    0x7f                      becomes  0x0000007f
48617**    0x81 0x00                 becomes  0x00000080
48618**    0x82 0x00                 becomes  0x00000100
48619**    0x80 0x7f                 becomes  0x0000007f
48620**    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
48621**    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
48622**
48623** Variable length integers are used for rowids and to hold the number of
48624** bytes of key and data in a btree cell.
48625**
48626** The content of a cell looks like this:
48627**
48628**    SIZE    DESCRIPTION
48629**      4     Page number of the left child. Omitted if leaf flag is set.
48630**     var    Number of bytes of data. Omitted if the zerodata flag is set.
48631**     var    Number of bytes of key. Or the key itself if intkey flag is set.
48632**      *     Payload
48633**      4     First page of the overflow chain.  Omitted if no overflow
48634**
48635** Overflow pages form a linked list.  Each page except the last is completely
48636** filled with data (pagesize - 4 bytes).  The last page can have as little
48637** as 1 byte of data.
48638**
48639**    SIZE    DESCRIPTION
48640**      4     Page number of next overflow page
48641**      *     Data
48642**
48643** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
48644** file header points to the first in a linked list of trunk page.  Each trunk
48645** page points to multiple leaf pages.  The content of a leaf page is
48646** unspecified.  A trunk page looks like this:
48647**
48648**    SIZE    DESCRIPTION
48649**      4     Page number of next trunk page
48650**      4     Number of leaf pointers on this page
48651**      *     zero or more pages numbers of leaves
48652*/
48653
48654
48655/* The following value is the maximum cell size assuming a maximum page
48656** size give above.
48657*/
48658#define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
48659
48660/* The maximum number of cells on a single page of the database.  This
48661** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
48662** plus 2 bytes for the index to the cell in the page header).  Such
48663** small cells will be rare, but they are possible.
48664*/
48665#define MX_CELL(pBt) ((pBt->pageSize-8)/6)
48666
48667/* Forward declarations */
48668typedef struct MemPage MemPage;
48669typedef struct BtLock BtLock;
48670
48671/*
48672** This is a magic string that appears at the beginning of every
48673** SQLite database in order to identify the file as a real database.
48674**
48675** You can change this value at compile-time by specifying a
48676** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
48677** header must be exactly 16 bytes including the zero-terminator so
48678** the string itself should be 15 characters long.  If you change
48679** the header, then your custom library will not be able to read
48680** databases generated by the standard tools and the standard tools
48681** will not be able to read databases created by your custom library.
48682*/
48683#ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
48684#  define SQLITE_FILE_HEADER "SQLite format 3"
48685#endif
48686
48687/*
48688** Page type flags.  An ORed combination of these flags appear as the
48689** first byte of on-disk image of every BTree page.
48690*/
48691#define PTF_INTKEY    0x01
48692#define PTF_ZERODATA  0x02
48693#define PTF_LEAFDATA  0x04
48694#define PTF_LEAF      0x08
48695
48696/*
48697** As each page of the file is loaded into memory, an instance of the following
48698** structure is appended and initialized to zero.  This structure stores
48699** information about the page that is decoded from the raw file page.
48700**
48701** The pParent field points back to the parent page.  This allows us to
48702** walk up the BTree from any leaf to the root.  Care must be taken to
48703** unref() the parent page pointer when this page is no longer referenced.
48704** The pageDestructor() routine handles that chore.
48705**
48706** Access to all fields of this structure is controlled by the mutex
48707** stored in MemPage.pBt->mutex.
48708*/
48709struct MemPage {
48710  u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
48711  u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
48712  u8 intKey;           /* True if intkey flag is set */
48713  u8 leaf;             /* True if leaf flag is set */
48714  u8 hasData;          /* True if this page stores data */
48715  u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
48716  u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
48717  u8 max1bytePayload;  /* min(maxLocal,127) */
48718  u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
48719  u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
48720  u16 cellOffset;      /* Index in aData of first cell pointer */
48721  u16 nFree;           /* Number of free bytes on the page */
48722  u16 nCell;           /* Number of cells on this page, local and ovfl */
48723  u16 maskPage;        /* Mask for page offset */
48724  u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
48725                       ** non-overflow cell */
48726  u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
48727  BtShared *pBt;       /* Pointer to BtShared that this page is part of */
48728  u8 *aData;           /* Pointer to disk image of the page data */
48729  u8 *aDataEnd;        /* One byte past the end of usable data */
48730  u8 *aCellIdx;        /* The cell index area */
48731  DbPage *pDbPage;     /* Pager page handle */
48732  Pgno pgno;           /* Page number for this page */
48733};
48734
48735/*
48736** The in-memory image of a disk page has the auxiliary information appended
48737** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
48738** that extra information.
48739*/
48740#define EXTRA_SIZE sizeof(MemPage)
48741
48742/*
48743** A linked list of the following structures is stored at BtShared.pLock.
48744** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
48745** is opened on the table with root page BtShared.iTable. Locks are removed
48746** from this list when a transaction is committed or rolled back, or when
48747** a btree handle is closed.
48748*/
48749struct BtLock {
48750  Btree *pBtree;        /* Btree handle holding this lock */
48751  Pgno iTable;          /* Root page of table */
48752  u8 eLock;             /* READ_LOCK or WRITE_LOCK */
48753  BtLock *pNext;        /* Next in BtShared.pLock list */
48754};
48755
48756/* Candidate values for BtLock.eLock */
48757#define READ_LOCK     1
48758#define WRITE_LOCK    2
48759
48760/* A Btree handle
48761**
48762** A database connection contains a pointer to an instance of
48763** this object for every database file that it has open.  This structure
48764** is opaque to the database connection.  The database connection cannot
48765** see the internals of this structure and only deals with pointers to
48766** this structure.
48767**
48768** For some database files, the same underlying database cache might be
48769** shared between multiple connections.  In that case, each connection
48770** has it own instance of this object.  But each instance of this object
48771** points to the same BtShared object.  The database cache and the
48772** schema associated with the database file are all contained within
48773** the BtShared object.
48774**
48775** All fields in this structure are accessed under sqlite3.mutex.
48776** The pBt pointer itself may not be changed while there exists cursors
48777** in the referenced BtShared that point back to this Btree since those
48778** cursors have to go through this Btree to find their BtShared and
48779** they often do so without holding sqlite3.mutex.
48780*/
48781struct Btree {
48782  sqlite3 *db;       /* The database connection holding this btree */
48783  BtShared *pBt;     /* Sharable content of this btree */
48784  u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
48785  u8 sharable;       /* True if we can share pBt with another db */
48786  u8 locked;         /* True if db currently has pBt locked */
48787  int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
48788  int nBackup;       /* Number of backup operations reading this btree */
48789  Btree *pNext;      /* List of other sharable Btrees from the same db */
48790  Btree *pPrev;      /* Back pointer of the same list */
48791#ifndef SQLITE_OMIT_SHARED_CACHE
48792  BtLock lock;       /* Object used to lock page 1 */
48793#endif
48794};
48795
48796/*
48797** Btree.inTrans may take one of the following values.
48798**
48799** If the shared-data extension is enabled, there may be multiple users
48800** of the Btree structure. At most one of these may open a write transaction,
48801** but any number may have active read transactions.
48802*/
48803#define TRANS_NONE  0
48804#define TRANS_READ  1
48805#define TRANS_WRITE 2
48806
48807/*
48808** An instance of this object represents a single database file.
48809**
48810** A single database file can be in use at the same time by two
48811** or more database connections.  When two or more connections are
48812** sharing the same database file, each connection has it own
48813** private Btree object for the file and each of those Btrees points
48814** to this one BtShared object.  BtShared.nRef is the number of
48815** connections currently sharing this database file.
48816**
48817** Fields in this structure are accessed under the BtShared.mutex
48818** mutex, except for nRef and pNext which are accessed under the
48819** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
48820** may not be modified once it is initially set as long as nRef>0.
48821** The pSchema field may be set once under BtShared.mutex and
48822** thereafter is unchanged as long as nRef>0.
48823**
48824** isPending:
48825**
48826**   If a BtShared client fails to obtain a write-lock on a database
48827**   table (because there exists one or more read-locks on the table),
48828**   the shared-cache enters 'pending-lock' state and isPending is
48829**   set to true.
48830**
48831**   The shared-cache leaves the 'pending lock' state when either of
48832**   the following occur:
48833**
48834**     1) The current writer (BtShared.pWriter) concludes its transaction, OR
48835**     2) The number of locks held by other connections drops to zero.
48836**
48837**   while in the 'pending-lock' state, no connection may start a new
48838**   transaction.
48839**
48840**   This feature is included to help prevent writer-starvation.
48841*/
48842struct BtShared {
48843  Pager *pPager;        /* The page cache */
48844  sqlite3 *db;          /* Database connection currently using this Btree */
48845  BtCursor *pCursor;    /* A list of all open cursors */
48846  MemPage *pPage1;      /* First page of the database */
48847  u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
48848#ifndef SQLITE_OMIT_AUTOVACUUM
48849  u8 autoVacuum;        /* True if auto-vacuum is enabled */
48850  u8 incrVacuum;        /* True if incr-vacuum is enabled */
48851#endif
48852  u8 inTransaction;     /* Transaction state */
48853  u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
48854  u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
48855  u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
48856  u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
48857  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
48858  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
48859  u32 pageSize;         /* Total number of bytes on a page */
48860  u32 usableSize;       /* Number of usable bytes on each page */
48861  int nTransaction;     /* Number of open transactions (read + write) */
48862  u32 nPage;            /* Number of pages in the database */
48863  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
48864  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
48865  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
48866  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
48867#ifndef SQLITE_OMIT_SHARED_CACHE
48868  int nRef;             /* Number of references to this structure */
48869  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
48870  BtLock *pLock;        /* List of locks held on this shared-btree struct */
48871  Btree *pWriter;       /* Btree with currently open write transaction */
48872#endif
48873  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
48874};
48875
48876/*
48877** Allowed values for BtShared.btsFlags
48878*/
48879#define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
48880#define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
48881#define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
48882#define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
48883#define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
48884#define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
48885#define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
48886
48887/*
48888** An instance of the following structure is used to hold information
48889** about a cell.  The parseCellPtr() function fills in this structure
48890** based on information extract from the raw disk page.
48891*/
48892typedef struct CellInfo CellInfo;
48893struct CellInfo {
48894  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
48895  u8 *pCell;     /* Pointer to the start of cell content */
48896  u32 nData;     /* Number of bytes of data */
48897  u32 nPayload;  /* Total amount of payload */
48898  u16 nHeader;   /* Size of the cell content header in bytes */
48899  u16 nLocal;    /* Amount of payload held locally */
48900  u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
48901  u16 nSize;     /* Size of the cell content on the main b-tree page */
48902};
48903
48904/*
48905** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
48906** this will be declared corrupt. This value is calculated based on a
48907** maximum database size of 2^31 pages a minimum fanout of 2 for a
48908** root-node and 3 for all other internal nodes.
48909**
48910** If a tree that appears to be taller than this is encountered, it is
48911** assumed that the database is corrupt.
48912*/
48913#define BTCURSOR_MAX_DEPTH 20
48914
48915/*
48916** A cursor is a pointer to a particular entry within a particular
48917** b-tree within a database file.
48918**
48919** The entry is identified by its MemPage and the index in
48920** MemPage.aCell[] of the entry.
48921**
48922** A single database file can be shared by two more database connections,
48923** but cursors cannot be shared.  Each cursor is associated with a
48924** particular database connection identified BtCursor.pBtree.db.
48925**
48926** Fields in this structure are accessed under the BtShared.mutex
48927** found at self->pBt->mutex.
48928*/
48929struct BtCursor {
48930  Btree *pBtree;            /* The Btree to which this cursor belongs */
48931  BtShared *pBt;            /* The BtShared this cursor points to */
48932  BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
48933  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
48934#ifndef SQLITE_OMIT_INCRBLOB
48935  Pgno *aOverflow;          /* Cache of overflow page locations */
48936#endif
48937  Pgno pgnoRoot;            /* The root page of this tree */
48938  sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
48939  CellInfo info;            /* A parse of the cell we are pointing at */
48940  i64 nKey;        /* Size of pKey, or last integer key */
48941  void *pKey;      /* Saved key that was cursor's last known position */
48942  int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
48943  u8 wrFlag;                /* True if writable */
48944  u8 atLast;                /* Cursor pointing to the last entry */
48945  u8 validNKey;             /* True if info.nKey is valid */
48946  u8 eState;                /* One of the CURSOR_XXX constants (see below) */
48947#ifndef SQLITE_OMIT_INCRBLOB
48948  u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
48949#endif
48950  i16 iPage;                            /* Index of current page in apPage */
48951  u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
48952  MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
48953};
48954
48955/*
48956** Potential values for BtCursor.eState.
48957**
48958** CURSOR_VALID:
48959**   Cursor points to a valid entry. getPayload() etc. may be called.
48960**
48961** CURSOR_INVALID:
48962**   Cursor does not point to a valid entry. This can happen (for example)
48963**   because the table is empty or because BtreeCursorFirst() has not been
48964**   called.
48965**
48966** CURSOR_REQUIRESEEK:
48967**   The table that this cursor was opened on still exists, but has been
48968**   modified since the cursor was last used. The cursor position is saved
48969**   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
48970**   this state, restoreCursorPosition() can be called to attempt to
48971**   seek the cursor to the saved position.
48972**
48973** CURSOR_FAULT:
48974**   A unrecoverable error (an I/O error or a malloc failure) has occurred
48975**   on a different connection that shares the BtShared cache with this
48976**   cursor.  The error has left the cache in an inconsistent state.
48977**   Do nothing else with this cursor.  Any attempt to use the cursor
48978**   should return the error code stored in BtCursor.skip
48979*/
48980#define CURSOR_INVALID           0
48981#define CURSOR_VALID             1
48982#define CURSOR_REQUIRESEEK       2
48983#define CURSOR_FAULT             3
48984
48985/*
48986** The database page the PENDING_BYTE occupies. This page is never used.
48987*/
48988# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
48989
48990/*
48991** These macros define the location of the pointer-map entry for a
48992** database page. The first argument to each is the number of usable
48993** bytes on each page of the database (often 1024). The second is the
48994** page number to look up in the pointer map.
48995**
48996** PTRMAP_PAGENO returns the database page number of the pointer-map
48997** page that stores the required pointer. PTRMAP_PTROFFSET returns
48998** the offset of the requested map entry.
48999**
49000** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
49001** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
49002** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
49003** this test.
49004*/
49005#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
49006#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
49007#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
49008
49009/*
49010** The pointer map is a lookup table that identifies the parent page for
49011** each child page in the database file.  The parent page is the page that
49012** contains a pointer to the child.  Every page in the database contains
49013** 0 or 1 parent pages.  (In this context 'database page' refers
49014** to any page that is not part of the pointer map itself.)  Each pointer map
49015** entry consists of a single byte 'type' and a 4 byte parent page number.
49016** The PTRMAP_XXX identifiers below are the valid types.
49017**
49018** The purpose of the pointer map is to facility moving pages from one
49019** position in the file to another as part of autovacuum.  When a page
49020** is moved, the pointer in its parent must be updated to point to the
49021** new location.  The pointer map is used to locate the parent page quickly.
49022**
49023** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
49024**                  used in this case.
49025**
49026** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
49027**                  is not used in this case.
49028**
49029** PTRMAP_OVERFLOW1: The database page is the first page in a list of
49030**                   overflow pages. The page number identifies the page that
49031**                   contains the cell with a pointer to this overflow page.
49032**
49033** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
49034**                   overflow pages. The page-number identifies the previous
49035**                   page in the overflow page list.
49036**
49037** PTRMAP_BTREE: The database page is a non-root btree page. The page number
49038**               identifies the parent page in the btree.
49039*/
49040#define PTRMAP_ROOTPAGE 1
49041#define PTRMAP_FREEPAGE 2
49042#define PTRMAP_OVERFLOW1 3
49043#define PTRMAP_OVERFLOW2 4
49044#define PTRMAP_BTREE 5
49045
49046/* A bunch of assert() statements to check the transaction state variables
49047** of handle p (type Btree*) are internally consistent.
49048*/
49049#define btreeIntegrity(p) \
49050  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
49051  assert( p->pBt->inTransaction>=p->inTrans );
49052
49053
49054/*
49055** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
49056** if the database supports auto-vacuum or not. Because it is used
49057** within an expression that is an argument to another macro
49058** (sqliteMallocRaw), it is not possible to use conditional compilation.
49059** So, this macro is defined instead.
49060*/
49061#ifndef SQLITE_OMIT_AUTOVACUUM
49062#define ISAUTOVACUUM (pBt->autoVacuum)
49063#else
49064#define ISAUTOVACUUM 0
49065#endif
49066
49067
49068/*
49069** This structure is passed around through all the sanity checking routines
49070** in order to keep track of some global state information.
49071*/
49072typedef struct IntegrityCk IntegrityCk;
49073struct IntegrityCk {
49074  BtShared *pBt;    /* The tree being checked out */
49075  Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
49076  int *anRef;       /* Number of times each page is referenced */
49077  Pgno nPage;       /* Number of pages in the database */
49078  int mxErr;        /* Stop accumulating errors when this reaches zero */
49079  int nErr;         /* Number of messages written to zErrMsg so far */
49080  int mallocFailed; /* A memory allocation error has occurred */
49081  StrAccum errMsg;  /* Accumulate the error message text here */
49082};
49083
49084/*
49085** Routines to read or write a two- and four-byte big-endian integer values.
49086*/
49087#define get2byte(x)   ((x)[0]<<8 | (x)[1])
49088#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
49089#define get4byte sqlite3Get4byte
49090#define put4byte sqlite3Put4byte
49091
49092/************** End of btreeInt.h ********************************************/
49093/************** Continuing where we left off in btmutex.c ********************/
49094#ifndef SQLITE_OMIT_SHARED_CACHE
49095#if SQLITE_THREADSAFE
49096
49097/*
49098** Obtain the BtShared mutex associated with B-Tree handle p. Also,
49099** set BtShared.db to the database handle associated with p and the
49100** p->locked boolean to true.
49101*/
49102static void lockBtreeMutex(Btree *p){
49103  assert( p->locked==0 );
49104  assert( sqlite3_mutex_notheld(p->pBt->mutex) );
49105  assert( sqlite3_mutex_held(p->db->mutex) );
49106
49107  sqlite3_mutex_enter(p->pBt->mutex);
49108  p->pBt->db = p->db;
49109  p->locked = 1;
49110}
49111
49112/*
49113** Release the BtShared mutex associated with B-Tree handle p and
49114** clear the p->locked boolean.
49115*/
49116static void unlockBtreeMutex(Btree *p){
49117  BtShared *pBt = p->pBt;
49118  assert( p->locked==1 );
49119  assert( sqlite3_mutex_held(pBt->mutex) );
49120  assert( sqlite3_mutex_held(p->db->mutex) );
49121  assert( p->db==pBt->db );
49122
49123  sqlite3_mutex_leave(pBt->mutex);
49124  p->locked = 0;
49125}
49126
49127/*
49128** Enter a mutex on the given BTree object.
49129**
49130** If the object is not sharable, then no mutex is ever required
49131** and this routine is a no-op.  The underlying mutex is non-recursive.
49132** But we keep a reference count in Btree.wantToLock so the behavior
49133** of this interface is recursive.
49134**
49135** To avoid deadlocks, multiple Btrees are locked in the same order
49136** by all database connections.  The p->pNext is a list of other
49137** Btrees belonging to the same database connection as the p Btree
49138** which need to be locked after p.  If we cannot get a lock on
49139** p, then first unlock all of the others on p->pNext, then wait
49140** for the lock to become available on p, then relock all of the
49141** subsequent Btrees that desire a lock.
49142*/
49143SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49144  Btree *pLater;
49145
49146  /* Some basic sanity checking on the Btree.  The list of Btrees
49147  ** connected by pNext and pPrev should be in sorted order by
49148  ** Btree.pBt value. All elements of the list should belong to
49149  ** the same connection. Only shared Btrees are on the list. */
49150  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
49151  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
49152  assert( p->pNext==0 || p->pNext->db==p->db );
49153  assert( p->pPrev==0 || p->pPrev->db==p->db );
49154  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
49155
49156  /* Check for locking consistency */
49157  assert( !p->locked || p->wantToLock>0 );
49158  assert( p->sharable || p->wantToLock==0 );
49159
49160  /* We should already hold a lock on the database connection */
49161  assert( sqlite3_mutex_held(p->db->mutex) );
49162
49163  /* Unless the database is sharable and unlocked, then BtShared.db
49164  ** should already be set correctly. */
49165  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
49166
49167  if( !p->sharable ) return;
49168  p->wantToLock++;
49169  if( p->locked ) return;
49170
49171  /* In most cases, we should be able to acquire the lock we
49172  ** want without having to go throught the ascending lock
49173  ** procedure that follows.  Just be sure not to block.
49174  */
49175  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
49176    p->pBt->db = p->db;
49177    p->locked = 1;
49178    return;
49179  }
49180
49181  /* To avoid deadlock, first release all locks with a larger
49182  ** BtShared address.  Then acquire our lock.  Then reacquire
49183  ** the other BtShared locks that we used to hold in ascending
49184  ** order.
49185  */
49186  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49187    assert( pLater->sharable );
49188    assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
49189    assert( !pLater->locked || pLater->wantToLock>0 );
49190    if( pLater->locked ){
49191      unlockBtreeMutex(pLater);
49192    }
49193  }
49194  lockBtreeMutex(p);
49195  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49196    if( pLater->wantToLock ){
49197      lockBtreeMutex(pLater);
49198    }
49199  }
49200}
49201
49202/*
49203** Exit the recursive mutex on a Btree.
49204*/
49205SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
49206  if( p->sharable ){
49207    assert( p->wantToLock>0 );
49208    p->wantToLock--;
49209    if( p->wantToLock==0 ){
49210      unlockBtreeMutex(p);
49211    }
49212  }
49213}
49214
49215#ifndef NDEBUG
49216/*
49217** Return true if the BtShared mutex is held on the btree, or if the
49218** B-Tree is not marked as sharable.
49219**
49220** This routine is used only from within assert() statements.
49221*/
49222SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
49223  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
49224  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
49225  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
49226  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
49227
49228  return (p->sharable==0 || p->locked);
49229}
49230#endif
49231
49232
49233#ifndef SQLITE_OMIT_INCRBLOB
49234/*
49235** Enter and leave a mutex on a Btree given a cursor owned by that
49236** Btree.  These entry points are used by incremental I/O and can be
49237** omitted if that module is not used.
49238*/
49239SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
49240  sqlite3BtreeEnter(pCur->pBtree);
49241}
49242SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
49243  sqlite3BtreeLeave(pCur->pBtree);
49244}
49245#endif /* SQLITE_OMIT_INCRBLOB */
49246
49247
49248/*
49249** Enter the mutex on every Btree associated with a database
49250** connection.  This is needed (for example) prior to parsing
49251** a statement since we will be comparing table and column names
49252** against all schemas and we do not want those schemas being
49253** reset out from under us.
49254**
49255** There is a corresponding leave-all procedures.
49256**
49257** Enter the mutexes in accending order by BtShared pointer address
49258** to avoid the possibility of deadlock when two threads with
49259** two or more btrees in common both try to lock all their btrees
49260** at the same instant.
49261*/
49262SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49263  int i;
49264  Btree *p;
49265  assert( sqlite3_mutex_held(db->mutex) );
49266  for(i=0; i<db->nDb; i++){
49267    p = db->aDb[i].pBt;
49268    if( p ) sqlite3BtreeEnter(p);
49269  }
49270}
49271SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
49272  int i;
49273  Btree *p;
49274  assert( sqlite3_mutex_held(db->mutex) );
49275  for(i=0; i<db->nDb; i++){
49276    p = db->aDb[i].pBt;
49277    if( p ) sqlite3BtreeLeave(p);
49278  }
49279}
49280
49281/*
49282** Return true if a particular Btree requires a lock.  Return FALSE if
49283** no lock is ever required since it is not sharable.
49284*/
49285SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
49286  return p->sharable;
49287}
49288
49289#ifndef NDEBUG
49290/*
49291** Return true if the current thread holds the database connection
49292** mutex and all required BtShared mutexes.
49293**
49294** This routine is used inside assert() statements only.
49295*/
49296SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
49297  int i;
49298  if( !sqlite3_mutex_held(db->mutex) ){
49299    return 0;
49300  }
49301  for(i=0; i<db->nDb; i++){
49302    Btree *p;
49303    p = db->aDb[i].pBt;
49304    if( p && p->sharable &&
49305         (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
49306      return 0;
49307    }
49308  }
49309  return 1;
49310}
49311#endif /* NDEBUG */
49312
49313#ifndef NDEBUG
49314/*
49315** Return true if the correct mutexes are held for accessing the
49316** db->aDb[iDb].pSchema structure.  The mutexes required for schema
49317** access are:
49318**
49319**   (1) The mutex on db
49320**   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
49321**
49322** If pSchema is not NULL, then iDb is computed from pSchema and
49323** db using sqlite3SchemaToIndex().
49324*/
49325SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
49326  Btree *p;
49327  assert( db!=0 );
49328  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
49329  assert( iDb>=0 && iDb<db->nDb );
49330  if( !sqlite3_mutex_held(db->mutex) ) return 0;
49331  if( iDb==1 ) return 1;
49332  p = db->aDb[iDb].pBt;
49333  assert( p!=0 );
49334  return p->sharable==0 || p->locked==1;
49335}
49336#endif /* NDEBUG */
49337
49338#else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
49339/*
49340** The following are special cases for mutex enter routines for use
49341** in single threaded applications that use shared cache.  Except for
49342** these two routines, all mutex operations are no-ops in that case and
49343** are null #defines in btree.h.
49344**
49345** If shared cache is disabled, then all btree mutex routines, including
49346** the ones below, are no-ops and are null #defines in btree.h.
49347*/
49348
49349SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49350  p->pBt->db = p->db;
49351}
49352SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49353  int i;
49354  for(i=0; i<db->nDb; i++){
49355    Btree *p = db->aDb[i].pBt;
49356    if( p ){
49357      p->pBt->db = p->db;
49358    }
49359  }
49360}
49361#endif /* if SQLITE_THREADSAFE */
49362#endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
49363
49364/************** End of btmutex.c *********************************************/
49365/************** Begin file btree.c *******************************************/
49366/*
49367** 2004 April 6
49368**
49369** The author disclaims copyright to this source code.  In place of
49370** a legal notice, here is a blessing:
49371**
49372**    May you do good and not evil.
49373**    May you find forgiveness for yourself and forgive others.
49374**    May you share freely, never taking more than you give.
49375**
49376*************************************************************************
49377** This file implements a external (disk-based) database using BTrees.
49378** See the header comment on "btreeInt.h" for additional information.
49379** Including a description of file format and an overview of operation.
49380*/
49381
49382/*
49383** The header string that appears at the beginning of every
49384** SQLite database.
49385*/
49386static const char zMagicHeader[] = SQLITE_FILE_HEADER;
49387
49388/*
49389** Set this global variable to 1 to enable tracing using the TRACE
49390** macro.
49391*/
49392#if 0
49393int sqlite3BtreeTrace=1;  /* True to enable tracing */
49394# define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
49395#else
49396# define TRACE(X)
49397#endif
49398
49399/*
49400** Extract a 2-byte big-endian integer from an array of unsigned bytes.
49401** But if the value is zero, make it 65536.
49402**
49403** This routine is used to extract the "offset to cell content area" value
49404** from the header of a btree page.  If the page size is 65536 and the page
49405** is empty, the offset should be 65536, but the 2-byte value stores zero.
49406** This routine makes the necessary adjustment to 65536.
49407*/
49408#define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
49409
49410#ifndef SQLITE_OMIT_SHARED_CACHE
49411/*
49412** A list of BtShared objects that are eligible for participation
49413** in shared cache.  This variable has file scope during normal builds,
49414** but the test harness needs to access it so we make it global for
49415** test builds.
49416**
49417** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
49418*/
49419#ifdef SQLITE_TEST
49420SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49421#else
49422static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49423#endif
49424#endif /* SQLITE_OMIT_SHARED_CACHE */
49425
49426#ifndef SQLITE_OMIT_SHARED_CACHE
49427/*
49428** Enable or disable the shared pager and schema features.
49429**
49430** This routine has no effect on existing database connections.
49431** The shared cache setting effects only future calls to
49432** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
49433*/
49434SQLITE_API int sqlite3_enable_shared_cache(int enable){
49435  sqlite3GlobalConfig.sharedCacheEnabled = enable;
49436  return SQLITE_OK;
49437}
49438#endif
49439
49440
49441
49442#ifdef SQLITE_OMIT_SHARED_CACHE
49443  /*
49444  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
49445  ** and clearAllSharedCacheTableLocks()
49446  ** manipulate entries in the BtShared.pLock linked list used to store
49447  ** shared-cache table level locks. If the library is compiled with the
49448  ** shared-cache feature disabled, then there is only ever one user
49449  ** of each BtShared structure and so this locking is not necessary.
49450  ** So define the lock related functions as no-ops.
49451  */
49452  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
49453  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
49454  #define clearAllSharedCacheTableLocks(a)
49455  #define downgradeAllSharedCacheTableLocks(a)
49456  #define hasSharedCacheTableLock(a,b,c,d) 1
49457  #define hasReadConflicts(a, b) 0
49458#endif
49459
49460#ifndef SQLITE_OMIT_SHARED_CACHE
49461
49462#ifdef SQLITE_DEBUG
49463/*
49464**** This function is only used as part of an assert() statement. ***
49465**
49466** Check to see if pBtree holds the required locks to read or write to the
49467** table with root page iRoot.   Return 1 if it does and 0 if not.
49468**
49469** For example, when writing to a table with root-page iRoot via
49470** Btree connection pBtree:
49471**
49472**    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
49473**
49474** When writing to an index that resides in a sharable database, the
49475** caller should have first obtained a lock specifying the root page of
49476** the corresponding table. This makes things a bit more complicated,
49477** as this module treats each table as a separate structure. To determine
49478** the table corresponding to the index being written, this
49479** function has to search through the database schema.
49480**
49481** Instead of a lock on the table/index rooted at page iRoot, the caller may
49482** hold a write-lock on the schema table (root page 1). This is also
49483** acceptable.
49484*/
49485static int hasSharedCacheTableLock(
49486  Btree *pBtree,         /* Handle that must hold lock */
49487  Pgno iRoot,            /* Root page of b-tree */
49488  int isIndex,           /* True if iRoot is the root of an index b-tree */
49489  int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
49490){
49491  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
49492  Pgno iTab = 0;
49493  BtLock *pLock;
49494
49495  /* If this database is not shareable, or if the client is reading
49496  ** and has the read-uncommitted flag set, then no lock is required.
49497  ** Return true immediately.
49498  */
49499  if( (pBtree->sharable==0)
49500   || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
49501  ){
49502    return 1;
49503  }
49504
49505  /* If the client is reading  or writing an index and the schema is
49506  ** not loaded, then it is too difficult to actually check to see if
49507  ** the correct locks are held.  So do not bother - just return true.
49508  ** This case does not come up very often anyhow.
49509  */
49510  if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
49511    return 1;
49512  }
49513
49514  /* Figure out the root-page that the lock should be held on. For table
49515  ** b-trees, this is just the root page of the b-tree being read or
49516  ** written. For index b-trees, it is the root page of the associated
49517  ** table.  */
49518  if( isIndex ){
49519    HashElem *p;
49520    for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
49521      Index *pIdx = (Index *)sqliteHashData(p);
49522      if( pIdx->tnum==(int)iRoot ){
49523        iTab = pIdx->pTable->tnum;
49524      }
49525    }
49526  }else{
49527    iTab = iRoot;
49528  }
49529
49530  /* Search for the required lock. Either a write-lock on root-page iTab, a
49531  ** write-lock on the schema table, or (if the client is reading) a
49532  ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
49533  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
49534    if( pLock->pBtree==pBtree
49535     && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
49536     && pLock->eLock>=eLockType
49537    ){
49538      return 1;
49539    }
49540  }
49541
49542  /* Failed to find the required lock. */
49543  return 0;
49544}
49545#endif /* SQLITE_DEBUG */
49546
49547#ifdef SQLITE_DEBUG
49548/*
49549**** This function may be used as part of assert() statements only. ****
49550**
49551** Return true if it would be illegal for pBtree to write into the
49552** table or index rooted at iRoot because other shared connections are
49553** simultaneously reading that same table or index.
49554**
49555** It is illegal for pBtree to write if some other Btree object that
49556** shares the same BtShared object is currently reading or writing
49557** the iRoot table.  Except, if the other Btree object has the
49558** read-uncommitted flag set, then it is OK for the other object to
49559** have a read cursor.
49560**
49561** For example, before writing to any part of the table or index
49562** rooted at page iRoot, one should call:
49563**
49564**    assert( !hasReadConflicts(pBtree, iRoot) );
49565*/
49566static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
49567  BtCursor *p;
49568  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
49569    if( p->pgnoRoot==iRoot
49570     && p->pBtree!=pBtree
49571     && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
49572    ){
49573      return 1;
49574    }
49575  }
49576  return 0;
49577}
49578#endif    /* #ifdef SQLITE_DEBUG */
49579
49580/*
49581** Query to see if Btree handle p may obtain a lock of type eLock
49582** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
49583** SQLITE_OK if the lock may be obtained (by calling
49584** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
49585*/
49586static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
49587  BtShared *pBt = p->pBt;
49588  BtLock *pIter;
49589
49590  assert( sqlite3BtreeHoldsMutex(p) );
49591  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49592  assert( p->db!=0 );
49593  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
49594
49595  /* If requesting a write-lock, then the Btree must have an open write
49596  ** transaction on this file. And, obviously, for this to be so there
49597  ** must be an open write transaction on the file itself.
49598  */
49599  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
49600  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
49601
49602  /* This routine is a no-op if the shared-cache is not enabled */
49603  if( !p->sharable ){
49604    return SQLITE_OK;
49605  }
49606
49607  /* If some other connection is holding an exclusive lock, the
49608  ** requested lock may not be obtained.
49609  */
49610  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
49611    sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
49612    return SQLITE_LOCKED_SHAREDCACHE;
49613  }
49614
49615  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49616    /* The condition (pIter->eLock!=eLock) in the following if(...)
49617    ** statement is a simplification of:
49618    **
49619    **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
49620    **
49621    ** since we know that if eLock==WRITE_LOCK, then no other connection
49622    ** may hold a WRITE_LOCK on any table in this file (since there can
49623    ** only be a single writer).
49624    */
49625    assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
49626    assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
49627    if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
49628      sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
49629      if( eLock==WRITE_LOCK ){
49630        assert( p==pBt->pWriter );
49631        pBt->btsFlags |= BTS_PENDING;
49632      }
49633      return SQLITE_LOCKED_SHAREDCACHE;
49634    }
49635  }
49636  return SQLITE_OK;
49637}
49638#endif /* !SQLITE_OMIT_SHARED_CACHE */
49639
49640#ifndef SQLITE_OMIT_SHARED_CACHE
49641/*
49642** Add a lock on the table with root-page iTable to the shared-btree used
49643** by Btree handle p. Parameter eLock must be either READ_LOCK or
49644** WRITE_LOCK.
49645**
49646** This function assumes the following:
49647**
49648**   (a) The specified Btree object p is connected to a sharable
49649**       database (one with the BtShared.sharable flag set), and
49650**
49651**   (b) No other Btree objects hold a lock that conflicts
49652**       with the requested lock (i.e. querySharedCacheTableLock() has
49653**       already been called and returned SQLITE_OK).
49654**
49655** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
49656** is returned if a malloc attempt fails.
49657*/
49658static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
49659  BtShared *pBt = p->pBt;
49660  BtLock *pLock = 0;
49661  BtLock *pIter;
49662
49663  assert( sqlite3BtreeHoldsMutex(p) );
49664  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49665  assert( p->db!=0 );
49666
49667  /* A connection with the read-uncommitted flag set will never try to
49668  ** obtain a read-lock using this function. The only read-lock obtained
49669  ** by a connection in read-uncommitted mode is on the sqlite_master
49670  ** table, and that lock is obtained in BtreeBeginTrans().  */
49671  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
49672
49673  /* This function should only be called on a sharable b-tree after it
49674  ** has been determined that no other b-tree holds a conflicting lock.  */
49675  assert( p->sharable );
49676  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
49677
49678  /* First search the list for an existing lock on this table. */
49679  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49680    if( pIter->iTable==iTable && pIter->pBtree==p ){
49681      pLock = pIter;
49682      break;
49683    }
49684  }
49685
49686  /* If the above search did not find a BtLock struct associating Btree p
49687  ** with table iTable, allocate one and link it into the list.
49688  */
49689  if( !pLock ){
49690    pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
49691    if( !pLock ){
49692      return SQLITE_NOMEM;
49693    }
49694    pLock->iTable = iTable;
49695    pLock->pBtree = p;
49696    pLock->pNext = pBt->pLock;
49697    pBt->pLock = pLock;
49698  }
49699
49700  /* Set the BtLock.eLock variable to the maximum of the current lock
49701  ** and the requested lock. This means if a write-lock was already held
49702  ** and a read-lock requested, we don't incorrectly downgrade the lock.
49703  */
49704  assert( WRITE_LOCK>READ_LOCK );
49705  if( eLock>pLock->eLock ){
49706    pLock->eLock = eLock;
49707  }
49708
49709  return SQLITE_OK;
49710}
49711#endif /* !SQLITE_OMIT_SHARED_CACHE */
49712
49713#ifndef SQLITE_OMIT_SHARED_CACHE
49714/*
49715** Release all the table locks (locks obtained via calls to
49716** the setSharedCacheTableLock() procedure) held by Btree object p.
49717**
49718** This function assumes that Btree p has an open read or write
49719** transaction. If it does not, then the BTS_PENDING flag
49720** may be incorrectly cleared.
49721*/
49722static void clearAllSharedCacheTableLocks(Btree *p){
49723  BtShared *pBt = p->pBt;
49724  BtLock **ppIter = &pBt->pLock;
49725
49726  assert( sqlite3BtreeHoldsMutex(p) );
49727  assert( p->sharable || 0==*ppIter );
49728  assert( p->inTrans>0 );
49729
49730  while( *ppIter ){
49731    BtLock *pLock = *ppIter;
49732    assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
49733    assert( pLock->pBtree->inTrans>=pLock->eLock );
49734    if( pLock->pBtree==p ){
49735      *ppIter = pLock->pNext;
49736      assert( pLock->iTable!=1 || pLock==&p->lock );
49737      if( pLock->iTable!=1 ){
49738        sqlite3_free(pLock);
49739      }
49740    }else{
49741      ppIter = &pLock->pNext;
49742    }
49743  }
49744
49745  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
49746  if( pBt->pWriter==p ){
49747    pBt->pWriter = 0;
49748    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
49749  }else if( pBt->nTransaction==2 ){
49750    /* This function is called when Btree p is concluding its
49751    ** transaction. If there currently exists a writer, and p is not
49752    ** that writer, then the number of locks held by connections other
49753    ** than the writer must be about to drop to zero. In this case
49754    ** set the BTS_PENDING flag to 0.
49755    **
49756    ** If there is not currently a writer, then BTS_PENDING must
49757    ** be zero already. So this next line is harmless in that case.
49758    */
49759    pBt->btsFlags &= ~BTS_PENDING;
49760  }
49761}
49762
49763/*
49764** This function changes all write-locks held by Btree p into read-locks.
49765*/
49766static void downgradeAllSharedCacheTableLocks(Btree *p){
49767  BtShared *pBt = p->pBt;
49768  if( pBt->pWriter==p ){
49769    BtLock *pLock;
49770    pBt->pWriter = 0;
49771    pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
49772    for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
49773      assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
49774      pLock->eLock = READ_LOCK;
49775    }
49776  }
49777}
49778
49779#endif /* SQLITE_OMIT_SHARED_CACHE */
49780
49781static void releasePage(MemPage *pPage);  /* Forward reference */
49782
49783/*
49784***** This routine is used inside of assert() only ****
49785**
49786** Verify that the cursor holds the mutex on its BtShared
49787*/
49788#ifdef SQLITE_DEBUG
49789static int cursorHoldsMutex(BtCursor *p){
49790  return sqlite3_mutex_held(p->pBt->mutex);
49791}
49792#endif
49793
49794
49795#ifndef SQLITE_OMIT_INCRBLOB
49796/*
49797** Invalidate the overflow page-list cache for cursor pCur, if any.
49798*/
49799static void invalidateOverflowCache(BtCursor *pCur){
49800  assert( cursorHoldsMutex(pCur) );
49801  sqlite3_free(pCur->aOverflow);
49802  pCur->aOverflow = 0;
49803}
49804
49805/*
49806** Invalidate the overflow page-list cache for all cursors opened
49807** on the shared btree structure pBt.
49808*/
49809static void invalidateAllOverflowCache(BtShared *pBt){
49810  BtCursor *p;
49811  assert( sqlite3_mutex_held(pBt->mutex) );
49812  for(p=pBt->pCursor; p; p=p->pNext){
49813    invalidateOverflowCache(p);
49814  }
49815}
49816
49817/*
49818** This function is called before modifying the contents of a table
49819** to invalidate any incrblob cursors that are open on the
49820** row or one of the rows being modified.
49821**
49822** If argument isClearTable is true, then the entire contents of the
49823** table is about to be deleted. In this case invalidate all incrblob
49824** cursors open on any row within the table with root-page pgnoRoot.
49825**
49826** Otherwise, if argument isClearTable is false, then the row with
49827** rowid iRow is being replaced or deleted. In this case invalidate
49828** only those incrblob cursors open on that specific row.
49829*/
49830static void invalidateIncrblobCursors(
49831  Btree *pBtree,          /* The database file to check */
49832  i64 iRow,               /* The rowid that might be changing */
49833  int isClearTable        /* True if all rows are being deleted */
49834){
49835  BtCursor *p;
49836  BtShared *pBt = pBtree->pBt;
49837  assert( sqlite3BtreeHoldsMutex(pBtree) );
49838  for(p=pBt->pCursor; p; p=p->pNext){
49839    if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
49840      p->eState = CURSOR_INVALID;
49841    }
49842  }
49843}
49844
49845#else
49846  /* Stub functions when INCRBLOB is omitted */
49847  #define invalidateOverflowCache(x)
49848  #define invalidateAllOverflowCache(x)
49849  #define invalidateIncrblobCursors(x,y,z)
49850#endif /* SQLITE_OMIT_INCRBLOB */
49851
49852/*
49853** Set bit pgno of the BtShared.pHasContent bitvec. This is called
49854** when a page that previously contained data becomes a free-list leaf
49855** page.
49856**
49857** The BtShared.pHasContent bitvec exists to work around an obscure
49858** bug caused by the interaction of two useful IO optimizations surrounding
49859** free-list leaf pages:
49860**
49861**   1) When all data is deleted from a page and the page becomes
49862**      a free-list leaf page, the page is not written to the database
49863**      (as free-list leaf pages contain no meaningful data). Sometimes
49864**      such a page is not even journalled (as it will not be modified,
49865**      why bother journalling it?).
49866**
49867**   2) When a free-list leaf page is reused, its content is not read
49868**      from the database or written to the journal file (why should it
49869**      be, if it is not at all meaningful?).
49870**
49871** By themselves, these optimizations work fine and provide a handy
49872** performance boost to bulk delete or insert operations. However, if
49873** a page is moved to the free-list and then reused within the same
49874** transaction, a problem comes up. If the page is not journalled when
49875** it is moved to the free-list and it is also not journalled when it
49876** is extracted from the free-list and reused, then the original data
49877** may be lost. In the event of a rollback, it may not be possible
49878** to restore the database to its original configuration.
49879**
49880** The solution is the BtShared.pHasContent bitvec. Whenever a page is
49881** moved to become a free-list leaf page, the corresponding bit is
49882** set in the bitvec. Whenever a leaf page is extracted from the free-list,
49883** optimization 2 above is omitted if the corresponding bit is already
49884** set in BtShared.pHasContent. The contents of the bitvec are cleared
49885** at the end of every transaction.
49886*/
49887static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
49888  int rc = SQLITE_OK;
49889  if( !pBt->pHasContent ){
49890    assert( pgno<=pBt->nPage );
49891    pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
49892    if( !pBt->pHasContent ){
49893      rc = SQLITE_NOMEM;
49894    }
49895  }
49896  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
49897    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
49898  }
49899  return rc;
49900}
49901
49902/*
49903** Query the BtShared.pHasContent vector.
49904**
49905** This function is called when a free-list leaf page is removed from the
49906** free-list for reuse. It returns false if it is safe to retrieve the
49907** page from the pager layer with the 'no-content' flag set. True otherwise.
49908*/
49909static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
49910  Bitvec *p = pBt->pHasContent;
49911  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
49912}
49913
49914/*
49915** Clear (destroy) the BtShared.pHasContent bitvec. This should be
49916** invoked at the conclusion of each write-transaction.
49917*/
49918static void btreeClearHasContent(BtShared *pBt){
49919  sqlite3BitvecDestroy(pBt->pHasContent);
49920  pBt->pHasContent = 0;
49921}
49922
49923/*
49924** Save the current cursor position in the variables BtCursor.nKey
49925** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
49926**
49927** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
49928** prior to calling this routine.
49929*/
49930static int saveCursorPosition(BtCursor *pCur){
49931  int rc;
49932
49933  assert( CURSOR_VALID==pCur->eState );
49934  assert( 0==pCur->pKey );
49935  assert( cursorHoldsMutex(pCur) );
49936
49937  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
49938  assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
49939
49940  /* If this is an intKey table, then the above call to BtreeKeySize()
49941  ** stores the integer key in pCur->nKey. In this case this value is
49942  ** all that is required. Otherwise, if pCur is not open on an intKey
49943  ** table, then malloc space for and store the pCur->nKey bytes of key
49944  ** data.
49945  */
49946  if( 0==pCur->apPage[0]->intKey ){
49947    void *pKey = sqlite3Malloc( (int)pCur->nKey );
49948    if( pKey ){
49949      rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
49950      if( rc==SQLITE_OK ){
49951        pCur->pKey = pKey;
49952      }else{
49953        sqlite3_free(pKey);
49954      }
49955    }else{
49956      rc = SQLITE_NOMEM;
49957    }
49958  }
49959  assert( !pCur->apPage[0]->intKey || !pCur->pKey );
49960
49961  if( rc==SQLITE_OK ){
49962    int i;
49963    for(i=0; i<=pCur->iPage; i++){
49964      releasePage(pCur->apPage[i]);
49965      pCur->apPage[i] = 0;
49966    }
49967    pCur->iPage = -1;
49968    pCur->eState = CURSOR_REQUIRESEEK;
49969  }
49970
49971  invalidateOverflowCache(pCur);
49972  return rc;
49973}
49974
49975/*
49976** Save the positions of all cursors (except pExcept) that are open on
49977** the table  with root-page iRoot. Usually, this is called just before cursor
49978** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
49979*/
49980static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
49981  BtCursor *p;
49982  assert( sqlite3_mutex_held(pBt->mutex) );
49983  assert( pExcept==0 || pExcept->pBt==pBt );
49984  for(p=pBt->pCursor; p; p=p->pNext){
49985    if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) &&
49986        p->eState==CURSOR_VALID ){
49987      int rc = saveCursorPosition(p);
49988      if( SQLITE_OK!=rc ){
49989        return rc;
49990      }
49991    }
49992  }
49993  return SQLITE_OK;
49994}
49995
49996/*
49997** Clear the current cursor position.
49998*/
49999SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
50000  assert( cursorHoldsMutex(pCur) );
50001  sqlite3_free(pCur->pKey);
50002  pCur->pKey = 0;
50003  pCur->eState = CURSOR_INVALID;
50004}
50005
50006/*
50007** In this version of BtreeMoveto, pKey is a packed index record
50008** such as is generated by the OP_MakeRecord opcode.  Unpack the
50009** record and then call BtreeMovetoUnpacked() to do the work.
50010*/
50011static int btreeMoveto(
50012  BtCursor *pCur,     /* Cursor open on the btree to be searched */
50013  const void *pKey,   /* Packed key if the btree is an index */
50014  i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
50015  int bias,           /* Bias search to the high end */
50016  int *pRes           /* Write search results here */
50017){
50018  int rc;                    /* Status code */
50019  UnpackedRecord *pIdxKey;   /* Unpacked index key */
50020  char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
50021  char *pFree = 0;
50022
50023  if( pKey ){
50024    assert( nKey==(i64)(int)nKey );
50025    pIdxKey = sqlite3VdbeAllocUnpackedRecord(
50026        pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
50027    );
50028    if( pIdxKey==0 ) return SQLITE_NOMEM;
50029    sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
50030  }else{
50031    pIdxKey = 0;
50032  }
50033  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
50034  if( pFree ){
50035    sqlite3DbFree(pCur->pKeyInfo->db, pFree);
50036  }
50037  return rc;
50038}
50039
50040/*
50041** Restore the cursor to the position it was in (or as close to as possible)
50042** when saveCursorPosition() was called. Note that this call deletes the
50043** saved position info stored by saveCursorPosition(), so there can be
50044** at most one effective restoreCursorPosition() call after each
50045** saveCursorPosition().
50046*/
50047static int btreeRestoreCursorPosition(BtCursor *pCur){
50048  int rc;
50049  assert( cursorHoldsMutex(pCur) );
50050  assert( pCur->eState>=CURSOR_REQUIRESEEK );
50051  if( pCur->eState==CURSOR_FAULT ){
50052    return pCur->skipNext;
50053  }
50054  pCur->eState = CURSOR_INVALID;
50055  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
50056  if( rc==SQLITE_OK ){
50057    sqlite3_free(pCur->pKey);
50058    pCur->pKey = 0;
50059    assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
50060  }
50061  return rc;
50062}
50063
50064#define restoreCursorPosition(p) \
50065  (p->eState>=CURSOR_REQUIRESEEK ? \
50066         btreeRestoreCursorPosition(p) : \
50067         SQLITE_OK)
50068
50069/*
50070** Determine whether or not a cursor has moved from the position it
50071** was last placed at.  Cursors can move when the row they are pointing
50072** at is deleted out from under them.
50073**
50074** This routine returns an error code if something goes wrong.  The
50075** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
50076*/
50077SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
50078  int rc;
50079
50080  rc = restoreCursorPosition(pCur);
50081  if( rc ){
50082    *pHasMoved = 1;
50083    return rc;
50084  }
50085  if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
50086    *pHasMoved = 1;
50087  }else{
50088    *pHasMoved = 0;
50089  }
50090  return SQLITE_OK;
50091}
50092
50093#ifndef SQLITE_OMIT_AUTOVACUUM
50094/*
50095** Given a page number of a regular database page, return the page
50096** number for the pointer-map page that contains the entry for the
50097** input page number.
50098**
50099** Return 0 (not a valid page) for pgno==1 since there is
50100** no pointer map associated with page 1.  The integrity_check logic
50101** requires that ptrmapPageno(*,1)!=1.
50102*/
50103static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
50104  int nPagesPerMapPage;
50105  Pgno iPtrMap, ret;
50106  assert( sqlite3_mutex_held(pBt->mutex) );
50107  if( pgno<2 ) return 0;
50108  nPagesPerMapPage = (pBt->usableSize/5)+1;
50109  iPtrMap = (pgno-2)/nPagesPerMapPage;
50110  ret = (iPtrMap*nPagesPerMapPage) + 2;
50111  if( ret==PENDING_BYTE_PAGE(pBt) ){
50112    ret++;
50113  }
50114  return ret;
50115}
50116
50117/*
50118** Write an entry into the pointer map.
50119**
50120** This routine updates the pointer map entry for page number 'key'
50121** so that it maps to type 'eType' and parent page number 'pgno'.
50122**
50123** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
50124** a no-op.  If an error occurs, the appropriate error code is written
50125** into *pRC.
50126*/
50127static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
50128  DbPage *pDbPage;  /* The pointer map page */
50129  u8 *pPtrmap;      /* The pointer map data */
50130  Pgno iPtrmap;     /* The pointer map page number */
50131  int offset;       /* Offset in pointer map page */
50132  int rc;           /* Return code from subfunctions */
50133
50134  if( *pRC ) return;
50135
50136  assert( sqlite3_mutex_held(pBt->mutex) );
50137  /* The master-journal page number must never be used as a pointer map page */
50138  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
50139
50140  assert( pBt->autoVacuum );
50141  if( key==0 ){
50142    *pRC = SQLITE_CORRUPT_BKPT;
50143    return;
50144  }
50145  iPtrmap = PTRMAP_PAGENO(pBt, key);
50146  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50147  if( rc!=SQLITE_OK ){
50148    *pRC = rc;
50149    return;
50150  }
50151  offset = PTRMAP_PTROFFSET(iPtrmap, key);
50152  if( offset<0 ){
50153    *pRC = SQLITE_CORRUPT_BKPT;
50154    goto ptrmap_exit;
50155  }
50156  assert( offset <= (int)pBt->usableSize-5 );
50157  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50158
50159  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
50160    TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
50161    *pRC= rc = sqlite3PagerWrite(pDbPage);
50162    if( rc==SQLITE_OK ){
50163      pPtrmap[offset] = eType;
50164      put4byte(&pPtrmap[offset+1], parent);
50165    }
50166  }
50167
50168ptrmap_exit:
50169  sqlite3PagerUnref(pDbPage);
50170}
50171
50172/*
50173** Read an entry from the pointer map.
50174**
50175** This routine retrieves the pointer map entry for page 'key', writing
50176** the type and parent page number to *pEType and *pPgno respectively.
50177** An error code is returned if something goes wrong, otherwise SQLITE_OK.
50178*/
50179static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
50180  DbPage *pDbPage;   /* The pointer map page */
50181  int iPtrmap;       /* Pointer map page index */
50182  u8 *pPtrmap;       /* Pointer map page data */
50183  int offset;        /* Offset of entry in pointer map */
50184  int rc;
50185
50186  assert( sqlite3_mutex_held(pBt->mutex) );
50187
50188  iPtrmap = PTRMAP_PAGENO(pBt, key);
50189  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50190  if( rc!=0 ){
50191    return rc;
50192  }
50193  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50194
50195  offset = PTRMAP_PTROFFSET(iPtrmap, key);
50196  if( offset<0 ){
50197    sqlite3PagerUnref(pDbPage);
50198    return SQLITE_CORRUPT_BKPT;
50199  }
50200  assert( offset <= (int)pBt->usableSize-5 );
50201  assert( pEType!=0 );
50202  *pEType = pPtrmap[offset];
50203  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
50204
50205  sqlite3PagerUnref(pDbPage);
50206  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
50207  return SQLITE_OK;
50208}
50209
50210#else /* if defined SQLITE_OMIT_AUTOVACUUM */
50211  #define ptrmapPut(w,x,y,z,rc)
50212  #define ptrmapGet(w,x,y,z) SQLITE_OK
50213  #define ptrmapPutOvflPtr(x, y, rc)
50214#endif
50215
50216/*
50217** Given a btree page and a cell index (0 means the first cell on
50218** the page, 1 means the second cell, and so forth) return a pointer
50219** to the cell content.
50220**
50221** This routine works only for pages that do not contain overflow cells.
50222*/
50223#define findCell(P,I) \
50224  ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
50225#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
50226
50227
50228/*
50229** This a more complex version of findCell() that works for
50230** pages that do contain overflow cells.
50231*/
50232static u8 *findOverflowCell(MemPage *pPage, int iCell){
50233  int i;
50234  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50235  for(i=pPage->nOverflow-1; i>=0; i--){
50236    int k;
50237    k = pPage->aiOvfl[i];
50238    if( k<=iCell ){
50239      if( k==iCell ){
50240        return pPage->apOvfl[i];
50241      }
50242      iCell--;
50243    }
50244  }
50245  return findCell(pPage, iCell);
50246}
50247
50248/*
50249** Parse a cell content block and fill in the CellInfo structure.  There
50250** are two versions of this function.  btreeParseCell() takes a
50251** cell index as the second argument and btreeParseCellPtr()
50252** takes a pointer to the body of the cell as its second argument.
50253**
50254** Within this file, the parseCell() macro can be called instead of
50255** btreeParseCellPtr(). Using some compilers, this will be faster.
50256*/
50257static void btreeParseCellPtr(
50258  MemPage *pPage,         /* Page containing the cell */
50259  u8 *pCell,              /* Pointer to the cell text. */
50260  CellInfo *pInfo         /* Fill in this structure */
50261){
50262  u16 n;                  /* Number bytes in cell content header */
50263  u32 nPayload;           /* Number of bytes of cell payload */
50264
50265  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50266
50267  pInfo->pCell = pCell;
50268  assert( pPage->leaf==0 || pPage->leaf==1 );
50269  n = pPage->childPtrSize;
50270  assert( n==4-4*pPage->leaf );
50271  if( pPage->intKey ){
50272    if( pPage->hasData ){
50273      n += getVarint32(&pCell[n], nPayload);
50274    }else{
50275      nPayload = 0;
50276    }
50277    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
50278    pInfo->nData = nPayload;
50279  }else{
50280    pInfo->nData = 0;
50281    n += getVarint32(&pCell[n], nPayload);
50282    pInfo->nKey = nPayload;
50283  }
50284  pInfo->nPayload = nPayload;
50285  pInfo->nHeader = n;
50286  testcase( nPayload==pPage->maxLocal );
50287  testcase( nPayload==pPage->maxLocal+1 );
50288  if( likely(nPayload<=pPage->maxLocal) ){
50289    /* This is the (easy) common case where the entire payload fits
50290    ** on the local page.  No overflow is required.
50291    */
50292    if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
50293    pInfo->nLocal = (u16)nPayload;
50294    pInfo->iOverflow = 0;
50295  }else{
50296    /* If the payload will not fit completely on the local page, we have
50297    ** to decide how much to store locally and how much to spill onto
50298    ** overflow pages.  The strategy is to minimize the amount of unused
50299    ** space on overflow pages while keeping the amount of local storage
50300    ** in between minLocal and maxLocal.
50301    **
50302    ** Warning:  changing the way overflow payload is distributed in any
50303    ** way will result in an incompatible file format.
50304    */
50305    int minLocal;  /* Minimum amount of payload held locally */
50306    int maxLocal;  /* Maximum amount of payload held locally */
50307    int surplus;   /* Overflow payload available for local storage */
50308
50309    minLocal = pPage->minLocal;
50310    maxLocal = pPage->maxLocal;
50311    surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
50312    testcase( surplus==maxLocal );
50313    testcase( surplus==maxLocal+1 );
50314    if( surplus <= maxLocal ){
50315      pInfo->nLocal = (u16)surplus;
50316    }else{
50317      pInfo->nLocal = (u16)minLocal;
50318    }
50319    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
50320    pInfo->nSize = pInfo->iOverflow + 4;
50321  }
50322}
50323#define parseCell(pPage, iCell, pInfo) \
50324  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
50325static void btreeParseCell(
50326  MemPage *pPage,         /* Page containing the cell */
50327  int iCell,              /* The cell index.  First cell is 0 */
50328  CellInfo *pInfo         /* Fill in this structure */
50329){
50330  parseCell(pPage, iCell, pInfo);
50331}
50332
50333/*
50334** Compute the total number of bytes that a Cell needs in the cell
50335** data area of the btree-page.  The return number includes the cell
50336** data header and the local payload, but not any overflow page or
50337** the space used by the cell pointer.
50338*/
50339static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
50340  u8 *pIter = &pCell[pPage->childPtrSize];
50341  u32 nSize;
50342
50343#ifdef SQLITE_DEBUG
50344  /* The value returned by this function should always be the same as
50345  ** the (CellInfo.nSize) value found by doing a full parse of the
50346  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
50347  ** this function verifies that this invariant is not violated. */
50348  CellInfo debuginfo;
50349  btreeParseCellPtr(pPage, pCell, &debuginfo);
50350#endif
50351
50352  if( pPage->intKey ){
50353    u8 *pEnd;
50354    if( pPage->hasData ){
50355      pIter += getVarint32(pIter, nSize);
50356    }else{
50357      nSize = 0;
50358    }
50359
50360    /* pIter now points at the 64-bit integer key value, a variable length
50361    ** integer. The following block moves pIter to point at the first byte
50362    ** past the end of the key value. */
50363    pEnd = &pIter[9];
50364    while( (*pIter++)&0x80 && pIter<pEnd );
50365  }else{
50366    pIter += getVarint32(pIter, nSize);
50367  }
50368
50369  testcase( nSize==pPage->maxLocal );
50370  testcase( nSize==pPage->maxLocal+1 );
50371  if( nSize>pPage->maxLocal ){
50372    int minLocal = pPage->minLocal;
50373    nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
50374    testcase( nSize==pPage->maxLocal );
50375    testcase( nSize==pPage->maxLocal+1 );
50376    if( nSize>pPage->maxLocal ){
50377      nSize = minLocal;
50378    }
50379    nSize += 4;
50380  }
50381  nSize += (u32)(pIter - pCell);
50382
50383  /* The minimum size of any cell is 4 bytes. */
50384  if( nSize<4 ){
50385    nSize = 4;
50386  }
50387
50388  assert( nSize==debuginfo.nSize );
50389  return (u16)nSize;
50390}
50391
50392#ifdef SQLITE_DEBUG
50393/* This variation on cellSizePtr() is used inside of assert() statements
50394** only. */
50395static u16 cellSize(MemPage *pPage, int iCell){
50396  return cellSizePtr(pPage, findCell(pPage, iCell));
50397}
50398#endif
50399
50400#ifndef SQLITE_OMIT_AUTOVACUUM
50401/*
50402** If the cell pCell, part of page pPage contains a pointer
50403** to an overflow page, insert an entry into the pointer-map
50404** for the overflow page.
50405*/
50406static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
50407  CellInfo info;
50408  if( *pRC ) return;
50409  assert( pCell!=0 );
50410  btreeParseCellPtr(pPage, pCell, &info);
50411  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
50412  if( info.iOverflow ){
50413    Pgno ovfl = get4byte(&pCell[info.iOverflow]);
50414    ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
50415  }
50416}
50417#endif
50418
50419
50420/*
50421** Defragment the page given.  All Cells are moved to the
50422** end of the page and all free space is collected into one
50423** big FreeBlk that occurs in between the header and cell
50424** pointer array and the cell content area.
50425*/
50426static int defragmentPage(MemPage *pPage){
50427  int i;                     /* Loop counter */
50428  int pc;                    /* Address of a i-th cell */
50429  int hdr;                   /* Offset to the page header */
50430  int size;                  /* Size of a cell */
50431  int usableSize;            /* Number of usable bytes on a page */
50432  int cellOffset;            /* Offset to the cell pointer array */
50433  int cbrk;                  /* Offset to the cell content area */
50434  int nCell;                 /* Number of cells on the page */
50435  unsigned char *data;       /* The page data */
50436  unsigned char *temp;       /* Temp area for cell content */
50437  int iCellFirst;            /* First allowable cell index */
50438  int iCellLast;             /* Last possible cell index */
50439
50440
50441  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50442  assert( pPage->pBt!=0 );
50443  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
50444  assert( pPage->nOverflow==0 );
50445  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50446  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
50447  data = pPage->aData;
50448  hdr = pPage->hdrOffset;
50449  cellOffset = pPage->cellOffset;
50450  nCell = pPage->nCell;
50451  assert( nCell==get2byte(&data[hdr+3]) );
50452  usableSize = pPage->pBt->usableSize;
50453  cbrk = get2byte(&data[hdr+5]);
50454  memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
50455  cbrk = usableSize;
50456  iCellFirst = cellOffset + 2*nCell;
50457  iCellLast = usableSize - 4;
50458  for(i=0; i<nCell; i++){
50459    u8 *pAddr;     /* The i-th cell pointer */
50460    pAddr = &data[cellOffset + i*2];
50461    pc = get2byte(pAddr);
50462    testcase( pc==iCellFirst );
50463    testcase( pc==iCellLast );
50464#if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50465    /* These conditions have already been verified in btreeInitPage()
50466    ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
50467    */
50468    if( pc<iCellFirst || pc>iCellLast ){
50469      return SQLITE_CORRUPT_BKPT;
50470    }
50471#endif
50472    assert( pc>=iCellFirst && pc<=iCellLast );
50473    size = cellSizePtr(pPage, &temp[pc]);
50474    cbrk -= size;
50475#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50476    if( cbrk<iCellFirst ){
50477      return SQLITE_CORRUPT_BKPT;
50478    }
50479#else
50480    if( cbrk<iCellFirst || pc+size>usableSize ){
50481      return SQLITE_CORRUPT_BKPT;
50482    }
50483#endif
50484    assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
50485    testcase( cbrk+size==usableSize );
50486    testcase( pc+size==usableSize );
50487    memcpy(&data[cbrk], &temp[pc], size);
50488    put2byte(pAddr, cbrk);
50489  }
50490  assert( cbrk>=iCellFirst );
50491  put2byte(&data[hdr+5], cbrk);
50492  data[hdr+1] = 0;
50493  data[hdr+2] = 0;
50494  data[hdr+7] = 0;
50495  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
50496  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50497  if( cbrk-iCellFirst!=pPage->nFree ){
50498    return SQLITE_CORRUPT_BKPT;
50499  }
50500  return SQLITE_OK;
50501}
50502
50503/*
50504** Allocate nByte bytes of space from within the B-Tree page passed
50505** as the first argument. Write into *pIdx the index into pPage->aData[]
50506** of the first byte of allocated space. Return either SQLITE_OK or
50507** an error code (usually SQLITE_CORRUPT).
50508**
50509** The caller guarantees that there is sufficient space to make the
50510** allocation.  This routine might need to defragment in order to bring
50511** all the space together, however.  This routine will avoid using
50512** the first two bytes past the cell pointer area since presumably this
50513** allocation is being made in order to insert a new cell, so we will
50514** also end up needing a new cell pointer.
50515*/
50516static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
50517  const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
50518  u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
50519  int nFrag;                           /* Number of fragmented bytes on pPage */
50520  int top;                             /* First byte of cell content area */
50521  int gap;        /* First byte of gap between cell pointers and cell content */
50522  int rc;         /* Integer return code */
50523  int usableSize; /* Usable size of the page */
50524
50525  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50526  assert( pPage->pBt );
50527  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50528  assert( nByte>=0 );  /* Minimum cell size is 4 */
50529  assert( pPage->nFree>=nByte );
50530  assert( pPage->nOverflow==0 );
50531  usableSize = pPage->pBt->usableSize;
50532  assert( nByte < usableSize-8 );
50533
50534  nFrag = data[hdr+7];
50535  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
50536  gap = pPage->cellOffset + 2*pPage->nCell;
50537  top = get2byteNotZero(&data[hdr+5]);
50538  if( gap>top ) return SQLITE_CORRUPT_BKPT;
50539  testcase( gap+2==top );
50540  testcase( gap+1==top );
50541  testcase( gap==top );
50542
50543  if( nFrag>=60 ){
50544    /* Always defragment highly fragmented pages */
50545    rc = defragmentPage(pPage);
50546    if( rc ) return rc;
50547    top = get2byteNotZero(&data[hdr+5]);
50548  }else if( gap+2<=top ){
50549    /* Search the freelist looking for a free slot big enough to satisfy
50550    ** the request. The allocation is made from the first free slot in
50551    ** the list that is large enough to accomadate it.
50552    */
50553    int pc, addr;
50554    for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50555      int size;            /* Size of the free slot */
50556      if( pc>usableSize-4 || pc<addr+4 ){
50557        return SQLITE_CORRUPT_BKPT;
50558      }
50559      size = get2byte(&data[pc+2]);
50560      if( size>=nByte ){
50561        int x = size - nByte;
50562        testcase( x==4 );
50563        testcase( x==3 );
50564        if( x<4 ){
50565          /* Remove the slot from the free-list. Update the number of
50566          ** fragmented bytes within the page. */
50567          memcpy(&data[addr], &data[pc], 2);
50568          data[hdr+7] = (u8)(nFrag + x);
50569        }else if( size+pc > usableSize ){
50570          return SQLITE_CORRUPT_BKPT;
50571        }else{
50572          /* The slot remains on the free-list. Reduce its size to account
50573          ** for the portion used by the new allocation. */
50574          put2byte(&data[pc+2], x);
50575        }
50576        *pIdx = pc + x;
50577        return SQLITE_OK;
50578      }
50579    }
50580  }
50581
50582  /* Check to make sure there is enough space in the gap to satisfy
50583  ** the allocation.  If not, defragment.
50584  */
50585  testcase( gap+2+nByte==top );
50586  if( gap+2+nByte>top ){
50587    rc = defragmentPage(pPage);
50588    if( rc ) return rc;
50589    top = get2byteNotZero(&data[hdr+5]);
50590    assert( gap+nByte<=top );
50591  }
50592
50593
50594  /* Allocate memory from the gap in between the cell pointer array
50595  ** and the cell content area.  The btreeInitPage() call has already
50596  ** validated the freelist.  Given that the freelist is valid, there
50597  ** is no way that the allocation can extend off the end of the page.
50598  ** The assert() below verifies the previous sentence.
50599  */
50600  top -= nByte;
50601  put2byte(&data[hdr+5], top);
50602  assert( top+nByte <= (int)pPage->pBt->usableSize );
50603  *pIdx = top;
50604  return SQLITE_OK;
50605}
50606
50607/*
50608** Return a section of the pPage->aData to the freelist.
50609** The first byte of the new free block is pPage->aDisk[start]
50610** and the size of the block is "size" bytes.
50611**
50612** Most of the effort here is involved in coalesing adjacent
50613** free blocks into a single big free block.
50614*/
50615static int freeSpace(MemPage *pPage, int start, int size){
50616  int addr, pbegin, hdr;
50617  int iLast;                        /* Largest possible freeblock offset */
50618  unsigned char *data = pPage->aData;
50619
50620  assert( pPage->pBt!=0 );
50621  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50622  assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
50623  assert( (start + size) <= (int)pPage->pBt->usableSize );
50624  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50625  assert( size>=0 );   /* Minimum cell size is 4 */
50626
50627  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
50628    /* Overwrite deleted information with zeros when the secure_delete
50629    ** option is enabled */
50630    memset(&data[start], 0, size);
50631  }
50632
50633  /* Add the space back into the linked list of freeblocks.  Note that
50634  ** even though the freeblock list was checked by btreeInitPage(),
50635  ** btreeInitPage() did not detect overlapping cells or
50636  ** freeblocks that overlapped cells.   Nor does it detect when the
50637  ** cell content area exceeds the value in the page header.  If these
50638  ** situations arise, then subsequent insert operations might corrupt
50639  ** the freelist.  So we do need to check for corruption while scanning
50640  ** the freelist.
50641  */
50642  hdr = pPage->hdrOffset;
50643  addr = hdr + 1;
50644  iLast = pPage->pBt->usableSize - 4;
50645  assert( start<=iLast );
50646  while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
50647    if( pbegin<addr+4 ){
50648      return SQLITE_CORRUPT_BKPT;
50649    }
50650    addr = pbegin;
50651  }
50652  if( pbegin>iLast ){
50653    return SQLITE_CORRUPT_BKPT;
50654  }
50655  assert( pbegin>addr || pbegin==0 );
50656  put2byte(&data[addr], start);
50657  put2byte(&data[start], pbegin);
50658  put2byte(&data[start+2], size);
50659  pPage->nFree = pPage->nFree + (u16)size;
50660
50661  /* Coalesce adjacent free blocks */
50662  addr = hdr + 1;
50663  while( (pbegin = get2byte(&data[addr]))>0 ){
50664    int pnext, psize, x;
50665    assert( pbegin>addr );
50666    assert( pbegin <= (int)pPage->pBt->usableSize-4 );
50667    pnext = get2byte(&data[pbegin]);
50668    psize = get2byte(&data[pbegin+2]);
50669    if( pbegin + psize + 3 >= pnext && pnext>0 ){
50670      int frag = pnext - (pbegin+psize);
50671      if( (frag<0) || (frag>(int)data[hdr+7]) ){
50672        return SQLITE_CORRUPT_BKPT;
50673      }
50674      data[hdr+7] -= (u8)frag;
50675      x = get2byte(&data[pnext]);
50676      put2byte(&data[pbegin], x);
50677      x = pnext + get2byte(&data[pnext+2]) - pbegin;
50678      put2byte(&data[pbegin+2], x);
50679    }else{
50680      addr = pbegin;
50681    }
50682  }
50683
50684  /* If the cell content area begins with a freeblock, remove it. */
50685  if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
50686    int top;
50687    pbegin = get2byte(&data[hdr+1]);
50688    memcpy(&data[hdr+1], &data[pbegin], 2);
50689    top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
50690    put2byte(&data[hdr+5], top);
50691  }
50692  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50693  return SQLITE_OK;
50694}
50695
50696/*
50697** Decode the flags byte (the first byte of the header) for a page
50698** and initialize fields of the MemPage structure accordingly.
50699**
50700** Only the following combinations are supported.  Anything different
50701** indicates a corrupt database files:
50702**
50703**         PTF_ZERODATA
50704**         PTF_ZERODATA | PTF_LEAF
50705**         PTF_LEAFDATA | PTF_INTKEY
50706**         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
50707*/
50708static int decodeFlags(MemPage *pPage, int flagByte){
50709  BtShared *pBt;     /* A copy of pPage->pBt */
50710
50711  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
50712  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50713  pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
50714  flagByte &= ~PTF_LEAF;
50715  pPage->childPtrSize = 4-4*pPage->leaf;
50716  pBt = pPage->pBt;
50717  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
50718    pPage->intKey = 1;
50719    pPage->hasData = pPage->leaf;
50720    pPage->maxLocal = pBt->maxLeaf;
50721    pPage->minLocal = pBt->minLeaf;
50722  }else if( flagByte==PTF_ZERODATA ){
50723    pPage->intKey = 0;
50724    pPage->hasData = 0;
50725    pPage->maxLocal = pBt->maxLocal;
50726    pPage->minLocal = pBt->minLocal;
50727  }else{
50728    return SQLITE_CORRUPT_BKPT;
50729  }
50730  pPage->max1bytePayload = pBt->max1bytePayload;
50731  return SQLITE_OK;
50732}
50733
50734/*
50735** Initialize the auxiliary information for a disk block.
50736**
50737** Return SQLITE_OK on success.  If we see that the page does
50738** not contain a well-formed database page, then return
50739** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
50740** guarantee that the page is well-formed.  It only shows that
50741** we failed to detect any corruption.
50742*/
50743static int btreeInitPage(MemPage *pPage){
50744
50745  assert( pPage->pBt!=0 );
50746  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50747  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
50748  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
50749  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
50750
50751  if( !pPage->isInit ){
50752    u16 pc;            /* Address of a freeblock within pPage->aData[] */
50753    u8 hdr;            /* Offset to beginning of page header */
50754    u8 *data;          /* Equal to pPage->aData */
50755    BtShared *pBt;        /* The main btree structure */
50756    int usableSize;    /* Amount of usable space on each page */
50757    u16 cellOffset;    /* Offset from start of page to first cell pointer */
50758    int nFree;         /* Number of unused bytes on the page */
50759    int top;           /* First byte of the cell content area */
50760    int iCellFirst;    /* First allowable cell or freeblock offset */
50761    int iCellLast;     /* Last possible cell or freeblock offset */
50762
50763    pBt = pPage->pBt;
50764
50765    hdr = pPage->hdrOffset;
50766    data = pPage->aData;
50767    if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
50768    assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
50769    pPage->maskPage = (u16)(pBt->pageSize - 1);
50770    pPage->nOverflow = 0;
50771    usableSize = pBt->usableSize;
50772    pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
50773    pPage->aDataEnd = &data[usableSize];
50774    pPage->aCellIdx = &data[cellOffset];
50775    top = get2byteNotZero(&data[hdr+5]);
50776    pPage->nCell = get2byte(&data[hdr+3]);
50777    if( pPage->nCell>MX_CELL(pBt) ){
50778      /* To many cells for a single page.  The page must be corrupt */
50779      return SQLITE_CORRUPT_BKPT;
50780    }
50781    testcase( pPage->nCell==MX_CELL(pBt) );
50782
50783    /* A malformed database page might cause us to read past the end
50784    ** of page when parsing a cell.
50785    **
50786    ** The following block of code checks early to see if a cell extends
50787    ** past the end of a page boundary and causes SQLITE_CORRUPT to be
50788    ** returned if it does.
50789    */
50790    iCellFirst = cellOffset + 2*pPage->nCell;
50791    iCellLast = usableSize - 4;
50792#if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50793    {
50794      int i;            /* Index into the cell pointer array */
50795      int sz;           /* Size of a cell */
50796
50797      if( !pPage->leaf ) iCellLast--;
50798      for(i=0; i<pPage->nCell; i++){
50799        pc = get2byte(&data[cellOffset+i*2]);
50800        testcase( pc==iCellFirst );
50801        testcase( pc==iCellLast );
50802        if( pc<iCellFirst || pc>iCellLast ){
50803          return SQLITE_CORRUPT_BKPT;
50804        }
50805        sz = cellSizePtr(pPage, &data[pc]);
50806        testcase( pc+sz==usableSize );
50807        if( pc+sz>usableSize ){
50808          return SQLITE_CORRUPT_BKPT;
50809        }
50810      }
50811      if( !pPage->leaf ) iCellLast++;
50812    }
50813#endif
50814
50815    /* Compute the total free space on the page */
50816    pc = get2byte(&data[hdr+1]);
50817    nFree = data[hdr+7] + top;
50818    while( pc>0 ){
50819      u16 next, size;
50820      if( pc<iCellFirst || pc>iCellLast ){
50821        /* Start of free block is off the page */
50822        return SQLITE_CORRUPT_BKPT;
50823      }
50824      next = get2byte(&data[pc]);
50825      size = get2byte(&data[pc+2]);
50826      if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
50827        /* Free blocks must be in ascending order. And the last byte of
50828	** the free-block must lie on the database page.  */
50829        return SQLITE_CORRUPT_BKPT;
50830      }
50831      nFree = nFree + size;
50832      pc = next;
50833    }
50834
50835    /* At this point, nFree contains the sum of the offset to the start
50836    ** of the cell-content area plus the number of free bytes within
50837    ** the cell-content area. If this is greater than the usable-size
50838    ** of the page, then the page must be corrupted. This check also
50839    ** serves to verify that the offset to the start of the cell-content
50840    ** area, according to the page header, lies within the page.
50841    */
50842    if( nFree>usableSize ){
50843      return SQLITE_CORRUPT_BKPT;
50844    }
50845    pPage->nFree = (u16)(nFree - iCellFirst);
50846    pPage->isInit = 1;
50847  }
50848  return SQLITE_OK;
50849}
50850
50851/*
50852** Set up a raw page so that it looks like a database page holding
50853** no entries.
50854*/
50855static void zeroPage(MemPage *pPage, int flags){
50856  unsigned char *data = pPage->aData;
50857  BtShared *pBt = pPage->pBt;
50858  u8 hdr = pPage->hdrOffset;
50859  u16 first;
50860
50861  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
50862  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
50863  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
50864  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50865  assert( sqlite3_mutex_held(pBt->mutex) );
50866  if( pBt->btsFlags & BTS_SECURE_DELETE ){
50867    memset(&data[hdr], 0, pBt->usableSize - hdr);
50868  }
50869  data[hdr] = (char)flags;
50870  first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
50871  memset(&data[hdr+1], 0, 4);
50872  data[hdr+7] = 0;
50873  put2byte(&data[hdr+5], pBt->usableSize);
50874  pPage->nFree = (u16)(pBt->usableSize - first);
50875  decodeFlags(pPage, flags);
50876  pPage->hdrOffset = hdr;
50877  pPage->cellOffset = first;
50878  pPage->aDataEnd = &data[pBt->usableSize];
50879  pPage->aCellIdx = &data[first];
50880  pPage->nOverflow = 0;
50881  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
50882  pPage->maskPage = (u16)(pBt->pageSize - 1);
50883  pPage->nCell = 0;
50884  pPage->isInit = 1;
50885}
50886
50887
50888/*
50889** Convert a DbPage obtained from the pager into a MemPage used by
50890** the btree layer.
50891*/
50892static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
50893  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
50894  pPage->aData = sqlite3PagerGetData(pDbPage);
50895  pPage->pDbPage = pDbPage;
50896  pPage->pBt = pBt;
50897  pPage->pgno = pgno;
50898  pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
50899  return pPage;
50900}
50901
50902/*
50903** Get a page from the pager.  Initialize the MemPage.pBt and
50904** MemPage.aData elements if needed.
50905**
50906** If the noContent flag is set, it means that we do not care about
50907** the content of the page at this time.  So do not go to the disk
50908** to fetch the content.  Just fill in the content with zeros for now.
50909** If in the future we call sqlite3PagerWrite() on this page, that
50910** means we have started to be concerned about content and the disk
50911** read should occur at that point.
50912*/
50913static int btreeGetPage(
50914  BtShared *pBt,       /* The btree */
50915  Pgno pgno,           /* Number of the page to fetch */
50916  MemPage **ppPage,    /* Return the page in this parameter */
50917  int noContent        /* Do not load page content if true */
50918){
50919  int rc;
50920  DbPage *pDbPage;
50921
50922  assert( sqlite3_mutex_held(pBt->mutex) );
50923  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
50924  if( rc ) return rc;
50925  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
50926  return SQLITE_OK;
50927}
50928
50929/*
50930** Retrieve a page from the pager cache. If the requested page is not
50931** already in the pager cache return NULL. Initialize the MemPage.pBt and
50932** MemPage.aData elements if needed.
50933*/
50934static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
50935  DbPage *pDbPage;
50936  assert( sqlite3_mutex_held(pBt->mutex) );
50937  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
50938  if( pDbPage ){
50939    return btreePageFromDbPage(pDbPage, pgno, pBt);
50940  }
50941  return 0;
50942}
50943
50944/*
50945** Return the size of the database file in pages. If there is any kind of
50946** error, return ((unsigned int)-1).
50947*/
50948static Pgno btreePagecount(BtShared *pBt){
50949  return pBt->nPage;
50950}
50951SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
50952  assert( sqlite3BtreeHoldsMutex(p) );
50953  assert( ((p->pBt->nPage)&0x8000000)==0 );
50954  return (int)btreePagecount(p->pBt);
50955}
50956
50957/*
50958** Get a page from the pager and initialize it.  This routine is just a
50959** convenience wrapper around separate calls to btreeGetPage() and
50960** btreeInitPage().
50961**
50962** If an error occurs, then the value *ppPage is set to is undefined. It
50963** may remain unchanged, or it may be set to an invalid value.
50964*/
50965static int getAndInitPage(
50966  BtShared *pBt,          /* The database file */
50967  Pgno pgno,           /* Number of the page to get */
50968  MemPage **ppPage     /* Write the page pointer here */
50969){
50970  int rc;
50971  assert( sqlite3_mutex_held(pBt->mutex) );
50972
50973  if( pgno>btreePagecount(pBt) ){
50974    rc = SQLITE_CORRUPT_BKPT;
50975  }else{
50976    rc = btreeGetPage(pBt, pgno, ppPage, 0);
50977    if( rc==SQLITE_OK ){
50978      rc = btreeInitPage(*ppPage);
50979      if( rc!=SQLITE_OK ){
50980        releasePage(*ppPage);
50981      }
50982    }
50983  }
50984
50985  testcase( pgno==0 );
50986  assert( pgno!=0 || rc==SQLITE_CORRUPT );
50987  return rc;
50988}
50989
50990/*
50991** Release a MemPage.  This should be called once for each prior
50992** call to btreeGetPage.
50993*/
50994static void releasePage(MemPage *pPage){
50995  if( pPage ){
50996    assert( pPage->aData );
50997    assert( pPage->pBt );
50998    assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
50999    assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
51000    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51001    sqlite3PagerUnref(pPage->pDbPage);
51002  }
51003}
51004
51005/*
51006** During a rollback, when the pager reloads information into the cache
51007** so that the cache is restored to its original state at the start of
51008** the transaction, for each page restored this routine is called.
51009**
51010** This routine needs to reset the extra data section at the end of the
51011** page to agree with the restored data.
51012*/
51013static void pageReinit(DbPage *pData){
51014  MemPage *pPage;
51015  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
51016  assert( sqlite3PagerPageRefcount(pData)>0 );
51017  if( pPage->isInit ){
51018    assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51019    pPage->isInit = 0;
51020    if( sqlite3PagerPageRefcount(pData)>1 ){
51021      /* pPage might not be a btree page;  it might be an overflow page
51022      ** or ptrmap page or a free page.  In those cases, the following
51023      ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
51024      ** But no harm is done by this.  And it is very important that
51025      ** btreeInitPage() be called on every btree page so we make
51026      ** the call for every page that comes in for re-initing. */
51027      btreeInitPage(pPage);
51028    }
51029  }
51030}
51031
51032/*
51033** Invoke the busy handler for a btree.
51034*/
51035static int btreeInvokeBusyHandler(void *pArg){
51036  BtShared *pBt = (BtShared*)pArg;
51037  assert( pBt->db );
51038  assert( sqlite3_mutex_held(pBt->db->mutex) );
51039  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
51040}
51041
51042/*
51043** Open a database file.
51044**
51045** zFilename is the name of the database file.  If zFilename is NULL
51046** then an ephemeral database is created.  The ephemeral database might
51047** be exclusively in memory, or it might use a disk-based memory cache.
51048** Either way, the ephemeral database will be automatically deleted
51049** when sqlite3BtreeClose() is called.
51050**
51051** If zFilename is ":memory:" then an in-memory database is created
51052** that is automatically destroyed when it is closed.
51053**
51054** The "flags" parameter is a bitmask that might contain bits like
51055** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
51056**
51057** If the database is already opened in the same database connection
51058** and we are in shared cache mode, then the open will fail with an
51059** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
51060** objects in the same database connection since doing so will lead
51061** to problems with locking.
51062*/
51063SQLITE_PRIVATE int sqlite3BtreeOpen(
51064  sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
51065  const char *zFilename,  /* Name of the file containing the BTree database */
51066  sqlite3 *db,            /* Associated database handle */
51067  Btree **ppBtree,        /* Pointer to new Btree object written here */
51068  int flags,              /* Options */
51069  int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
51070){
51071  BtShared *pBt = 0;             /* Shared part of btree structure */
51072  Btree *p;                      /* Handle to return */
51073  sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
51074  int rc = SQLITE_OK;            /* Result code from this function */
51075  u8 nReserve;                   /* Byte of unused space on each page */
51076  unsigned char zDbHeader[100];  /* Database header content */
51077
51078  /* True if opening an ephemeral, temporary database */
51079  const int isTempDb = zFilename==0 || zFilename[0]==0;
51080
51081  /* Set the variable isMemdb to true for an in-memory database, or
51082  ** false for a file-based database.
51083  */
51084#ifdef SQLITE_OMIT_MEMORYDB
51085  const int isMemdb = 0;
51086#else
51087  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
51088                       || (isTempDb && sqlite3TempInMemory(db));
51089#endif
51090
51091  assert( db!=0 );
51092  assert( pVfs!=0 );
51093  assert( sqlite3_mutex_held(db->mutex) );
51094  assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
51095
51096  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
51097  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
51098
51099  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
51100  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
51101
51102  if( isMemdb ){
51103    flags |= BTREE_MEMORY;
51104  }
51105  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
51106    vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
51107  }
51108  p = sqlite3MallocZero(sizeof(Btree));
51109  if( !p ){
51110    return SQLITE_NOMEM;
51111  }
51112  p->inTrans = TRANS_NONE;
51113  p->db = db;
51114#ifndef SQLITE_OMIT_SHARED_CACHE
51115  p->lock.pBtree = p;
51116  p->lock.iTable = 1;
51117#endif
51118
51119#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51120  /*
51121  ** If this Btree is a candidate for shared cache, try to find an
51122  ** existing BtShared object that we can share with
51123  */
51124  if( isMemdb==0 && isTempDb==0 ){
51125    if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
51126      int nFullPathname = pVfs->mxPathname+1;
51127      char *zFullPathname = sqlite3Malloc(nFullPathname);
51128      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51129      p->sharable = 1;
51130      if( !zFullPathname ){
51131        sqlite3_free(p);
51132        return SQLITE_NOMEM;
51133      }
51134      rc = sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
51135      if( rc ){
51136        sqlite3_free(zFullPathname);
51137        sqlite3_free(p);
51138        return rc;
51139      }
51140#if SQLITE_THREADSAFE
51141      mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
51142      sqlite3_mutex_enter(mutexOpen);
51143      mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
51144      sqlite3_mutex_enter(mutexShared);
51145#endif
51146      for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
51147        assert( pBt->nRef>0 );
51148        if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
51149                 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
51150          int iDb;
51151          for(iDb=db->nDb-1; iDb>=0; iDb--){
51152            Btree *pExisting = db->aDb[iDb].pBt;
51153            if( pExisting && pExisting->pBt==pBt ){
51154              sqlite3_mutex_leave(mutexShared);
51155              sqlite3_mutex_leave(mutexOpen);
51156              sqlite3_free(zFullPathname);
51157              sqlite3_free(p);
51158              return SQLITE_CONSTRAINT;
51159            }
51160          }
51161          p->pBt = pBt;
51162          pBt->nRef++;
51163          break;
51164        }
51165      }
51166      sqlite3_mutex_leave(mutexShared);
51167      sqlite3_free(zFullPathname);
51168    }
51169#ifdef SQLITE_DEBUG
51170    else{
51171      /* In debug mode, we mark all persistent databases as sharable
51172      ** even when they are not.  This exercises the locking code and
51173      ** gives more opportunity for asserts(sqlite3_mutex_held())
51174      ** statements to find locking problems.
51175      */
51176      p->sharable = 1;
51177    }
51178#endif
51179  }
51180#endif
51181  if( pBt==0 ){
51182    /*
51183    ** The following asserts make sure that structures used by the btree are
51184    ** the right size.  This is to guard against size changes that result
51185    ** when compiling on a different architecture.
51186    */
51187    assert( sizeof(i64)==8 || sizeof(i64)==4 );
51188    assert( sizeof(u64)==8 || sizeof(u64)==4 );
51189    assert( sizeof(u32)==4 );
51190    assert( sizeof(u16)==2 );
51191    assert( sizeof(Pgno)==4 );
51192
51193    pBt = sqlite3MallocZero( sizeof(*pBt) );
51194    if( pBt==0 ){
51195      rc = SQLITE_NOMEM;
51196      goto btree_open_out;
51197    }
51198    rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
51199                          EXTRA_SIZE, flags, vfsFlags, pageReinit);
51200    if( rc==SQLITE_OK ){
51201      rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
51202    }
51203    if( rc!=SQLITE_OK ){
51204      goto btree_open_out;
51205    }
51206    pBt->openFlags = (u8)flags;
51207    pBt->db = db;
51208    sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
51209    p->pBt = pBt;
51210
51211    pBt->pCursor = 0;
51212    pBt->pPage1 = 0;
51213    if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
51214#ifdef SQLITE_SECURE_DELETE
51215    pBt->btsFlags |= BTS_SECURE_DELETE;
51216#endif
51217    pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
51218    if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
51219         || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
51220      pBt->pageSize = 0;
51221#ifndef SQLITE_OMIT_AUTOVACUUM
51222      /* If the magic name ":memory:" will create an in-memory database, then
51223      ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
51224      ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
51225      ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
51226      ** regular file-name. In this case the auto-vacuum applies as per normal.
51227      */
51228      if( zFilename && !isMemdb ){
51229        pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
51230        pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
51231      }
51232#endif
51233      nReserve = 0;
51234    }else{
51235      nReserve = zDbHeader[20];
51236      pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51237#ifndef SQLITE_OMIT_AUTOVACUUM
51238      pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
51239      pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
51240#endif
51241    }
51242    rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51243    if( rc ) goto btree_open_out;
51244    pBt->usableSize = pBt->pageSize - nReserve;
51245    assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
51246
51247#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51248    /* Add the new BtShared object to the linked list sharable BtShareds.
51249    */
51250    if( p->sharable ){
51251      MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51252      pBt->nRef = 1;
51253      MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
51254      if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
51255        pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
51256        if( pBt->mutex==0 ){
51257          rc = SQLITE_NOMEM;
51258          db->mallocFailed = 0;
51259          goto btree_open_out;
51260        }
51261      }
51262      sqlite3_mutex_enter(mutexShared);
51263      pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
51264      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
51265      sqlite3_mutex_leave(mutexShared);
51266    }
51267#endif
51268  }
51269
51270#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51271  /* If the new Btree uses a sharable pBtShared, then link the new
51272  ** Btree into the list of all sharable Btrees for the same connection.
51273  ** The list is kept in ascending order by pBt address.
51274  */
51275  if( p->sharable ){
51276    int i;
51277    Btree *pSib;
51278    for(i=0; i<db->nDb; i++){
51279      if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
51280        while( pSib->pPrev ){ pSib = pSib->pPrev; }
51281        if( p->pBt<pSib->pBt ){
51282          p->pNext = pSib;
51283          p->pPrev = 0;
51284          pSib->pPrev = p;
51285        }else{
51286          while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
51287            pSib = pSib->pNext;
51288          }
51289          p->pNext = pSib->pNext;
51290          p->pPrev = pSib;
51291          if( p->pNext ){
51292            p->pNext->pPrev = p;
51293          }
51294          pSib->pNext = p;
51295        }
51296        break;
51297      }
51298    }
51299  }
51300#endif
51301  *ppBtree = p;
51302
51303btree_open_out:
51304  if( rc!=SQLITE_OK ){
51305    if( pBt && pBt->pPager ){
51306      sqlite3PagerClose(pBt->pPager);
51307    }
51308    sqlite3_free(pBt);
51309    sqlite3_free(p);
51310    *ppBtree = 0;
51311  }else{
51312    /* If the B-Tree was successfully opened, set the pager-cache size to the
51313    ** default value. Except, when opening on an existing shared pager-cache,
51314    ** do not change the pager-cache size.
51315    */
51316    if( sqlite3BtreeSchema(p, 0, 0)==0 ){
51317      sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
51318    }
51319  }
51320  if( mutexOpen ){
51321    assert( sqlite3_mutex_held(mutexOpen) );
51322    sqlite3_mutex_leave(mutexOpen);
51323  }
51324  return rc;
51325}
51326
51327/*
51328** Decrement the BtShared.nRef counter.  When it reaches zero,
51329** remove the BtShared structure from the sharing list.  Return
51330** true if the BtShared.nRef counter reaches zero and return
51331** false if it is still positive.
51332*/
51333static int removeFromSharingList(BtShared *pBt){
51334#ifndef SQLITE_OMIT_SHARED_CACHE
51335  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
51336  BtShared *pList;
51337  int removed = 0;
51338
51339  assert( sqlite3_mutex_notheld(pBt->mutex) );
51340  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
51341  sqlite3_mutex_enter(pMaster);
51342  pBt->nRef--;
51343  if( pBt->nRef<=0 ){
51344    if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
51345      GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
51346    }else{
51347      pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
51348      while( ALWAYS(pList) && pList->pNext!=pBt ){
51349        pList=pList->pNext;
51350      }
51351      if( ALWAYS(pList) ){
51352        pList->pNext = pBt->pNext;
51353      }
51354    }
51355    if( SQLITE_THREADSAFE ){
51356      sqlite3_mutex_free(pBt->mutex);
51357    }
51358    removed = 1;
51359  }
51360  sqlite3_mutex_leave(pMaster);
51361  return removed;
51362#else
51363  return 1;
51364#endif
51365}
51366
51367/*
51368** Make sure pBt->pTmpSpace points to an allocation of
51369** MX_CELL_SIZE(pBt) bytes.
51370*/
51371static void allocateTempSpace(BtShared *pBt){
51372  if( !pBt->pTmpSpace ){
51373    pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
51374  }
51375}
51376
51377/*
51378** Free the pBt->pTmpSpace allocation
51379*/
51380static void freeTempSpace(BtShared *pBt){
51381  sqlite3PageFree( pBt->pTmpSpace);
51382  pBt->pTmpSpace = 0;
51383}
51384
51385/*
51386** Close an open database and invalidate all cursors.
51387*/
51388SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
51389  BtShared *pBt = p->pBt;
51390  BtCursor *pCur;
51391
51392  /* Close all cursors opened via this handle.  */
51393  assert( sqlite3_mutex_held(p->db->mutex) );
51394  sqlite3BtreeEnter(p);
51395  pCur = pBt->pCursor;
51396  while( pCur ){
51397    BtCursor *pTmp = pCur;
51398    pCur = pCur->pNext;
51399    if( pTmp->pBtree==p ){
51400      sqlite3BtreeCloseCursor(pTmp);
51401    }
51402  }
51403
51404  /* Rollback any active transaction and free the handle structure.
51405  ** The call to sqlite3BtreeRollback() drops any table-locks held by
51406  ** this handle.
51407  */
51408  sqlite3BtreeRollback(p, SQLITE_OK);
51409  sqlite3BtreeLeave(p);
51410
51411  /* If there are still other outstanding references to the shared-btree
51412  ** structure, return now. The remainder of this procedure cleans
51413  ** up the shared-btree.
51414  */
51415  assert( p->wantToLock==0 && p->locked==0 );
51416  if( !p->sharable || removeFromSharingList(pBt) ){
51417    /* The pBt is no longer on the sharing list, so we can access
51418    ** it without having to hold the mutex.
51419    **
51420    ** Clean out and delete the BtShared object.
51421    */
51422    assert( !pBt->pCursor );
51423    sqlite3PagerClose(pBt->pPager);
51424    if( pBt->xFreeSchema && pBt->pSchema ){
51425      pBt->xFreeSchema(pBt->pSchema);
51426    }
51427    sqlite3DbFree(0, pBt->pSchema);
51428    freeTempSpace(pBt);
51429    sqlite3_free(pBt);
51430  }
51431
51432#ifndef SQLITE_OMIT_SHARED_CACHE
51433  assert( p->wantToLock==0 );
51434  assert( p->locked==0 );
51435  if( p->pPrev ) p->pPrev->pNext = p->pNext;
51436  if( p->pNext ) p->pNext->pPrev = p->pPrev;
51437#endif
51438
51439  sqlite3_free(p);
51440  return SQLITE_OK;
51441}
51442
51443/*
51444** Change the limit on the number of pages allowed in the cache.
51445**
51446** The maximum number of cache pages is set to the absolute
51447** value of mxPage.  If mxPage is negative, the pager will
51448** operate asynchronously - it will not stop to do fsync()s
51449** to insure data is written to the disk surface before
51450** continuing.  Transactions still work if synchronous is off,
51451** and the database cannot be corrupted if this program
51452** crashes.  But if the operating system crashes or there is
51453** an abrupt power failure when synchronous is off, the database
51454** could be left in an inconsistent and unrecoverable state.
51455** Synchronous is on by default so database corruption is not
51456** normally a worry.
51457*/
51458SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
51459  BtShared *pBt = p->pBt;
51460  assert( sqlite3_mutex_held(p->db->mutex) );
51461  sqlite3BtreeEnter(p);
51462  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
51463  sqlite3BtreeLeave(p);
51464  return SQLITE_OK;
51465}
51466
51467/*
51468** Change the way data is synced to disk in order to increase or decrease
51469** how well the database resists damage due to OS crashes and power
51470** failures.  Level 1 is the same as asynchronous (no syncs() occur and
51471** there is a high probability of damage)  Level 2 is the default.  There
51472** is a very low but non-zero probability of damage.  Level 3 reduces the
51473** probability of damage to near zero but with a write performance reduction.
51474*/
51475#ifndef SQLITE_OMIT_PAGER_PRAGMAS
51476SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
51477  Btree *p,              /* The btree to set the safety level on */
51478  int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
51479  int fullSync,          /* PRAGMA fullfsync. */
51480  int ckptFullSync       /* PRAGMA checkpoint_fullfync */
51481){
51482  BtShared *pBt = p->pBt;
51483  assert( sqlite3_mutex_held(p->db->mutex) );
51484  assert( level>=1 && level<=3 );
51485  sqlite3BtreeEnter(p);
51486  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
51487  sqlite3BtreeLeave(p);
51488  return SQLITE_OK;
51489}
51490#endif
51491
51492/*
51493** Return TRUE if the given btree is set to safety level 1.  In other
51494** words, return TRUE if no sync() occurs on the disk files.
51495*/
51496SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
51497  BtShared *pBt = p->pBt;
51498  int rc;
51499  assert( sqlite3_mutex_held(p->db->mutex) );
51500  sqlite3BtreeEnter(p);
51501  assert( pBt && pBt->pPager );
51502  rc = sqlite3PagerNosync(pBt->pPager);
51503  sqlite3BtreeLeave(p);
51504  return rc;
51505}
51506
51507/*
51508** Change the default pages size and the number of reserved bytes per page.
51509** Or, if the page size has already been fixed, return SQLITE_READONLY
51510** without changing anything.
51511**
51512** The page size must be a power of 2 between 512 and 65536.  If the page
51513** size supplied does not meet this constraint then the page size is not
51514** changed.
51515**
51516** Page sizes are constrained to be a power of two so that the region
51517** of the database file used for locking (beginning at PENDING_BYTE,
51518** the first byte past the 1GB boundary, 0x40000000) needs to occur
51519** at the beginning of a page.
51520**
51521** If parameter nReserve is less than zero, then the number of reserved
51522** bytes per page is left unchanged.
51523**
51524** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
51525** and autovacuum mode can no longer be changed.
51526*/
51527SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
51528  int rc = SQLITE_OK;
51529  BtShared *pBt = p->pBt;
51530  assert( nReserve>=-1 && nReserve<=255 );
51531  sqlite3BtreeEnter(p);
51532  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
51533    sqlite3BtreeLeave(p);
51534    return SQLITE_READONLY;
51535  }
51536  if( nReserve<0 ){
51537    nReserve = pBt->pageSize - pBt->usableSize;
51538  }
51539  assert( nReserve>=0 && nReserve<=255 );
51540  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
51541        ((pageSize-1)&pageSize)==0 ){
51542    assert( (pageSize & 7)==0 );
51543    assert( !pBt->pPage1 && !pBt->pCursor );
51544    pBt->pageSize = (u32)pageSize;
51545    freeTempSpace(pBt);
51546  }
51547  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51548  pBt->usableSize = pBt->pageSize - (u16)nReserve;
51549  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51550  sqlite3BtreeLeave(p);
51551  return rc;
51552}
51553
51554/*
51555** Return the currently defined page size
51556*/
51557SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
51558  return p->pBt->pageSize;
51559}
51560
51561#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
51562/*
51563** Return the number of bytes of space at the end of every page that
51564** are intentually left unused.  This is the "reserved" space that is
51565** sometimes used by extensions.
51566*/
51567SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
51568  int n;
51569  sqlite3BtreeEnter(p);
51570  n = p->pBt->pageSize - p->pBt->usableSize;
51571  sqlite3BtreeLeave(p);
51572  return n;
51573}
51574
51575/*
51576** Set the maximum page count for a database if mxPage is positive.
51577** No changes are made if mxPage is 0 or negative.
51578** Regardless of the value of mxPage, return the maximum page count.
51579*/
51580SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
51581  int n;
51582  sqlite3BtreeEnter(p);
51583  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
51584  sqlite3BtreeLeave(p);
51585  return n;
51586}
51587
51588/*
51589** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
51590** then make no changes.  Always return the value of the BTS_SECURE_DELETE
51591** setting after the change.
51592*/
51593SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
51594  int b;
51595  if( p==0 ) return 0;
51596  sqlite3BtreeEnter(p);
51597  if( newFlag>=0 ){
51598    p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
51599    if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
51600  }
51601  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
51602  sqlite3BtreeLeave(p);
51603  return b;
51604}
51605#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
51606
51607/*
51608** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
51609** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
51610** is disabled. The default value for the auto-vacuum property is
51611** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
51612*/
51613SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
51614#ifdef SQLITE_OMIT_AUTOVACUUM
51615  return SQLITE_READONLY;
51616#else
51617  BtShared *pBt = p->pBt;
51618  int rc = SQLITE_OK;
51619  u8 av = (u8)autoVacuum;
51620
51621  sqlite3BtreeEnter(p);
51622  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
51623    rc = SQLITE_READONLY;
51624  }else{
51625    pBt->autoVacuum = av ?1:0;
51626    pBt->incrVacuum = av==2 ?1:0;
51627  }
51628  sqlite3BtreeLeave(p);
51629  return rc;
51630#endif
51631}
51632
51633/*
51634** Return the value of the 'auto-vacuum' property. If auto-vacuum is
51635** enabled 1 is returned. Otherwise 0.
51636*/
51637SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
51638#ifdef SQLITE_OMIT_AUTOVACUUM
51639  return BTREE_AUTOVACUUM_NONE;
51640#else
51641  int rc;
51642  sqlite3BtreeEnter(p);
51643  rc = (
51644    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
51645    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
51646    BTREE_AUTOVACUUM_INCR
51647  );
51648  sqlite3BtreeLeave(p);
51649  return rc;
51650#endif
51651}
51652
51653
51654/*
51655** Get a reference to pPage1 of the database file.  This will
51656** also acquire a readlock on that file.
51657**
51658** SQLITE_OK is returned on success.  If the file is not a
51659** well-formed database file, then SQLITE_CORRUPT is returned.
51660** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
51661** is returned if we run out of memory.
51662*/
51663static int lockBtree(BtShared *pBt){
51664  int rc;              /* Result code from subfunctions */
51665  MemPage *pPage1;     /* Page 1 of the database file */
51666  int nPage;           /* Number of pages in the database */
51667  int nPageFile = 0;   /* Number of pages in the database file */
51668  int nPageHeader;     /* Number of pages in the database according to hdr */
51669
51670  assert( sqlite3_mutex_held(pBt->mutex) );
51671  assert( pBt->pPage1==0 );
51672  rc = sqlite3PagerSharedLock(pBt->pPager);
51673  if( rc!=SQLITE_OK ) return rc;
51674  rc = btreeGetPage(pBt, 1, &pPage1, 0);
51675  if( rc!=SQLITE_OK ) return rc;
51676
51677  /* Do some checking to help insure the file we opened really is
51678  ** a valid database file.
51679  */
51680  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
51681  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
51682  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
51683    nPage = nPageFile;
51684  }
51685  if( nPage>0 ){
51686    u32 pageSize;
51687    u32 usableSize;
51688    u8 *page1 = pPage1->aData;
51689    rc = SQLITE_NOTADB;
51690    if( memcmp(page1, zMagicHeader, 16)!=0 ){
51691      goto page1_init_failed;
51692    }
51693
51694#ifdef SQLITE_OMIT_WAL
51695    if( page1[18]>1 ){
51696      pBt->btsFlags |= BTS_READ_ONLY;
51697    }
51698    if( page1[19]>1 ){
51699      goto page1_init_failed;
51700    }
51701#else
51702    if( page1[18]>2 ){
51703      pBt->btsFlags |= BTS_READ_ONLY;
51704    }
51705    if( page1[19]>2 ){
51706      goto page1_init_failed;
51707    }
51708
51709    /* If the write version is set to 2, this database should be accessed
51710    ** in WAL mode. If the log is not already open, open it now. Then
51711    ** return SQLITE_OK and return without populating BtShared.pPage1.
51712    ** The caller detects this and calls this function again. This is
51713    ** required as the version of page 1 currently in the page1 buffer
51714    ** may not be the latest version - there may be a newer one in the log
51715    ** file.
51716    */
51717    if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
51718      int isOpen = 0;
51719      rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
51720      if( rc!=SQLITE_OK ){
51721        goto page1_init_failed;
51722      }else if( isOpen==0 ){
51723        releasePage(pPage1);
51724        return SQLITE_OK;
51725      }
51726      rc = SQLITE_NOTADB;
51727    }
51728#endif
51729
51730    /* The maximum embedded fraction must be exactly 25%.  And the minimum
51731    ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
51732    ** The original design allowed these amounts to vary, but as of
51733    ** version 3.6.0, we require them to be fixed.
51734    */
51735    if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
51736      goto page1_init_failed;
51737    }
51738    pageSize = (page1[16]<<8) | (page1[17]<<16);
51739    if( ((pageSize-1)&pageSize)!=0
51740     || pageSize>SQLITE_MAX_PAGE_SIZE
51741     || pageSize<=256
51742    ){
51743      goto page1_init_failed;
51744    }
51745    assert( (pageSize & 7)==0 );
51746    usableSize = pageSize - page1[20];
51747    if( (u32)pageSize!=pBt->pageSize ){
51748      /* After reading the first page of the database assuming a page size
51749      ** of BtShared.pageSize, we have discovered that the page-size is
51750      ** actually pageSize. Unlock the database, leave pBt->pPage1 at
51751      ** zero and return SQLITE_OK. The caller will call this function
51752      ** again with the correct page-size.
51753      */
51754      releasePage(pPage1);
51755      pBt->usableSize = usableSize;
51756      pBt->pageSize = pageSize;
51757      freeTempSpace(pBt);
51758      rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
51759                                   pageSize-usableSize);
51760      return rc;
51761    }
51762    if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
51763      rc = SQLITE_CORRUPT_BKPT;
51764      goto page1_init_failed;
51765    }
51766    if( usableSize<480 ){
51767      goto page1_init_failed;
51768    }
51769    pBt->pageSize = pageSize;
51770    pBt->usableSize = usableSize;
51771#ifndef SQLITE_OMIT_AUTOVACUUM
51772    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
51773    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
51774#endif
51775  }
51776
51777  /* maxLocal is the maximum amount of payload to store locally for
51778  ** a cell.  Make sure it is small enough so that at least minFanout
51779  ** cells can will fit on one page.  We assume a 10-byte page header.
51780  ** Besides the payload, the cell must store:
51781  **     2-byte pointer to the cell
51782  **     4-byte child pointer
51783  **     9-byte nKey value
51784  **     4-byte nData value
51785  **     4-byte overflow page pointer
51786  ** So a cell consists of a 2-byte pointer, a header which is as much as
51787  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
51788  ** page pointer.
51789  */
51790  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
51791  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
51792  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
51793  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
51794  if( pBt->maxLocal>127 ){
51795    pBt->max1bytePayload = 127;
51796  }else{
51797    pBt->max1bytePayload = (u8)pBt->maxLocal;
51798  }
51799  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
51800  pBt->pPage1 = pPage1;
51801  pBt->nPage = nPage;
51802  return SQLITE_OK;
51803
51804page1_init_failed:
51805  releasePage(pPage1);
51806  pBt->pPage1 = 0;
51807  return rc;
51808}
51809
51810/*
51811** If there are no outstanding cursors and we are not in the middle
51812** of a transaction but there is a read lock on the database, then
51813** this routine unrefs the first page of the database file which
51814** has the effect of releasing the read lock.
51815**
51816** If there is a transaction in progress, this routine is a no-op.
51817*/
51818static void unlockBtreeIfUnused(BtShared *pBt){
51819  assert( sqlite3_mutex_held(pBt->mutex) );
51820  assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
51821  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
51822    assert( pBt->pPage1->aData );
51823    assert( sqlite3PagerRefcount(pBt->pPager)==1 );
51824    assert( pBt->pPage1->aData );
51825    releasePage(pBt->pPage1);
51826    pBt->pPage1 = 0;
51827  }
51828}
51829
51830/*
51831** If pBt points to an empty file then convert that empty file
51832** into a new empty database by initializing the first page of
51833** the database.
51834*/
51835static int newDatabase(BtShared *pBt){
51836  MemPage *pP1;
51837  unsigned char *data;
51838  int rc;
51839
51840  assert( sqlite3_mutex_held(pBt->mutex) );
51841  if( pBt->nPage>0 ){
51842    return SQLITE_OK;
51843  }
51844  pP1 = pBt->pPage1;
51845  assert( pP1!=0 );
51846  data = pP1->aData;
51847  rc = sqlite3PagerWrite(pP1->pDbPage);
51848  if( rc ) return rc;
51849  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
51850  assert( sizeof(zMagicHeader)==16 );
51851  data[16] = (u8)((pBt->pageSize>>8)&0xff);
51852  data[17] = (u8)((pBt->pageSize>>16)&0xff);
51853  data[18] = 1;
51854  data[19] = 1;
51855  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
51856  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
51857  data[21] = 64;
51858  data[22] = 32;
51859  data[23] = 32;
51860  memset(&data[24], 0, 100-24);
51861  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
51862  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51863#ifndef SQLITE_OMIT_AUTOVACUUM
51864  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
51865  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
51866  put4byte(&data[36 + 4*4], pBt->autoVacuum);
51867  put4byte(&data[36 + 7*4], pBt->incrVacuum);
51868#endif
51869  pBt->nPage = 1;
51870  data[31] = 1;
51871  return SQLITE_OK;
51872}
51873
51874/*
51875** Attempt to start a new transaction. A write-transaction
51876** is started if the second argument is nonzero, otherwise a read-
51877** transaction.  If the second argument is 2 or more and exclusive
51878** transaction is started, meaning that no other process is allowed
51879** to access the database.  A preexisting transaction may not be
51880** upgraded to exclusive by calling this routine a second time - the
51881** exclusivity flag only works for a new transaction.
51882**
51883** A write-transaction must be started before attempting any
51884** changes to the database.  None of the following routines
51885** will work unless a transaction is started first:
51886**
51887**      sqlite3BtreeCreateTable()
51888**      sqlite3BtreeCreateIndex()
51889**      sqlite3BtreeClearTable()
51890**      sqlite3BtreeDropTable()
51891**      sqlite3BtreeInsert()
51892**      sqlite3BtreeDelete()
51893**      sqlite3BtreeUpdateMeta()
51894**
51895** If an initial attempt to acquire the lock fails because of lock contention
51896** and the database was previously unlocked, then invoke the busy handler
51897** if there is one.  But if there was previously a read-lock, do not
51898** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is
51899** returned when there is already a read-lock in order to avoid a deadlock.
51900**
51901** Suppose there are two processes A and B.  A has a read lock and B has
51902** a reserved lock.  B tries to promote to exclusive but is blocked because
51903** of A's read lock.  A tries to promote to reserved but is blocked by B.
51904** One or the other of the two processes must give way or there can be
51905** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
51906** when A already has a read lock, we encourage A to give up and let B
51907** proceed.
51908*/
51909SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
51910  sqlite3 *pBlock = 0;
51911  BtShared *pBt = p->pBt;
51912  int rc = SQLITE_OK;
51913
51914  sqlite3BtreeEnter(p);
51915  btreeIntegrity(p);
51916
51917  /* If the btree is already in a write-transaction, or it
51918  ** is already in a read-transaction and a read-transaction
51919  ** is requested, this is a no-op.
51920  */
51921  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
51922    goto trans_begun;
51923  }
51924
51925  /* Write transactions are not possible on a read-only database */
51926  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
51927    rc = SQLITE_READONLY;
51928    goto trans_begun;
51929  }
51930
51931#ifndef SQLITE_OMIT_SHARED_CACHE
51932  /* If another database handle has already opened a write transaction
51933  ** on this shared-btree structure and a second write transaction is
51934  ** requested, return SQLITE_LOCKED.
51935  */
51936  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
51937   || (pBt->btsFlags & BTS_PENDING)!=0
51938  ){
51939    pBlock = pBt->pWriter->db;
51940  }else if( wrflag>1 ){
51941    BtLock *pIter;
51942    for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
51943      if( pIter->pBtree!=p ){
51944        pBlock = pIter->pBtree->db;
51945        break;
51946      }
51947    }
51948  }
51949  if( pBlock ){
51950    sqlite3ConnectionBlocked(p->db, pBlock);
51951    rc = SQLITE_LOCKED_SHAREDCACHE;
51952    goto trans_begun;
51953  }
51954#endif
51955
51956  /* Any read-only or read-write transaction implies a read-lock on
51957  ** page 1. So if some other shared-cache client already has a write-lock
51958  ** on page 1, the transaction cannot be opened. */
51959  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
51960  if( SQLITE_OK!=rc ) goto trans_begun;
51961
51962  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
51963  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
51964  do {
51965    /* Call lockBtree() until either pBt->pPage1 is populated or
51966    ** lockBtree() returns something other than SQLITE_OK. lockBtree()
51967    ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
51968    ** reading page 1 it discovers that the page-size of the database
51969    ** file is not pBt->pageSize. In this case lockBtree() will update
51970    ** pBt->pageSize to the page-size of the file on disk.
51971    */
51972    while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
51973
51974    if( rc==SQLITE_OK && wrflag ){
51975      if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
51976        rc = SQLITE_READONLY;
51977      }else{
51978        rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
51979        if( rc==SQLITE_OK ){
51980          rc = newDatabase(pBt);
51981        }
51982      }
51983    }
51984
51985    if( rc!=SQLITE_OK ){
51986      unlockBtreeIfUnused(pBt);
51987    }
51988  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
51989          btreeInvokeBusyHandler(pBt) );
51990
51991  if( rc==SQLITE_OK ){
51992    if( p->inTrans==TRANS_NONE ){
51993      pBt->nTransaction++;
51994#ifndef SQLITE_OMIT_SHARED_CACHE
51995      if( p->sharable ){
51996	assert( p->lock.pBtree==p && p->lock.iTable==1 );
51997        p->lock.eLock = READ_LOCK;
51998        p->lock.pNext = pBt->pLock;
51999        pBt->pLock = &p->lock;
52000      }
52001#endif
52002    }
52003    p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
52004    if( p->inTrans>pBt->inTransaction ){
52005      pBt->inTransaction = p->inTrans;
52006    }
52007    if( wrflag ){
52008      MemPage *pPage1 = pBt->pPage1;
52009#ifndef SQLITE_OMIT_SHARED_CACHE
52010      assert( !pBt->pWriter );
52011      pBt->pWriter = p;
52012      pBt->btsFlags &= ~BTS_EXCLUSIVE;
52013      if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
52014#endif
52015
52016      /* If the db-size header field is incorrect (as it may be if an old
52017      ** client has been writing the database file), update it now. Doing
52018      ** this sooner rather than later means the database size can safely
52019      ** re-read the database size from page 1 if a savepoint or transaction
52020      ** rollback occurs within the transaction.
52021      */
52022      if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
52023        rc = sqlite3PagerWrite(pPage1->pDbPage);
52024        if( rc==SQLITE_OK ){
52025          put4byte(&pPage1->aData[28], pBt->nPage);
52026        }
52027      }
52028    }
52029  }
52030
52031
52032trans_begun:
52033  if( rc==SQLITE_OK && wrflag ){
52034    /* This call makes sure that the pager has the correct number of
52035    ** open savepoints. If the second parameter is greater than 0 and
52036    ** the sub-journal is not already open, then it will be opened here.
52037    */
52038    rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
52039  }
52040
52041  btreeIntegrity(p);
52042  sqlite3BtreeLeave(p);
52043  return rc;
52044}
52045
52046#ifndef SQLITE_OMIT_AUTOVACUUM
52047
52048/*
52049** Set the pointer-map entries for all children of page pPage. Also, if
52050** pPage contains cells that point to overflow pages, set the pointer
52051** map entries for the overflow pages as well.
52052*/
52053static int setChildPtrmaps(MemPage *pPage){
52054  int i;                             /* Counter variable */
52055  int nCell;                         /* Number of cells in page pPage */
52056  int rc;                            /* Return code */
52057  BtShared *pBt = pPage->pBt;
52058  u8 isInitOrig = pPage->isInit;
52059  Pgno pgno = pPage->pgno;
52060
52061  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52062  rc = btreeInitPage(pPage);
52063  if( rc!=SQLITE_OK ){
52064    goto set_child_ptrmaps_out;
52065  }
52066  nCell = pPage->nCell;
52067
52068  for(i=0; i<nCell; i++){
52069    u8 *pCell = findCell(pPage, i);
52070
52071    ptrmapPutOvflPtr(pPage, pCell, &rc);
52072
52073    if( !pPage->leaf ){
52074      Pgno childPgno = get4byte(pCell);
52075      ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52076    }
52077  }
52078
52079  if( !pPage->leaf ){
52080    Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52081    ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52082  }
52083
52084set_child_ptrmaps_out:
52085  pPage->isInit = isInitOrig;
52086  return rc;
52087}
52088
52089/*
52090** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
52091** that it points to iTo. Parameter eType describes the type of pointer to
52092** be modified, as  follows:
52093**
52094** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child
52095**                   page of pPage.
52096**
52097** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
52098**                   page pointed to by one of the cells on pPage.
52099**
52100** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
52101**                   overflow page in the list.
52102*/
52103static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
52104  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52105  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52106  if( eType==PTRMAP_OVERFLOW2 ){
52107    /* The pointer is always the first 4 bytes of the page in this case.  */
52108    if( get4byte(pPage->aData)!=iFrom ){
52109      return SQLITE_CORRUPT_BKPT;
52110    }
52111    put4byte(pPage->aData, iTo);
52112  }else{
52113    u8 isInitOrig = pPage->isInit;
52114    int i;
52115    int nCell;
52116
52117    btreeInitPage(pPage);
52118    nCell = pPage->nCell;
52119
52120    for(i=0; i<nCell; i++){
52121      u8 *pCell = findCell(pPage, i);
52122      if( eType==PTRMAP_OVERFLOW1 ){
52123        CellInfo info;
52124        btreeParseCellPtr(pPage, pCell, &info);
52125        if( info.iOverflow
52126         && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
52127         && iFrom==get4byte(&pCell[info.iOverflow])
52128        ){
52129          put4byte(&pCell[info.iOverflow], iTo);
52130          break;
52131        }
52132      }else{
52133        if( get4byte(pCell)==iFrom ){
52134          put4byte(pCell, iTo);
52135          break;
52136        }
52137      }
52138    }
52139
52140    if( i==nCell ){
52141      if( eType!=PTRMAP_BTREE ||
52142          get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
52143        return SQLITE_CORRUPT_BKPT;
52144      }
52145      put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
52146    }
52147
52148    pPage->isInit = isInitOrig;
52149  }
52150  return SQLITE_OK;
52151}
52152
52153
52154/*
52155** Move the open database page pDbPage to location iFreePage in the
52156** database. The pDbPage reference remains valid.
52157**
52158** The isCommit flag indicates that there is no need to remember that
52159** the journal needs to be sync()ed before database page pDbPage->pgno
52160** can be written to. The caller has already promised not to write to that
52161** page.
52162*/
52163static int relocatePage(
52164  BtShared *pBt,           /* Btree */
52165  MemPage *pDbPage,        /* Open page to move */
52166  u8 eType,                /* Pointer map 'type' entry for pDbPage */
52167  Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
52168  Pgno iFreePage,          /* The location to move pDbPage to */
52169  int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
52170){
52171  MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
52172  Pgno iDbPage = pDbPage->pgno;
52173  Pager *pPager = pBt->pPager;
52174  int rc;
52175
52176  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
52177      eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
52178  assert( sqlite3_mutex_held(pBt->mutex) );
52179  assert( pDbPage->pBt==pBt );
52180
52181  /* Move page iDbPage from its current location to page number iFreePage */
52182  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
52183      iDbPage, iFreePage, iPtrPage, eType));
52184  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
52185  if( rc!=SQLITE_OK ){
52186    return rc;
52187  }
52188  pDbPage->pgno = iFreePage;
52189
52190  /* If pDbPage was a btree-page, then it may have child pages and/or cells
52191  ** that point to overflow pages. The pointer map entries for all these
52192  ** pages need to be changed.
52193  **
52194  ** If pDbPage is an overflow page, then the first 4 bytes may store a
52195  ** pointer to a subsequent overflow page. If this is the case, then
52196  ** the pointer map needs to be updated for the subsequent overflow page.
52197  */
52198  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
52199    rc = setChildPtrmaps(pDbPage);
52200    if( rc!=SQLITE_OK ){
52201      return rc;
52202    }
52203  }else{
52204    Pgno nextOvfl = get4byte(pDbPage->aData);
52205    if( nextOvfl!=0 ){
52206      ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
52207      if( rc!=SQLITE_OK ){
52208        return rc;
52209      }
52210    }
52211  }
52212
52213  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
52214  ** that it points at iFreePage. Also fix the pointer map entry for
52215  ** iPtrPage.
52216  */
52217  if( eType!=PTRMAP_ROOTPAGE ){
52218    rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
52219    if( rc!=SQLITE_OK ){
52220      return rc;
52221    }
52222    rc = sqlite3PagerWrite(pPtrPage->pDbPage);
52223    if( rc!=SQLITE_OK ){
52224      releasePage(pPtrPage);
52225      return rc;
52226    }
52227    rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
52228    releasePage(pPtrPage);
52229    if( rc==SQLITE_OK ){
52230      ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
52231    }
52232  }
52233  return rc;
52234}
52235
52236/* Forward declaration required by incrVacuumStep(). */
52237static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
52238
52239/*
52240** Perform a single step of an incremental-vacuum. If successful,
52241** return SQLITE_OK. If there is no work to do (and therefore no
52242** point in calling this function again), return SQLITE_DONE.
52243**
52244** More specificly, this function attempts to re-organize the
52245** database so that the last page of the file currently in use
52246** is no longer in use.
52247**
52248** If the nFin parameter is non-zero, this function assumes
52249** that the caller will keep calling incrVacuumStep() until
52250** it returns SQLITE_DONE or an error, and that nFin is the
52251** number of pages the database file will contain after this
52252** process is complete.  If nFin is zero, it is assumed that
52253** incrVacuumStep() will be called a finite amount of times
52254** which may or may not empty the freelist.  A full autovacuum
52255** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
52256*/
52257static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
52258  Pgno nFreeList;           /* Number of pages still on the free-list */
52259  int rc;
52260
52261  assert( sqlite3_mutex_held(pBt->mutex) );
52262  assert( iLastPg>nFin );
52263
52264  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
52265    u8 eType;
52266    Pgno iPtrPage;
52267
52268    nFreeList = get4byte(&pBt->pPage1->aData[36]);
52269    if( nFreeList==0 ){
52270      return SQLITE_DONE;
52271    }
52272
52273    rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
52274    if( rc!=SQLITE_OK ){
52275      return rc;
52276    }
52277    if( eType==PTRMAP_ROOTPAGE ){
52278      return SQLITE_CORRUPT_BKPT;
52279    }
52280
52281    if( eType==PTRMAP_FREEPAGE ){
52282      if( nFin==0 ){
52283        /* Remove the page from the files free-list. This is not required
52284        ** if nFin is non-zero. In that case, the free-list will be
52285        ** truncated to zero after this function returns, so it doesn't
52286        ** matter if it still contains some garbage entries.
52287        */
52288        Pgno iFreePg;
52289        MemPage *pFreePg;
52290        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
52291        if( rc!=SQLITE_OK ){
52292          return rc;
52293        }
52294        assert( iFreePg==iLastPg );
52295        releasePage(pFreePg);
52296      }
52297    } else {
52298      Pgno iFreePg;             /* Index of free page to move pLastPg to */
52299      MemPage *pLastPg;
52300
52301      rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
52302      if( rc!=SQLITE_OK ){
52303        return rc;
52304      }
52305
52306      /* If nFin is zero, this loop runs exactly once and page pLastPg
52307      ** is swapped with the first free page pulled off the free list.
52308      **
52309      ** On the other hand, if nFin is greater than zero, then keep
52310      ** looping until a free-page located within the first nFin pages
52311      ** of the file is found.
52312      */
52313      do {
52314        MemPage *pFreePg;
52315        rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
52316        if( rc!=SQLITE_OK ){
52317          releasePage(pLastPg);
52318          return rc;
52319        }
52320        releasePage(pFreePg);
52321      }while( nFin!=0 && iFreePg>nFin );
52322      assert( iFreePg<iLastPg );
52323
52324      rc = sqlite3PagerWrite(pLastPg->pDbPage);
52325      if( rc==SQLITE_OK ){
52326        rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
52327      }
52328      releasePage(pLastPg);
52329      if( rc!=SQLITE_OK ){
52330        return rc;
52331      }
52332    }
52333  }
52334
52335  if( nFin==0 ){
52336    iLastPg--;
52337    while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
52338      if( PTRMAP_ISPAGE(pBt, iLastPg) ){
52339        MemPage *pPg;
52340        rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
52341        if( rc!=SQLITE_OK ){
52342          return rc;
52343        }
52344        rc = sqlite3PagerWrite(pPg->pDbPage);
52345        releasePage(pPg);
52346        if( rc!=SQLITE_OK ){
52347          return rc;
52348        }
52349      }
52350      iLastPg--;
52351    }
52352    sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
52353    pBt->nPage = iLastPg;
52354  }
52355  return SQLITE_OK;
52356}
52357
52358/*
52359** A write-transaction must be opened before calling this function.
52360** It performs a single unit of work towards an incremental vacuum.
52361**
52362** If the incremental vacuum is finished after this function has run,
52363** SQLITE_DONE is returned. If it is not finished, but no error occurred,
52364** SQLITE_OK is returned. Otherwise an SQLite error code.
52365*/
52366SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
52367  int rc;
52368  BtShared *pBt = p->pBt;
52369
52370  sqlite3BtreeEnter(p);
52371  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
52372  if( !pBt->autoVacuum ){
52373    rc = SQLITE_DONE;
52374  }else{
52375    invalidateAllOverflowCache(pBt);
52376    rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
52377    if( rc==SQLITE_OK ){
52378      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52379      put4byte(&pBt->pPage1->aData[28], pBt->nPage);
52380    }
52381  }
52382  sqlite3BtreeLeave(p);
52383  return rc;
52384}
52385
52386/*
52387** This routine is called prior to sqlite3PagerCommit when a transaction
52388** is commited for an auto-vacuum database.
52389**
52390** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
52391** the database file should be truncated to during the commit process.
52392** i.e. the database has been reorganized so that only the first *pnTrunc
52393** pages are in use.
52394*/
52395static int autoVacuumCommit(BtShared *pBt){
52396  int rc = SQLITE_OK;
52397  Pager *pPager = pBt->pPager;
52398  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
52399
52400  assert( sqlite3_mutex_held(pBt->mutex) );
52401  invalidateAllOverflowCache(pBt);
52402  assert(pBt->autoVacuum);
52403  if( !pBt->incrVacuum ){
52404    Pgno nFin;         /* Number of pages in database after autovacuuming */
52405    Pgno nFree;        /* Number of pages on the freelist initially */
52406    Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
52407    Pgno iFree;        /* The next page to be freed */
52408    int nEntry;        /* Number of entries on one ptrmap page */
52409    Pgno nOrig;        /* Database size before freeing */
52410
52411    nOrig = btreePagecount(pBt);
52412    if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
52413      /* It is not possible to create a database for which the final page
52414      ** is either a pointer-map page or the pending-byte page. If one
52415      ** is encountered, this indicates corruption.
52416      */
52417      return SQLITE_CORRUPT_BKPT;
52418    }
52419
52420    nFree = get4byte(&pBt->pPage1->aData[36]);
52421    nEntry = pBt->usableSize/5;
52422    nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
52423    nFin = nOrig - nFree - nPtrmap;
52424    if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
52425      nFin--;
52426    }
52427    while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
52428      nFin--;
52429    }
52430    if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
52431
52432    for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
52433      rc = incrVacuumStep(pBt, nFin, iFree);
52434    }
52435    if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
52436      rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52437      put4byte(&pBt->pPage1->aData[32], 0);
52438      put4byte(&pBt->pPage1->aData[36], 0);
52439      put4byte(&pBt->pPage1->aData[28], nFin);
52440      sqlite3PagerTruncateImage(pBt->pPager, nFin);
52441      pBt->nPage = nFin;
52442    }
52443    if( rc!=SQLITE_OK ){
52444      sqlite3PagerRollback(pPager);
52445    }
52446  }
52447
52448  assert( nRef==sqlite3PagerRefcount(pPager) );
52449  return rc;
52450}
52451
52452#else /* ifndef SQLITE_OMIT_AUTOVACUUM */
52453# define setChildPtrmaps(x) SQLITE_OK
52454#endif
52455
52456/*
52457** This routine does the first phase of a two-phase commit.  This routine
52458** causes a rollback journal to be created (if it does not already exist)
52459** and populated with enough information so that if a power loss occurs
52460** the database can be restored to its original state by playing back
52461** the journal.  Then the contents of the journal are flushed out to
52462** the disk.  After the journal is safely on oxide, the changes to the
52463** database are written into the database file and flushed to oxide.
52464** At the end of this call, the rollback journal still exists on the
52465** disk and we are still holding all locks, so the transaction has not
52466** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
52467** commit process.
52468**
52469** This call is a no-op if no write-transaction is currently active on pBt.
52470**
52471** Otherwise, sync the database file for the btree pBt. zMaster points to
52472** the name of a master journal file that should be written into the
52473** individual journal file, or is NULL, indicating no master journal file
52474** (single database transaction).
52475**
52476** When this is called, the master journal should already have been
52477** created, populated with this journal pointer and synced to disk.
52478**
52479** Once this is routine has returned, the only thing required to commit
52480** the write-transaction for this database file is to delete the journal.
52481*/
52482SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
52483  int rc = SQLITE_OK;
52484  if( p->inTrans==TRANS_WRITE ){
52485    BtShared *pBt = p->pBt;
52486    sqlite3BtreeEnter(p);
52487#ifndef SQLITE_OMIT_AUTOVACUUM
52488    if( pBt->autoVacuum ){
52489      rc = autoVacuumCommit(pBt);
52490      if( rc!=SQLITE_OK ){
52491        sqlite3BtreeLeave(p);
52492        return rc;
52493      }
52494    }
52495#endif
52496    rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
52497    sqlite3BtreeLeave(p);
52498  }
52499  return rc;
52500}
52501
52502/*
52503** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
52504** at the conclusion of a transaction.
52505*/
52506static void btreeEndTransaction(Btree *p){
52507  BtShared *pBt = p->pBt;
52508  assert( sqlite3BtreeHoldsMutex(p) );
52509
52510  btreeClearHasContent(pBt);
52511  if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
52512    /* If there are other active statements that belong to this database
52513    ** handle, downgrade to a read-only transaction. The other statements
52514    ** may still be reading from the database.  */
52515    downgradeAllSharedCacheTableLocks(p);
52516    p->inTrans = TRANS_READ;
52517  }else{
52518    /* If the handle had any kind of transaction open, decrement the
52519    ** transaction count of the shared btree. If the transaction count
52520    ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
52521    ** call below will unlock the pager.  */
52522    if( p->inTrans!=TRANS_NONE ){
52523      clearAllSharedCacheTableLocks(p);
52524      pBt->nTransaction--;
52525      if( 0==pBt->nTransaction ){
52526        pBt->inTransaction = TRANS_NONE;
52527      }
52528    }
52529
52530    /* Set the current transaction state to TRANS_NONE and unlock the
52531    ** pager if this call closed the only read or write transaction.  */
52532    p->inTrans = TRANS_NONE;
52533    unlockBtreeIfUnused(pBt);
52534  }
52535
52536  btreeIntegrity(p);
52537}
52538
52539/*
52540** Commit the transaction currently in progress.
52541**
52542** This routine implements the second phase of a 2-phase commit.  The
52543** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
52544** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
52545** routine did all the work of writing information out to disk and flushing the
52546** contents so that they are written onto the disk platter.  All this
52547** routine has to do is delete or truncate or zero the header in the
52548** the rollback journal (which causes the transaction to commit) and
52549** drop locks.
52550**
52551** Normally, if an error occurs while the pager layer is attempting to
52552** finalize the underlying journal file, this function returns an error and
52553** the upper layer will attempt a rollback. However, if the second argument
52554** is non-zero then this b-tree transaction is part of a multi-file
52555** transaction. In this case, the transaction has already been committed
52556** (by deleting a master journal file) and the caller will ignore this
52557** functions return code. So, even if an error occurs in the pager layer,
52558** reset the b-tree objects internal state to indicate that the write
52559** transaction has been closed. This is quite safe, as the pager will have
52560** transitioned to the error state.
52561**
52562** This will release the write lock on the database file.  If there
52563** are no active cursors, it also releases the read lock.
52564*/
52565SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
52566
52567  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
52568  sqlite3BtreeEnter(p);
52569  btreeIntegrity(p);
52570
52571  /* If the handle has a write-transaction open, commit the shared-btrees
52572  ** transaction and set the shared state to TRANS_READ.
52573  */
52574  if( p->inTrans==TRANS_WRITE ){
52575    int rc;
52576    BtShared *pBt = p->pBt;
52577    assert( pBt->inTransaction==TRANS_WRITE );
52578    assert( pBt->nTransaction>0 );
52579    rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
52580    if( rc!=SQLITE_OK && bCleanup==0 ){
52581      sqlite3BtreeLeave(p);
52582      return rc;
52583    }
52584    pBt->inTransaction = TRANS_READ;
52585  }
52586
52587  btreeEndTransaction(p);
52588  sqlite3BtreeLeave(p);
52589  return SQLITE_OK;
52590}
52591
52592/*
52593** Do both phases of a commit.
52594*/
52595SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
52596  int rc;
52597  sqlite3BtreeEnter(p);
52598  rc = sqlite3BtreeCommitPhaseOne(p, 0);
52599  if( rc==SQLITE_OK ){
52600    rc = sqlite3BtreeCommitPhaseTwo(p, 0);
52601  }
52602  sqlite3BtreeLeave(p);
52603  return rc;
52604}
52605
52606#ifndef NDEBUG
52607/*
52608** Return the number of write-cursors open on this handle. This is for use
52609** in assert() expressions, so it is only compiled if NDEBUG is not
52610** defined.
52611**
52612** For the purposes of this routine, a write-cursor is any cursor that
52613** is capable of writing to the databse.  That means the cursor was
52614** originally opened for writing and the cursor has not be disabled
52615** by having its state changed to CURSOR_FAULT.
52616*/
52617static int countWriteCursors(BtShared *pBt){
52618  BtCursor *pCur;
52619  int r = 0;
52620  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
52621    if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++;
52622  }
52623  return r;
52624}
52625#endif
52626
52627/*
52628** This routine sets the state to CURSOR_FAULT and the error
52629** code to errCode for every cursor on BtShared that pBtree
52630** references.
52631**
52632** Every cursor is tripped, including cursors that belong
52633** to other database connections that happen to be sharing
52634** the cache with pBtree.
52635**
52636** This routine gets called when a rollback occurs.
52637** All cursors using the same cache must be tripped
52638** to prevent them from trying to use the btree after
52639** the rollback.  The rollback may have deleted tables
52640** or moved root pages, so it is not sufficient to
52641** save the state of the cursor.  The cursor must be
52642** invalidated.
52643*/
52644SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
52645  BtCursor *p;
52646  if( pBtree==0 ) return;
52647  sqlite3BtreeEnter(pBtree);
52648  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52649    int i;
52650    sqlite3BtreeClearCursor(p);
52651    p->eState = CURSOR_FAULT;
52652    p->skipNext = errCode;
52653    for(i=0; i<=p->iPage; i++){
52654      releasePage(p->apPage[i]);
52655      p->apPage[i] = 0;
52656    }
52657  }
52658  sqlite3BtreeLeave(pBtree);
52659}
52660
52661/*
52662** Rollback the transaction in progress.  All cursors will be
52663** invalided by this operation.  Any attempt to use a cursor
52664** that was open at the beginning of this operation will result
52665** in an error.
52666**
52667** This will release the write lock on the database file.  If there
52668** are no active cursors, it also releases the read lock.
52669*/
52670SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
52671  int rc;
52672  BtShared *pBt = p->pBt;
52673  MemPage *pPage1;
52674
52675  sqlite3BtreeEnter(p);
52676  if( tripCode==SQLITE_OK ){
52677    rc = tripCode = saveAllCursors(pBt, 0, 0);
52678  }else{
52679    rc = SQLITE_OK;
52680  }
52681  if( tripCode ){
52682    sqlite3BtreeTripAllCursors(p, tripCode);
52683  }
52684  btreeIntegrity(p);
52685
52686  if( p->inTrans==TRANS_WRITE ){
52687    int rc2;
52688
52689    assert( TRANS_WRITE==pBt->inTransaction );
52690    rc2 = sqlite3PagerRollback(pBt->pPager);
52691    if( rc2!=SQLITE_OK ){
52692      rc = rc2;
52693    }
52694
52695    /* The rollback may have destroyed the pPage1->aData value.  So
52696    ** call btreeGetPage() on page 1 again to make
52697    ** sure pPage1->aData is set correctly. */
52698    if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
52699      int nPage = get4byte(28+(u8*)pPage1->aData);
52700      testcase( nPage==0 );
52701      if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
52702      testcase( pBt->nPage!=nPage );
52703      pBt->nPage = nPage;
52704      releasePage(pPage1);
52705    }
52706    assert( countWriteCursors(pBt)==0 );
52707    pBt->inTransaction = TRANS_READ;
52708  }
52709
52710  btreeEndTransaction(p);
52711  sqlite3BtreeLeave(p);
52712  return rc;
52713}
52714
52715/*
52716** Start a statement subtransaction. The subtransaction can can be rolled
52717** back independently of the main transaction. You must start a transaction
52718** before starting a subtransaction. The subtransaction is ended automatically
52719** if the main transaction commits or rolls back.
52720**
52721** Statement subtransactions are used around individual SQL statements
52722** that are contained within a BEGIN...COMMIT block.  If a constraint
52723** error occurs within the statement, the effect of that one statement
52724** can be rolled back without having to rollback the entire transaction.
52725**
52726** A statement sub-transaction is implemented as an anonymous savepoint. The
52727** value passed as the second parameter is the total number of savepoints,
52728** including the new anonymous savepoint, open on the B-Tree. i.e. if there
52729** are no active savepoints and no other statement-transactions open,
52730** iStatement is 1. This anonymous savepoint can be released or rolled back
52731** using the sqlite3BtreeSavepoint() function.
52732*/
52733SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
52734  int rc;
52735  BtShared *pBt = p->pBt;
52736  sqlite3BtreeEnter(p);
52737  assert( p->inTrans==TRANS_WRITE );
52738  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
52739  assert( iStatement>0 );
52740  assert( iStatement>p->db->nSavepoint );
52741  assert( pBt->inTransaction==TRANS_WRITE );
52742  /* At the pager level, a statement transaction is a savepoint with
52743  ** an index greater than all savepoints created explicitly using
52744  ** SQL statements. It is illegal to open, release or rollback any
52745  ** such savepoints while the statement transaction savepoint is active.
52746  */
52747  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
52748  sqlite3BtreeLeave(p);
52749  return rc;
52750}
52751
52752/*
52753** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
52754** or SAVEPOINT_RELEASE. This function either releases or rolls back the
52755** savepoint identified by parameter iSavepoint, depending on the value
52756** of op.
52757**
52758** Normally, iSavepoint is greater than or equal to zero. However, if op is
52759** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
52760** contents of the entire transaction are rolled back. This is different
52761** from a normal transaction rollback, as no locks are released and the
52762** transaction remains open.
52763*/
52764SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
52765  int rc = SQLITE_OK;
52766  if( p && p->inTrans==TRANS_WRITE ){
52767    BtShared *pBt = p->pBt;
52768    assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
52769    assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
52770    sqlite3BtreeEnter(p);
52771    rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
52772    if( rc==SQLITE_OK ){
52773      if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
52774        pBt->nPage = 0;
52775      }
52776      rc = newDatabase(pBt);
52777      pBt->nPage = get4byte(28 + pBt->pPage1->aData);
52778
52779      /* The database size was written into the offset 28 of the header
52780      ** when the transaction started, so we know that the value at offset
52781      ** 28 is nonzero. */
52782      assert( pBt->nPage>0 );
52783    }
52784    sqlite3BtreeLeave(p);
52785  }
52786  return rc;
52787}
52788
52789/*
52790** Create a new cursor for the BTree whose root is on the page
52791** iTable. If a read-only cursor is requested, it is assumed that
52792** the caller already has at least a read-only transaction open
52793** on the database already. If a write-cursor is requested, then
52794** the caller is assumed to have an open write transaction.
52795**
52796** If wrFlag==0, then the cursor can only be used for reading.
52797** If wrFlag==1, then the cursor can be used for reading or for
52798** writing if other conditions for writing are also met.  These
52799** are the conditions that must be met in order for writing to
52800** be allowed:
52801**
52802** 1:  The cursor must have been opened with wrFlag==1
52803**
52804** 2:  Other database connections that share the same pager cache
52805**     but which are not in the READ_UNCOMMITTED state may not have
52806**     cursors open with wrFlag==0 on the same table.  Otherwise
52807**     the changes made by this write cursor would be visible to
52808**     the read cursors in the other database connection.
52809**
52810** 3:  The database must be writable (not on read-only media)
52811**
52812** 4:  There must be an active transaction.
52813**
52814** No checking is done to make sure that page iTable really is the
52815** root page of a b-tree.  If it is not, then the cursor acquired
52816** will not work correctly.
52817**
52818** It is assumed that the sqlite3BtreeCursorZero() has been called
52819** on pCur to initialize the memory space prior to invoking this routine.
52820*/
52821static int btreeCursor(
52822  Btree *p,                              /* The btree */
52823  int iTable,                            /* Root page of table to open */
52824  int wrFlag,                            /* 1 to write. 0 read-only */
52825  struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
52826  BtCursor *pCur                         /* Space for new cursor */
52827){
52828  BtShared *pBt = p->pBt;                /* Shared b-tree handle */
52829
52830  assert( sqlite3BtreeHoldsMutex(p) );
52831  assert( wrFlag==0 || wrFlag==1 );
52832
52833  /* The following assert statements verify that if this is a sharable
52834  ** b-tree database, the connection is holding the required table locks,
52835  ** and that no other connection has any open cursor that conflicts with
52836  ** this lock.  */
52837  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
52838  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
52839
52840  /* Assert that the caller has opened the required transaction. */
52841  assert( p->inTrans>TRANS_NONE );
52842  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
52843  assert( pBt->pPage1 && pBt->pPage1->aData );
52844
52845  if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
52846    return SQLITE_READONLY;
52847  }
52848  if( iTable==1 && btreePagecount(pBt)==0 ){
52849    assert( wrFlag==0 );
52850    iTable = 0;
52851  }
52852
52853  /* Now that no other errors can occur, finish filling in the BtCursor
52854  ** variables and link the cursor into the BtShared list.  */
52855  pCur->pgnoRoot = (Pgno)iTable;
52856  pCur->iPage = -1;
52857  pCur->pKeyInfo = pKeyInfo;
52858  pCur->pBtree = p;
52859  pCur->pBt = pBt;
52860  pCur->wrFlag = (u8)wrFlag;
52861  pCur->pNext = pBt->pCursor;
52862  if( pCur->pNext ){
52863    pCur->pNext->pPrev = pCur;
52864  }
52865  pBt->pCursor = pCur;
52866  pCur->eState = CURSOR_INVALID;
52867  pCur->cachedRowid = 0;
52868  return SQLITE_OK;
52869}
52870SQLITE_PRIVATE int sqlite3BtreeCursor(
52871  Btree *p,                                   /* The btree */
52872  int iTable,                                 /* Root page of table to open */
52873  int wrFlag,                                 /* 1 to write. 0 read-only */
52874  struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
52875  BtCursor *pCur                              /* Write new cursor here */
52876){
52877  int rc;
52878  sqlite3BtreeEnter(p);
52879  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
52880  sqlite3BtreeLeave(p);
52881  return rc;
52882}
52883
52884/*
52885** Return the size of a BtCursor object in bytes.
52886**
52887** This interfaces is needed so that users of cursors can preallocate
52888** sufficient storage to hold a cursor.  The BtCursor object is opaque
52889** to users so they cannot do the sizeof() themselves - they must call
52890** this routine.
52891*/
52892SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
52893  return ROUND8(sizeof(BtCursor));
52894}
52895
52896/*
52897** Initialize memory that will be converted into a BtCursor object.
52898**
52899** The simple approach here would be to memset() the entire object
52900** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
52901** do not need to be zeroed and they are large, so we can save a lot
52902** of run-time by skipping the initialization of those elements.
52903*/
52904SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
52905  memset(p, 0, offsetof(BtCursor, iPage));
52906}
52907
52908/*
52909** Set the cached rowid value of every cursor in the same database file
52910** as pCur and having the same root page number as pCur.  The value is
52911** set to iRowid.
52912**
52913** Only positive rowid values are considered valid for this cache.
52914** The cache is initialized to zero, indicating an invalid cache.
52915** A btree will work fine with zero or negative rowids.  We just cannot
52916** cache zero or negative rowids, which means tables that use zero or
52917** negative rowids might run a little slower.  But in practice, zero
52918** or negative rowids are very uncommon so this should not be a problem.
52919*/
52920SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
52921  BtCursor *p;
52922  for(p=pCur->pBt->pCursor; p; p=p->pNext){
52923    if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
52924  }
52925  assert( pCur->cachedRowid==iRowid );
52926}
52927
52928/*
52929** Return the cached rowid for the given cursor.  A negative or zero
52930** return value indicates that the rowid cache is invalid and should be
52931** ignored.  If the rowid cache has never before been set, then a
52932** zero is returned.
52933*/
52934SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
52935  return pCur->cachedRowid;
52936}
52937
52938/*
52939** Close a cursor.  The read lock on the database file is released
52940** when the last cursor is closed.
52941*/
52942SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
52943  Btree *pBtree = pCur->pBtree;
52944  if( pBtree ){
52945    int i;
52946    BtShared *pBt = pCur->pBt;
52947    sqlite3BtreeEnter(pBtree);
52948    sqlite3BtreeClearCursor(pCur);
52949    if( pCur->pPrev ){
52950      pCur->pPrev->pNext = pCur->pNext;
52951    }else{
52952      pBt->pCursor = pCur->pNext;
52953    }
52954    if( pCur->pNext ){
52955      pCur->pNext->pPrev = pCur->pPrev;
52956    }
52957    for(i=0; i<=pCur->iPage; i++){
52958      releasePage(pCur->apPage[i]);
52959    }
52960    unlockBtreeIfUnused(pBt);
52961    invalidateOverflowCache(pCur);
52962    /* sqlite3_free(pCur); */
52963    sqlite3BtreeLeave(pBtree);
52964  }
52965  return SQLITE_OK;
52966}
52967
52968/*
52969** Make sure the BtCursor* given in the argument has a valid
52970** BtCursor.info structure.  If it is not already valid, call
52971** btreeParseCell() to fill it in.
52972**
52973** BtCursor.info is a cache of the information in the current cell.
52974** Using this cache reduces the number of calls to btreeParseCell().
52975**
52976** 2007-06-25:  There is a bug in some versions of MSVC that cause the
52977** compiler to crash when getCellInfo() is implemented as a macro.
52978** But there is a measureable speed advantage to using the macro on gcc
52979** (when less compiler optimizations like -Os or -O0 are used and the
52980** compiler is not doing agressive inlining.)  So we use a real function
52981** for MSVC and a macro for everything else.  Ticket #2457.
52982*/
52983#ifndef NDEBUG
52984  static void assertCellInfo(BtCursor *pCur){
52985    CellInfo info;
52986    int iPage = pCur->iPage;
52987    memset(&info, 0, sizeof(info));
52988    btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
52989    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
52990  }
52991#else
52992  #define assertCellInfo(x)
52993#endif
52994#ifdef _MSC_VER
52995  /* Use a real function in MSVC to work around bugs in that compiler. */
52996  static void getCellInfo(BtCursor *pCur){
52997    if( pCur->info.nSize==0 ){
52998      int iPage = pCur->iPage;
52999      btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
53000      pCur->validNKey = 1;
53001    }else{
53002      assertCellInfo(pCur);
53003    }
53004  }
53005#else /* if not _MSC_VER */
53006  /* Use a macro in all other compilers so that the function is inlined */
53007#define getCellInfo(pCur)                                                      \
53008  if( pCur->info.nSize==0 ){                                                   \
53009    int iPage = pCur->iPage;                                                   \
53010    btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
53011    pCur->validNKey = 1;                                                       \
53012  }else{                                                                       \
53013    assertCellInfo(pCur);                                                      \
53014  }
53015#endif /* _MSC_VER */
53016
53017#ifndef NDEBUG  /* The next routine used only within assert() statements */
53018/*
53019** Return true if the given BtCursor is valid.  A valid cursor is one
53020** that is currently pointing to a row in a (non-empty) table.
53021** This is a verification routine is used only within assert() statements.
53022*/
53023SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
53024  return pCur && pCur->eState==CURSOR_VALID;
53025}
53026#endif /* NDEBUG */
53027
53028/*
53029** Set *pSize to the size of the buffer needed to hold the value of
53030** the key for the current entry.  If the cursor is not pointing
53031** to a valid entry, *pSize is set to 0.
53032**
53033** For a table with the INTKEY flag set, this routine returns the key
53034** itself, not the number of bytes in the key.
53035**
53036** The caller must position the cursor prior to invoking this routine.
53037**
53038** This routine cannot fail.  It always returns SQLITE_OK.
53039*/
53040SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
53041  assert( cursorHoldsMutex(pCur) );
53042  assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
53043  if( pCur->eState!=CURSOR_VALID ){
53044    *pSize = 0;
53045  }else{
53046    getCellInfo(pCur);
53047    *pSize = pCur->info.nKey;
53048  }
53049  return SQLITE_OK;
53050}
53051
53052/*
53053** Set *pSize to the number of bytes of data in the entry the
53054** cursor currently points to.
53055**
53056** The caller must guarantee that the cursor is pointing to a non-NULL
53057** valid entry.  In other words, the calling procedure must guarantee
53058** that the cursor has Cursor.eState==CURSOR_VALID.
53059**
53060** Failure is not possible.  This function always returns SQLITE_OK.
53061** It might just as well be a procedure (returning void) but we continue
53062** to return an integer result code for historical reasons.
53063*/
53064SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
53065  assert( cursorHoldsMutex(pCur) );
53066  assert( pCur->eState==CURSOR_VALID );
53067  getCellInfo(pCur);
53068  *pSize = pCur->info.nData;
53069  return SQLITE_OK;
53070}
53071
53072/*
53073** Given the page number of an overflow page in the database (parameter
53074** ovfl), this function finds the page number of the next page in the
53075** linked list of overflow pages. If possible, it uses the auto-vacuum
53076** pointer-map data instead of reading the content of page ovfl to do so.
53077**
53078** If an error occurs an SQLite error code is returned. Otherwise:
53079**
53080** The page number of the next overflow page in the linked list is
53081** written to *pPgnoNext. If page ovfl is the last page in its linked
53082** list, *pPgnoNext is set to zero.
53083**
53084** If ppPage is not NULL, and a reference to the MemPage object corresponding
53085** to page number pOvfl was obtained, then *ppPage is set to point to that
53086** reference. It is the responsibility of the caller to call releasePage()
53087** on *ppPage to free the reference. In no reference was obtained (because
53088** the pointer-map was used to obtain the value for *pPgnoNext), then
53089** *ppPage is set to zero.
53090*/
53091static int getOverflowPage(
53092  BtShared *pBt,               /* The database file */
53093  Pgno ovfl,                   /* Current overflow page number */
53094  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
53095  Pgno *pPgnoNext              /* OUT: Next overflow page number */
53096){
53097  Pgno next = 0;
53098  MemPage *pPage = 0;
53099  int rc = SQLITE_OK;
53100
53101  assert( sqlite3_mutex_held(pBt->mutex) );
53102  assert(pPgnoNext);
53103
53104#ifndef SQLITE_OMIT_AUTOVACUUM
53105  /* Try to find the next page in the overflow list using the
53106  ** autovacuum pointer-map pages. Guess that the next page in
53107  ** the overflow list is page number (ovfl+1). If that guess turns
53108  ** out to be wrong, fall back to loading the data of page
53109  ** number ovfl to determine the next page number.
53110  */
53111  if( pBt->autoVacuum ){
53112    Pgno pgno;
53113    Pgno iGuess = ovfl+1;
53114    u8 eType;
53115
53116    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
53117      iGuess++;
53118    }
53119
53120    if( iGuess<=btreePagecount(pBt) ){
53121      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
53122      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
53123        next = iGuess;
53124        rc = SQLITE_DONE;
53125      }
53126    }
53127  }
53128#endif
53129
53130  assert( next==0 || rc==SQLITE_DONE );
53131  if( rc==SQLITE_OK ){
53132    rc = btreeGetPage(pBt, ovfl, &pPage, 0);
53133    assert( rc==SQLITE_OK || pPage==0 );
53134    if( rc==SQLITE_OK ){
53135      next = get4byte(pPage->aData);
53136    }
53137  }
53138
53139  *pPgnoNext = next;
53140  if( ppPage ){
53141    *ppPage = pPage;
53142  }else{
53143    releasePage(pPage);
53144  }
53145  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
53146}
53147
53148/*
53149** Copy data from a buffer to a page, or from a page to a buffer.
53150**
53151** pPayload is a pointer to data stored on database page pDbPage.
53152** If argument eOp is false, then nByte bytes of data are copied
53153** from pPayload to the buffer pointed at by pBuf. If eOp is true,
53154** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
53155** of data are copied from the buffer pBuf to pPayload.
53156**
53157** SQLITE_OK is returned on success, otherwise an error code.
53158*/
53159static int copyPayload(
53160  void *pPayload,           /* Pointer to page data */
53161  void *pBuf,               /* Pointer to buffer */
53162  int nByte,                /* Number of bytes to copy */
53163  int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
53164  DbPage *pDbPage           /* Page containing pPayload */
53165){
53166  if( eOp ){
53167    /* Copy data from buffer to page (a write operation) */
53168    int rc = sqlite3PagerWrite(pDbPage);
53169    if( rc!=SQLITE_OK ){
53170      return rc;
53171    }
53172    memcpy(pPayload, pBuf, nByte);
53173  }else{
53174    /* Copy data from page to buffer (a read operation) */
53175    memcpy(pBuf, pPayload, nByte);
53176  }
53177  return SQLITE_OK;
53178}
53179
53180/*
53181** This function is used to read or overwrite payload information
53182** for the entry that the pCur cursor is pointing to. If the eOp
53183** parameter is 0, this is a read operation (data copied into
53184** buffer pBuf). If it is non-zero, a write (data copied from
53185** buffer pBuf).
53186**
53187** A total of "amt" bytes are read or written beginning at "offset".
53188** Data is read to or from the buffer pBuf.
53189**
53190** The content being read or written might appear on the main page
53191** or be scattered out on multiple overflow pages.
53192**
53193** If the BtCursor.isIncrblobHandle flag is set, and the current
53194** cursor entry uses one or more overflow pages, this function
53195** allocates space for and lazily popluates the overflow page-list
53196** cache array (BtCursor.aOverflow). Subsequent calls use this
53197** cache to make seeking to the supplied offset more efficient.
53198**
53199** Once an overflow page-list cache has been allocated, it may be
53200** invalidated if some other cursor writes to the same table, or if
53201** the cursor is moved to a different row. Additionally, in auto-vacuum
53202** mode, the following events may invalidate an overflow page-list cache.
53203**
53204**   * An incremental vacuum,
53205**   * A commit in auto_vacuum="full" mode,
53206**   * Creating a table (may require moving an overflow page).
53207*/
53208static int accessPayload(
53209  BtCursor *pCur,      /* Cursor pointing to entry to read from */
53210  u32 offset,          /* Begin reading this far into payload */
53211  u32 amt,             /* Read this many bytes */
53212  unsigned char *pBuf, /* Write the bytes into this buffer */
53213  int eOp              /* zero to read. non-zero to write. */
53214){
53215  unsigned char *aPayload;
53216  int rc = SQLITE_OK;
53217  u32 nKey;
53218  int iIdx = 0;
53219  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
53220  BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
53221
53222  assert( pPage );
53223  assert( pCur->eState==CURSOR_VALID );
53224  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53225  assert( cursorHoldsMutex(pCur) );
53226
53227  getCellInfo(pCur);
53228  aPayload = pCur->info.pCell + pCur->info.nHeader;
53229  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
53230
53231  if( NEVER(offset+amt > nKey+pCur->info.nData)
53232   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
53233  ){
53234    /* Trying to read or write past the end of the data is an error */
53235    return SQLITE_CORRUPT_BKPT;
53236  }
53237
53238  /* Check if data must be read/written to/from the btree page itself. */
53239  if( offset<pCur->info.nLocal ){
53240    int a = amt;
53241    if( a+offset>pCur->info.nLocal ){
53242      a = pCur->info.nLocal - offset;
53243    }
53244    rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
53245    offset = 0;
53246    pBuf += a;
53247    amt -= a;
53248  }else{
53249    offset -= pCur->info.nLocal;
53250  }
53251
53252  if( rc==SQLITE_OK && amt>0 ){
53253    const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
53254    Pgno nextPage;
53255
53256    nextPage = get4byte(&aPayload[pCur->info.nLocal]);
53257
53258#ifndef SQLITE_OMIT_INCRBLOB
53259    /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
53260    ** has not been allocated, allocate it now. The array is sized at
53261    ** one entry for each overflow page in the overflow chain. The
53262    ** page number of the first overflow page is stored in aOverflow[0],
53263    ** etc. A value of 0 in the aOverflow[] array means "not yet known"
53264    ** (the cache is lazily populated).
53265    */
53266    if( pCur->isIncrblobHandle && !pCur->aOverflow ){
53267      int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
53268      pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
53269      /* nOvfl is always positive.  If it were zero, fetchPayload would have
53270      ** been used instead of this routine. */
53271      if( ALWAYS(nOvfl) && !pCur->aOverflow ){
53272        rc = SQLITE_NOMEM;
53273      }
53274    }
53275
53276    /* If the overflow page-list cache has been allocated and the
53277    ** entry for the first required overflow page is valid, skip
53278    ** directly to it.
53279    */
53280    if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
53281      iIdx = (offset/ovflSize);
53282      nextPage = pCur->aOverflow[iIdx];
53283      offset = (offset%ovflSize);
53284    }
53285#endif
53286
53287    for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
53288
53289#ifndef SQLITE_OMIT_INCRBLOB
53290      /* If required, populate the overflow page-list cache. */
53291      if( pCur->aOverflow ){
53292        assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
53293        pCur->aOverflow[iIdx] = nextPage;
53294      }
53295#endif
53296
53297      if( offset>=ovflSize ){
53298        /* The only reason to read this page is to obtain the page
53299        ** number for the next page in the overflow chain. The page
53300        ** data is not required. So first try to lookup the overflow
53301        ** page-list cache, if any, then fall back to the getOverflowPage()
53302        ** function.
53303        */
53304#ifndef SQLITE_OMIT_INCRBLOB
53305        if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
53306          nextPage = pCur->aOverflow[iIdx+1];
53307        } else
53308#endif
53309          rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
53310        offset -= ovflSize;
53311      }else{
53312        /* Need to read this page properly. It contains some of the
53313        ** range of data that is being read (eOp==0) or written (eOp!=0).
53314        */
53315#ifdef SQLITE_DIRECT_OVERFLOW_READ
53316        sqlite3_file *fd;
53317#endif
53318        int a = amt;
53319        if( a + offset > ovflSize ){
53320          a = ovflSize - offset;
53321        }
53322
53323#ifdef SQLITE_DIRECT_OVERFLOW_READ
53324        /* If all the following are true:
53325        **
53326        **   1) this is a read operation, and
53327        **   2) data is required from the start of this overflow page, and
53328        **   3) the database is file-backed, and
53329        **   4) there is no open write-transaction, and
53330        **   5) the database is not a WAL database,
53331        **
53332        ** then data can be read directly from the database file into the
53333        ** output buffer, bypassing the page-cache altogether. This speeds
53334        ** up loading large records that span many overflow pages.
53335        */
53336        if( eOp==0                                             /* (1) */
53337         && offset==0                                          /* (2) */
53338         && pBt->inTransaction==TRANS_READ                     /* (4) */
53339         && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
53340         && pBt->pPage1->aData[19]==0x01                       /* (5) */
53341        ){
53342          u8 aSave[4];
53343          u8 *aWrite = &pBuf[-4];
53344          memcpy(aSave, aWrite, 4);
53345          rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
53346          nextPage = get4byte(aWrite);
53347          memcpy(aWrite, aSave, 4);
53348        }else
53349#endif
53350
53351        {
53352          DbPage *pDbPage;
53353          rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
53354          if( rc==SQLITE_OK ){
53355            aPayload = sqlite3PagerGetData(pDbPage);
53356            nextPage = get4byte(aPayload);
53357            rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
53358            sqlite3PagerUnref(pDbPage);
53359            offset = 0;
53360          }
53361        }
53362        amt -= a;
53363        pBuf += a;
53364      }
53365    }
53366  }
53367
53368  if( rc==SQLITE_OK && amt>0 ){
53369    return SQLITE_CORRUPT_BKPT;
53370  }
53371  return rc;
53372}
53373
53374/*
53375** Read part of the key associated with cursor pCur.  Exactly
53376** "amt" bytes will be transfered into pBuf[].  The transfer
53377** begins at "offset".
53378**
53379** The caller must ensure that pCur is pointing to a valid row
53380** in the table.
53381**
53382** Return SQLITE_OK on success or an error code if anything goes
53383** wrong.  An error is returned if "offset+amt" is larger than
53384** the available payload.
53385*/
53386SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53387  assert( cursorHoldsMutex(pCur) );
53388  assert( pCur->eState==CURSOR_VALID );
53389  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53390  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53391  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
53392}
53393
53394/*
53395** Read part of the data associated with cursor pCur.  Exactly
53396** "amt" bytes will be transfered into pBuf[].  The transfer
53397** begins at "offset".
53398**
53399** Return SQLITE_OK on success or an error code if anything goes
53400** wrong.  An error is returned if "offset+amt" is larger than
53401** the available payload.
53402*/
53403SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53404  int rc;
53405
53406#ifndef SQLITE_OMIT_INCRBLOB
53407  if ( pCur->eState==CURSOR_INVALID ){
53408    return SQLITE_ABORT;
53409  }
53410#endif
53411
53412  assert( cursorHoldsMutex(pCur) );
53413  rc = restoreCursorPosition(pCur);
53414  if( rc==SQLITE_OK ){
53415    assert( pCur->eState==CURSOR_VALID );
53416    assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53417    assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53418    rc = accessPayload(pCur, offset, amt, pBuf, 0);
53419  }
53420  return rc;
53421}
53422
53423/*
53424** Return a pointer to payload information from the entry that the
53425** pCur cursor is pointing to.  The pointer is to the beginning of
53426** the key if skipKey==0 and it points to the beginning of data if
53427** skipKey==1.  The number of bytes of available key/data is written
53428** into *pAmt.  If *pAmt==0, then the value returned will not be
53429** a valid pointer.
53430**
53431** This routine is an optimization.  It is common for the entire key
53432** and data to fit on the local page and for there to be no overflow
53433** pages.  When that is so, this routine can be used to access the
53434** key and data without making a copy.  If the key and/or data spills
53435** onto overflow pages, then accessPayload() must be used to reassemble
53436** the key/data and copy it into a preallocated buffer.
53437**
53438** The pointer returned by this routine looks directly into the cached
53439** page of the database.  The data might change or move the next time
53440** any btree routine is called.
53441*/
53442static const unsigned char *fetchPayload(
53443  BtCursor *pCur,      /* Cursor pointing to entry to read from */
53444  int *pAmt,           /* Write the number of available bytes here */
53445  int skipKey          /* read beginning at data if this is true */
53446){
53447  unsigned char *aPayload;
53448  MemPage *pPage;
53449  u32 nKey;
53450  u32 nLocal;
53451
53452  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
53453  assert( pCur->eState==CURSOR_VALID );
53454  assert( cursorHoldsMutex(pCur) );
53455  pPage = pCur->apPage[pCur->iPage];
53456  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53457  if( NEVER(pCur->info.nSize==0) ){
53458    btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
53459                   &pCur->info);
53460  }
53461  aPayload = pCur->info.pCell;
53462  aPayload += pCur->info.nHeader;
53463  if( pPage->intKey ){
53464    nKey = 0;
53465  }else{
53466    nKey = (int)pCur->info.nKey;
53467  }
53468  if( skipKey ){
53469    aPayload += nKey;
53470    nLocal = pCur->info.nLocal - nKey;
53471  }else{
53472    nLocal = pCur->info.nLocal;
53473    assert( nLocal<=nKey );
53474  }
53475  *pAmt = nLocal;
53476  return aPayload;
53477}
53478
53479
53480/*
53481** For the entry that cursor pCur is point to, return as
53482** many bytes of the key or data as are available on the local
53483** b-tree page.  Write the number of available bytes into *pAmt.
53484**
53485** The pointer returned is ephemeral.  The key/data may move
53486** or be destroyed on the next call to any Btree routine,
53487** including calls from other threads against the same cache.
53488** Hence, a mutex on the BtShared should be held prior to calling
53489** this routine.
53490**
53491** These routines is used to get quick access to key and data
53492** in the common case where no overflow pages are used.
53493*/
53494SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
53495  const void *p = 0;
53496  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53497  assert( cursorHoldsMutex(pCur) );
53498  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53499    p = (const void*)fetchPayload(pCur, pAmt, 0);
53500  }
53501  return p;
53502}
53503SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
53504  const void *p = 0;
53505  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53506  assert( cursorHoldsMutex(pCur) );
53507  if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53508    p = (const void*)fetchPayload(pCur, pAmt, 1);
53509  }
53510  return p;
53511}
53512
53513
53514/*
53515** Move the cursor down to a new child page.  The newPgno argument is the
53516** page number of the child page to move to.
53517**
53518** This function returns SQLITE_CORRUPT if the page-header flags field of
53519** the new child page does not match the flags field of the parent (i.e.
53520** if an intkey page appears to be the parent of a non-intkey page, or
53521** vice-versa).
53522*/
53523static int moveToChild(BtCursor *pCur, u32 newPgno){
53524  int rc;
53525  int i = pCur->iPage;
53526  MemPage *pNewPage;
53527  BtShared *pBt = pCur->pBt;
53528
53529  assert( cursorHoldsMutex(pCur) );
53530  assert( pCur->eState==CURSOR_VALID );
53531  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
53532  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
53533    return SQLITE_CORRUPT_BKPT;
53534  }
53535  rc = getAndInitPage(pBt, newPgno, &pNewPage);
53536  if( rc ) return rc;
53537  pCur->apPage[i+1] = pNewPage;
53538  pCur->aiIdx[i+1] = 0;
53539  pCur->iPage++;
53540
53541  pCur->info.nSize = 0;
53542  pCur->validNKey = 0;
53543  if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
53544    return SQLITE_CORRUPT_BKPT;
53545  }
53546  return SQLITE_OK;
53547}
53548
53549#if 0
53550/*
53551** Page pParent is an internal (non-leaf) tree page. This function
53552** asserts that page number iChild is the left-child if the iIdx'th
53553** cell in page pParent. Or, if iIdx is equal to the total number of
53554** cells in pParent, that page number iChild is the right-child of
53555** the page.
53556*/
53557static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
53558  assert( iIdx<=pParent->nCell );
53559  if( iIdx==pParent->nCell ){
53560    assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
53561  }else{
53562    assert( get4byte(findCell(pParent, iIdx))==iChild );
53563  }
53564}
53565#else
53566#  define assertParentIndex(x,y,z)
53567#endif
53568
53569/*
53570** Move the cursor up to the parent page.
53571**
53572** pCur->idx is set to the cell index that contains the pointer
53573** to the page we are coming from.  If we are coming from the
53574** right-most child page then pCur->idx is set to one more than
53575** the largest cell index.
53576*/
53577static void moveToParent(BtCursor *pCur){
53578  assert( cursorHoldsMutex(pCur) );
53579  assert( pCur->eState==CURSOR_VALID );
53580  assert( pCur->iPage>0 );
53581  assert( pCur->apPage[pCur->iPage] );
53582
53583  /* UPDATE: It is actually possible for the condition tested by the assert
53584  ** below to be untrue if the database file is corrupt. This can occur if
53585  ** one cursor has modified page pParent while a reference to it is held
53586  ** by a second cursor. Which can only happen if a single page is linked
53587  ** into more than one b-tree structure in a corrupt database.  */
53588#if 0
53589  assertParentIndex(
53590    pCur->apPage[pCur->iPage-1],
53591    pCur->aiIdx[pCur->iPage-1],
53592    pCur->apPage[pCur->iPage]->pgno
53593  );
53594#endif
53595  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
53596
53597  releasePage(pCur->apPage[pCur->iPage]);
53598  pCur->iPage--;
53599  pCur->info.nSize = 0;
53600  pCur->validNKey = 0;
53601}
53602
53603/*
53604** Move the cursor to point to the root page of its b-tree structure.
53605**
53606** If the table has a virtual root page, then the cursor is moved to point
53607** to the virtual root page instead of the actual root page. A table has a
53608** virtual root page when the actual root page contains no cells and a
53609** single child page. This can only happen with the table rooted at page 1.
53610**
53611** If the b-tree structure is empty, the cursor state is set to
53612** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
53613** cell located on the root (or virtual root) page and the cursor state
53614** is set to CURSOR_VALID.
53615**
53616** If this function returns successfully, it may be assumed that the
53617** page-header flags indicate that the [virtual] root-page is the expected
53618** kind of b-tree page (i.e. if when opening the cursor the caller did not
53619** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
53620** indicating a table b-tree, or if the caller did specify a KeyInfo
53621** structure the flags byte is set to 0x02 or 0x0A, indicating an index
53622** b-tree).
53623*/
53624static int moveToRoot(BtCursor *pCur){
53625  MemPage *pRoot;
53626  int rc = SQLITE_OK;
53627  Btree *p = pCur->pBtree;
53628  BtShared *pBt = p->pBt;
53629
53630  assert( cursorHoldsMutex(pCur) );
53631  assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
53632  assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
53633  assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
53634  if( pCur->eState>=CURSOR_REQUIRESEEK ){
53635    if( pCur->eState==CURSOR_FAULT ){
53636      assert( pCur->skipNext!=SQLITE_OK );
53637      return pCur->skipNext;
53638    }
53639    sqlite3BtreeClearCursor(pCur);
53640  }
53641
53642  if( pCur->iPage>=0 ){
53643    int i;
53644    for(i=1; i<=pCur->iPage; i++){
53645      releasePage(pCur->apPage[i]);
53646    }
53647    pCur->iPage = 0;
53648  }else if( pCur->pgnoRoot==0 ){
53649    pCur->eState = CURSOR_INVALID;
53650    return SQLITE_OK;
53651  }else{
53652    rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
53653    if( rc!=SQLITE_OK ){
53654      pCur->eState = CURSOR_INVALID;
53655      return rc;
53656    }
53657    pCur->iPage = 0;
53658
53659    /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
53660    ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
53661    ** NULL, the caller expects a table b-tree. If this is not the case,
53662    ** return an SQLITE_CORRUPT error.  */
53663    assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
53664    if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
53665      return SQLITE_CORRUPT_BKPT;
53666    }
53667  }
53668
53669  /* Assert that the root page is of the correct type. This must be the
53670  ** case as the call to this function that loaded the root-page (either
53671  ** this call or a previous invocation) would have detected corruption
53672  ** if the assumption were not true, and it is not possible for the flags
53673  ** byte to have been modified while this cursor is holding a reference
53674  ** to the page.  */
53675  pRoot = pCur->apPage[0];
53676  assert( pRoot->pgno==pCur->pgnoRoot );
53677  assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
53678
53679  pCur->aiIdx[0] = 0;
53680  pCur->info.nSize = 0;
53681  pCur->atLast = 0;
53682  pCur->validNKey = 0;
53683
53684  if( pRoot->nCell==0 && !pRoot->leaf ){
53685    Pgno subpage;
53686    if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
53687    subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
53688    pCur->eState = CURSOR_VALID;
53689    rc = moveToChild(pCur, subpage);
53690  }else{
53691    pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
53692  }
53693  return rc;
53694}
53695
53696/*
53697** Move the cursor down to the left-most leaf entry beneath the
53698** entry to which it is currently pointing.
53699**
53700** The left-most leaf is the one with the smallest key - the first
53701** in ascending order.
53702*/
53703static int moveToLeftmost(BtCursor *pCur){
53704  Pgno pgno;
53705  int rc = SQLITE_OK;
53706  MemPage *pPage;
53707
53708  assert( cursorHoldsMutex(pCur) );
53709  assert( pCur->eState==CURSOR_VALID );
53710  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
53711    assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53712    pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
53713    rc = moveToChild(pCur, pgno);
53714  }
53715  return rc;
53716}
53717
53718/*
53719** Move the cursor down to the right-most leaf entry beneath the
53720** page to which it is currently pointing.  Notice the difference
53721** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
53722** finds the left-most entry beneath the *entry* whereas moveToRightmost()
53723** finds the right-most entry beneath the *page*.
53724**
53725** The right-most entry is the one with the largest key - the last
53726** key in ascending order.
53727*/
53728static int moveToRightmost(BtCursor *pCur){
53729  Pgno pgno;
53730  int rc = SQLITE_OK;
53731  MemPage *pPage = 0;
53732
53733  assert( cursorHoldsMutex(pCur) );
53734  assert( pCur->eState==CURSOR_VALID );
53735  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
53736    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
53737    pCur->aiIdx[pCur->iPage] = pPage->nCell;
53738    rc = moveToChild(pCur, pgno);
53739  }
53740  if( rc==SQLITE_OK ){
53741    pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
53742    pCur->info.nSize = 0;
53743    pCur->validNKey = 0;
53744  }
53745  return rc;
53746}
53747
53748/* Move the cursor to the first entry in the table.  Return SQLITE_OK
53749** on success.  Set *pRes to 0 if the cursor actually points to something
53750** or set *pRes to 1 if the table is empty.
53751*/
53752SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
53753  int rc;
53754
53755  assert( cursorHoldsMutex(pCur) );
53756  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53757  rc = moveToRoot(pCur);
53758  if( rc==SQLITE_OK ){
53759    if( pCur->eState==CURSOR_INVALID ){
53760      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53761      *pRes = 1;
53762    }else{
53763      assert( pCur->apPage[pCur->iPage]->nCell>0 );
53764      *pRes = 0;
53765      rc = moveToLeftmost(pCur);
53766    }
53767  }
53768  return rc;
53769}
53770
53771/* Move the cursor to the last entry in the table.  Return SQLITE_OK
53772** on success.  Set *pRes to 0 if the cursor actually points to something
53773** or set *pRes to 1 if the table is empty.
53774*/
53775SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
53776  int rc;
53777
53778  assert( cursorHoldsMutex(pCur) );
53779  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53780
53781  /* If the cursor already points to the last entry, this is a no-op. */
53782  if( CURSOR_VALID==pCur->eState && pCur->atLast ){
53783#ifdef SQLITE_DEBUG
53784    /* This block serves to assert() that the cursor really does point
53785    ** to the last entry in the b-tree. */
53786    int ii;
53787    for(ii=0; ii<pCur->iPage; ii++){
53788      assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
53789    }
53790    assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
53791    assert( pCur->apPage[pCur->iPage]->leaf );
53792#endif
53793    return SQLITE_OK;
53794  }
53795
53796  rc = moveToRoot(pCur);
53797  if( rc==SQLITE_OK ){
53798    if( CURSOR_INVALID==pCur->eState ){
53799      assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53800      *pRes = 1;
53801    }else{
53802      assert( pCur->eState==CURSOR_VALID );
53803      *pRes = 0;
53804      rc = moveToRightmost(pCur);
53805      pCur->atLast = rc==SQLITE_OK ?1:0;
53806    }
53807  }
53808  return rc;
53809}
53810
53811/* Move the cursor so that it points to an entry near the key
53812** specified by pIdxKey or intKey.   Return a success code.
53813**
53814** For INTKEY tables, the intKey parameter is used.  pIdxKey
53815** must be NULL.  For index tables, pIdxKey is used and intKey
53816** is ignored.
53817**
53818** If an exact match is not found, then the cursor is always
53819** left pointing at a leaf page which would hold the entry if it
53820** were present.  The cursor might point to an entry that comes
53821** before or after the key.
53822**
53823** An integer is written into *pRes which is the result of
53824** comparing the key with the entry to which the cursor is
53825** pointing.  The meaning of the integer written into
53826** *pRes is as follows:
53827**
53828**     *pRes<0      The cursor is left pointing at an entry that
53829**                  is smaller than intKey/pIdxKey or if the table is empty
53830**                  and the cursor is therefore left point to nothing.
53831**
53832**     *pRes==0     The cursor is left pointing at an entry that
53833**                  exactly matches intKey/pIdxKey.
53834**
53835**     *pRes>0      The cursor is left pointing at an entry that
53836**                  is larger than intKey/pIdxKey.
53837**
53838*/
53839SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
53840  BtCursor *pCur,          /* The cursor to be moved */
53841  UnpackedRecord *pIdxKey, /* Unpacked index key */
53842  i64 intKey,              /* The table key */
53843  int biasRight,           /* If true, bias the search to the high end */
53844  int *pRes                /* Write search results here */
53845){
53846  int rc;
53847
53848  assert( cursorHoldsMutex(pCur) );
53849  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53850  assert( pRes );
53851  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
53852
53853  /* If the cursor is already positioned at the point we are trying
53854  ** to move to, then just return without doing any work */
53855  if( pCur->eState==CURSOR_VALID && pCur->validNKey
53856   && pCur->apPage[0]->intKey
53857  ){
53858    if( pCur->info.nKey==intKey ){
53859      *pRes = 0;
53860      return SQLITE_OK;
53861    }
53862    if( pCur->atLast && pCur->info.nKey<intKey ){
53863      *pRes = -1;
53864      return SQLITE_OK;
53865    }
53866  }
53867
53868  rc = moveToRoot(pCur);
53869  if( rc ){
53870    return rc;
53871  }
53872  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
53873  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
53874  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
53875  if( pCur->eState==CURSOR_INVALID ){
53876    *pRes = -1;
53877    assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
53878    return SQLITE_OK;
53879  }
53880  assert( pCur->apPage[0]->intKey || pIdxKey );
53881  for(;;){
53882    int lwr, upr, idx;
53883    Pgno chldPg;
53884    MemPage *pPage = pCur->apPage[pCur->iPage];
53885    int c;
53886
53887    /* pPage->nCell must be greater than zero. If this is the root-page
53888    ** the cursor would have been INVALID above and this for(;;) loop
53889    ** not run. If this is not the root-page, then the moveToChild() routine
53890    ** would have already detected db corruption. Similarly, pPage must
53891    ** be the right kind (index or table) of b-tree page. Otherwise
53892    ** a moveToChild() or moveToRoot() call would have detected corruption.  */
53893    assert( pPage->nCell>0 );
53894    assert( pPage->intKey==(pIdxKey==0) );
53895    lwr = 0;
53896    upr = pPage->nCell-1;
53897    if( biasRight ){
53898      pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
53899    }else{
53900      pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
53901    }
53902    for(;;){
53903      u8 *pCell;                          /* Pointer to current cell in pPage */
53904
53905      assert( idx==pCur->aiIdx[pCur->iPage] );
53906      pCur->info.nSize = 0;
53907      pCell = findCell(pPage, idx) + pPage->childPtrSize;
53908      if( pPage->intKey ){
53909        i64 nCellKey;
53910        if( pPage->hasData ){
53911          u32 dummy;
53912          pCell += getVarint32(pCell, dummy);
53913        }
53914        getVarint(pCell, (u64*)&nCellKey);
53915        if( nCellKey==intKey ){
53916          c = 0;
53917        }else if( nCellKey<intKey ){
53918          c = -1;
53919        }else{
53920          assert( nCellKey>intKey );
53921          c = +1;
53922        }
53923        pCur->validNKey = 1;
53924        pCur->info.nKey = nCellKey;
53925      }else{
53926        /* The maximum supported page-size is 65536 bytes. This means that
53927        ** the maximum number of record bytes stored on an index B-Tree
53928        ** page is less than 16384 bytes and may be stored as a 2-byte
53929        ** varint. This information is used to attempt to avoid parsing
53930        ** the entire cell by checking for the cases where the record is
53931        ** stored entirely within the b-tree page by inspecting the first
53932        ** 2 bytes of the cell.
53933        */
53934        int nCell = pCell[0];
53935        if( nCell<=pPage->max1bytePayload
53936         /* && (pCell+nCell)<pPage->aDataEnd */
53937        ){
53938          /* This branch runs if the record-size field of the cell is a
53939          ** single byte varint and the record fits entirely on the main
53940          ** b-tree page.  */
53941          testcase( pCell+nCell+1==pPage->aDataEnd );
53942          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
53943        }else if( !(pCell[1] & 0x80)
53944          && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
53945          /* && (pCell+nCell+2)<=pPage->aDataEnd */
53946        ){
53947          /* The record-size field is a 2 byte varint and the record
53948          ** fits entirely on the main b-tree page.  */
53949          testcase( pCell+nCell+2==pPage->aDataEnd );
53950          c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
53951        }else{
53952          /* The record flows over onto one or more overflow pages. In
53953          ** this case the whole cell needs to be parsed, a buffer allocated
53954          ** and accessPayload() used to retrieve the record into the
53955          ** buffer before VdbeRecordCompare() can be called. */
53956          void *pCellKey;
53957          u8 * const pCellBody = pCell - pPage->childPtrSize;
53958          btreeParseCellPtr(pPage, pCellBody, &pCur->info);
53959          nCell = (int)pCur->info.nKey;
53960          pCellKey = sqlite3Malloc( nCell );
53961          if( pCellKey==0 ){
53962            rc = SQLITE_NOMEM;
53963            goto moveto_finish;
53964          }
53965          rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
53966          if( rc ){
53967            sqlite3_free(pCellKey);
53968            goto moveto_finish;
53969          }
53970          c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
53971          sqlite3_free(pCellKey);
53972        }
53973      }
53974      if( c==0 ){
53975        if( pPage->intKey && !pPage->leaf ){
53976          lwr = idx;
53977          break;
53978        }else{
53979          *pRes = 0;
53980          rc = SQLITE_OK;
53981          goto moveto_finish;
53982        }
53983      }
53984      if( c<0 ){
53985        lwr = idx+1;
53986      }else{
53987        upr = idx-1;
53988      }
53989      if( lwr>upr ){
53990        break;
53991      }
53992      pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
53993    }
53994    assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
53995    assert( pPage->isInit );
53996    if( pPage->leaf ){
53997      chldPg = 0;
53998    }else if( lwr>=pPage->nCell ){
53999      chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54000    }else{
54001      chldPg = get4byte(findCell(pPage, lwr));
54002    }
54003    if( chldPg==0 ){
54004      assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54005      *pRes = c;
54006      rc = SQLITE_OK;
54007      goto moveto_finish;
54008    }
54009    pCur->aiIdx[pCur->iPage] = (u16)lwr;
54010    pCur->info.nSize = 0;
54011    pCur->validNKey = 0;
54012    rc = moveToChild(pCur, chldPg);
54013    if( rc ) goto moveto_finish;
54014  }
54015moveto_finish:
54016  return rc;
54017}
54018
54019
54020/*
54021** Return TRUE if the cursor is not pointing at an entry of the table.
54022**
54023** TRUE will be returned after a call to sqlite3BtreeNext() moves
54024** past the last entry in the table or sqlite3BtreePrev() moves past
54025** the first entry.  TRUE is also returned if the table is empty.
54026*/
54027SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
54028  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
54029  ** have been deleted? This API will need to change to return an error code
54030  ** as well as the boolean result value.
54031  */
54032  return (CURSOR_VALID!=pCur->eState);
54033}
54034
54035/*
54036** Advance the cursor to the next entry in the database.  If
54037** successful then set *pRes=0.  If the cursor
54038** was already pointing to the last entry in the database before
54039** this routine was called, then set *pRes=1.
54040*/
54041SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
54042  int rc;
54043  int idx;
54044  MemPage *pPage;
54045
54046  assert( cursorHoldsMutex(pCur) );
54047  rc = restoreCursorPosition(pCur);
54048  if( rc!=SQLITE_OK ){
54049    return rc;
54050  }
54051  assert( pRes!=0 );
54052  if( CURSOR_INVALID==pCur->eState ){
54053    *pRes = 1;
54054    return SQLITE_OK;
54055  }
54056  if( pCur->skipNext>0 ){
54057    pCur->skipNext = 0;
54058    *pRes = 0;
54059    return SQLITE_OK;
54060  }
54061  pCur->skipNext = 0;
54062
54063  pPage = pCur->apPage[pCur->iPage];
54064  idx = ++pCur->aiIdx[pCur->iPage];
54065  assert( pPage->isInit );
54066
54067  /* If the database file is corrupt, it is possible for the value of idx
54068  ** to be invalid here. This can only occur if a second cursor modifies
54069  ** the page while cursor pCur is holding a reference to it. Which can
54070  ** only happen if the database is corrupt in such a way as to link the
54071  ** page into more than one b-tree structure. */
54072  testcase( idx>pPage->nCell );
54073
54074  pCur->info.nSize = 0;
54075  pCur->validNKey = 0;
54076  if( idx>=pPage->nCell ){
54077    if( !pPage->leaf ){
54078      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54079      if( rc ) return rc;
54080      rc = moveToLeftmost(pCur);
54081      *pRes = 0;
54082      return rc;
54083    }
54084    do{
54085      if( pCur->iPage==0 ){
54086        *pRes = 1;
54087        pCur->eState = CURSOR_INVALID;
54088        return SQLITE_OK;
54089      }
54090      moveToParent(pCur);
54091      pPage = pCur->apPage[pCur->iPage];
54092    }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
54093    *pRes = 0;
54094    if( pPage->intKey ){
54095      rc = sqlite3BtreeNext(pCur, pRes);
54096    }else{
54097      rc = SQLITE_OK;
54098    }
54099    return rc;
54100  }
54101  *pRes = 0;
54102  if( pPage->leaf ){
54103    return SQLITE_OK;
54104  }
54105  rc = moveToLeftmost(pCur);
54106  return rc;
54107}
54108
54109
54110/*
54111** Step the cursor to the back to the previous entry in the database.  If
54112** successful then set *pRes=0.  If the cursor
54113** was already pointing to the first entry in the database before
54114** this routine was called, then set *pRes=1.
54115*/
54116SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
54117  int rc;
54118  MemPage *pPage;
54119
54120  assert( cursorHoldsMutex(pCur) );
54121  rc = restoreCursorPosition(pCur);
54122  if( rc!=SQLITE_OK ){
54123    return rc;
54124  }
54125  pCur->atLast = 0;
54126  if( CURSOR_INVALID==pCur->eState ){
54127    *pRes = 1;
54128    return SQLITE_OK;
54129  }
54130  if( pCur->skipNext<0 ){
54131    pCur->skipNext = 0;
54132    *pRes = 0;
54133    return SQLITE_OK;
54134  }
54135  pCur->skipNext = 0;
54136
54137  pPage = pCur->apPage[pCur->iPage];
54138  assert( pPage->isInit );
54139  if( !pPage->leaf ){
54140    int idx = pCur->aiIdx[pCur->iPage];
54141    rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
54142    if( rc ){
54143      return rc;
54144    }
54145    rc = moveToRightmost(pCur);
54146  }else{
54147    while( pCur->aiIdx[pCur->iPage]==0 ){
54148      if( pCur->iPage==0 ){
54149        pCur->eState = CURSOR_INVALID;
54150        *pRes = 1;
54151        return SQLITE_OK;
54152      }
54153      moveToParent(pCur);
54154    }
54155    pCur->info.nSize = 0;
54156    pCur->validNKey = 0;
54157
54158    pCur->aiIdx[pCur->iPage]--;
54159    pPage = pCur->apPage[pCur->iPage];
54160    if( pPage->intKey && !pPage->leaf ){
54161      rc = sqlite3BtreePrevious(pCur, pRes);
54162    }else{
54163      rc = SQLITE_OK;
54164    }
54165  }
54166  *pRes = 0;
54167  return rc;
54168}
54169
54170/*
54171** Allocate a new page from the database file.
54172**
54173** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
54174** has already been called on the new page.)  The new page has also
54175** been referenced and the calling routine is responsible for calling
54176** sqlite3PagerUnref() on the new page when it is done.
54177**
54178** SQLITE_OK is returned on success.  Any other return value indicates
54179** an error.  *ppPage and *pPgno are undefined in the event of an error.
54180** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
54181**
54182** If the "nearby" parameter is not 0, then a (feeble) effort is made to
54183** locate a page close to the page number "nearby".  This can be used in an
54184** attempt to keep related pages close to each other in the database file,
54185** which in turn can make database access faster.
54186**
54187** If the "exact" parameter is not 0, and the page-number nearby exists
54188** anywhere on the free-list, then it is guarenteed to be returned. This
54189** is only used by auto-vacuum databases when allocating a new table.
54190*/
54191static int allocateBtreePage(
54192  BtShared *pBt,
54193  MemPage **ppPage,
54194  Pgno *pPgno,
54195  Pgno nearby,
54196  u8 exact
54197){
54198  MemPage *pPage1;
54199  int rc;
54200  u32 n;     /* Number of pages on the freelist */
54201  u32 k;     /* Number of leaves on the trunk of the freelist */
54202  MemPage *pTrunk = 0;
54203  MemPage *pPrevTrunk = 0;
54204  Pgno mxPage;     /* Total size of the database file */
54205
54206  assert( sqlite3_mutex_held(pBt->mutex) );
54207  pPage1 = pBt->pPage1;
54208  mxPage = btreePagecount(pBt);
54209  n = get4byte(&pPage1->aData[36]);
54210  testcase( n==mxPage-1 );
54211  if( n>=mxPage ){
54212    return SQLITE_CORRUPT_BKPT;
54213  }
54214  if( n>0 ){
54215    /* There are pages on the freelist.  Reuse one of those pages. */
54216    Pgno iTrunk;
54217    u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
54218
54219    /* If the 'exact' parameter was true and a query of the pointer-map
54220    ** shows that the page 'nearby' is somewhere on the free-list, then
54221    ** the entire-list will be searched for that page.
54222    */
54223#ifndef SQLITE_OMIT_AUTOVACUUM
54224    if( exact && nearby<=mxPage ){
54225      u8 eType;
54226      assert( nearby>0 );
54227      assert( pBt->autoVacuum );
54228      rc = ptrmapGet(pBt, nearby, &eType, 0);
54229      if( rc ) return rc;
54230      if( eType==PTRMAP_FREEPAGE ){
54231        searchList = 1;
54232      }
54233      *pPgno = nearby;
54234    }
54235#endif
54236
54237    /* Decrement the free-list count by 1. Set iTrunk to the index of the
54238    ** first free-list trunk page. iPrevTrunk is initially 1.
54239    */
54240    rc = sqlite3PagerWrite(pPage1->pDbPage);
54241    if( rc ) return rc;
54242    put4byte(&pPage1->aData[36], n-1);
54243
54244    /* The code within this loop is run only once if the 'searchList' variable
54245    ** is not true. Otherwise, it runs once for each trunk-page on the
54246    ** free-list until the page 'nearby' is located.
54247    */
54248    do {
54249      pPrevTrunk = pTrunk;
54250      if( pPrevTrunk ){
54251        iTrunk = get4byte(&pPrevTrunk->aData[0]);
54252      }else{
54253        iTrunk = get4byte(&pPage1->aData[32]);
54254      }
54255      testcase( iTrunk==mxPage );
54256      if( iTrunk>mxPage ){
54257        rc = SQLITE_CORRUPT_BKPT;
54258      }else{
54259        rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54260      }
54261      if( rc ){
54262        pTrunk = 0;
54263        goto end_allocate_page;
54264      }
54265      assert( pTrunk!=0 );
54266      assert( pTrunk->aData!=0 );
54267
54268      k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
54269      if( k==0 && !searchList ){
54270        /* The trunk has no leaves and the list is not being searched.
54271        ** So extract the trunk page itself and use it as the newly
54272        ** allocated page */
54273        assert( pPrevTrunk==0 );
54274        rc = sqlite3PagerWrite(pTrunk->pDbPage);
54275        if( rc ){
54276          goto end_allocate_page;
54277        }
54278        *pPgno = iTrunk;
54279        memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54280        *ppPage = pTrunk;
54281        pTrunk = 0;
54282        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54283      }else if( k>(u32)(pBt->usableSize/4 - 2) ){
54284        /* Value of k is out of range.  Database corruption */
54285        rc = SQLITE_CORRUPT_BKPT;
54286        goto end_allocate_page;
54287#ifndef SQLITE_OMIT_AUTOVACUUM
54288      }else if( searchList && nearby==iTrunk ){
54289        /* The list is being searched and this trunk page is the page
54290        ** to allocate, regardless of whether it has leaves.
54291        */
54292        assert( *pPgno==iTrunk );
54293        *ppPage = pTrunk;
54294        searchList = 0;
54295        rc = sqlite3PagerWrite(pTrunk->pDbPage);
54296        if( rc ){
54297          goto end_allocate_page;
54298        }
54299        if( k==0 ){
54300          if( !pPrevTrunk ){
54301            memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54302          }else{
54303            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54304            if( rc!=SQLITE_OK ){
54305              goto end_allocate_page;
54306            }
54307            memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
54308          }
54309        }else{
54310          /* The trunk page is required by the caller but it contains
54311          ** pointers to free-list leaves. The first leaf becomes a trunk
54312          ** page in this case.
54313          */
54314          MemPage *pNewTrunk;
54315          Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
54316          if( iNewTrunk>mxPage ){
54317            rc = SQLITE_CORRUPT_BKPT;
54318            goto end_allocate_page;
54319          }
54320          testcase( iNewTrunk==mxPage );
54321          rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
54322          if( rc!=SQLITE_OK ){
54323            goto end_allocate_page;
54324          }
54325          rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
54326          if( rc!=SQLITE_OK ){
54327            releasePage(pNewTrunk);
54328            goto end_allocate_page;
54329          }
54330          memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
54331          put4byte(&pNewTrunk->aData[4], k-1);
54332          memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
54333          releasePage(pNewTrunk);
54334          if( !pPrevTrunk ){
54335            assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
54336            put4byte(&pPage1->aData[32], iNewTrunk);
54337          }else{
54338            rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54339            if( rc ){
54340              goto end_allocate_page;
54341            }
54342            put4byte(&pPrevTrunk->aData[0], iNewTrunk);
54343          }
54344        }
54345        pTrunk = 0;
54346        TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54347#endif
54348      }else if( k>0 ){
54349        /* Extract a leaf from the trunk */
54350        u32 closest;
54351        Pgno iPage;
54352        unsigned char *aData = pTrunk->aData;
54353        if( nearby>0 ){
54354          u32 i;
54355          int dist;
54356          closest = 0;
54357          dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
54358          for(i=1; i<k; i++){
54359            int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
54360            if( d2<dist ){
54361              closest = i;
54362              dist = d2;
54363            }
54364          }
54365        }else{
54366          closest = 0;
54367        }
54368
54369        iPage = get4byte(&aData[8+closest*4]);
54370        testcase( iPage==mxPage );
54371        if( iPage>mxPage ){
54372          rc = SQLITE_CORRUPT_BKPT;
54373          goto end_allocate_page;
54374        }
54375        testcase( iPage==mxPage );
54376        if( !searchList || iPage==nearby ){
54377          int noContent;
54378          *pPgno = iPage;
54379          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
54380                 ": %d more free pages\n",
54381                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
54382          rc = sqlite3PagerWrite(pTrunk->pDbPage);
54383          if( rc ) goto end_allocate_page;
54384          if( closest<k-1 ){
54385            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
54386          }
54387          put4byte(&aData[4], k-1);
54388          noContent = !btreeGetHasContent(pBt, *pPgno);
54389          rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
54390          if( rc==SQLITE_OK ){
54391            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54392            if( rc!=SQLITE_OK ){
54393              releasePage(*ppPage);
54394            }
54395          }
54396          searchList = 0;
54397        }
54398      }
54399      releasePage(pPrevTrunk);
54400      pPrevTrunk = 0;
54401    }while( searchList );
54402  }else{
54403    /* There are no pages on the freelist, so create a new page at the
54404    ** end of the file */
54405    rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54406    if( rc ) return rc;
54407    pBt->nPage++;
54408    if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
54409
54410#ifndef SQLITE_OMIT_AUTOVACUUM
54411    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
54412      /* If *pPgno refers to a pointer-map page, allocate two new pages
54413      ** at the end of the file instead of one. The first allocated page
54414      ** becomes a new pointer-map page, the second is used by the caller.
54415      */
54416      MemPage *pPg = 0;
54417      TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
54418      assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
54419      rc = btreeGetPage(pBt, pBt->nPage, &pPg, 1);
54420      if( rc==SQLITE_OK ){
54421        rc = sqlite3PagerWrite(pPg->pDbPage);
54422        releasePage(pPg);
54423      }
54424      if( rc ) return rc;
54425      pBt->nPage++;
54426      if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
54427    }
54428#endif
54429    put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
54430    *pPgno = pBt->nPage;
54431
54432    assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54433    rc = btreeGetPage(pBt, *pPgno, ppPage, 1);
54434    if( rc ) return rc;
54435    rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54436    if( rc!=SQLITE_OK ){
54437      releasePage(*ppPage);
54438    }
54439    TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
54440  }
54441
54442  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54443
54444end_allocate_page:
54445  releasePage(pTrunk);
54446  releasePage(pPrevTrunk);
54447  if( rc==SQLITE_OK ){
54448    if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
54449      releasePage(*ppPage);
54450      return SQLITE_CORRUPT_BKPT;
54451    }
54452    (*ppPage)->isInit = 0;
54453  }else{
54454    *ppPage = 0;
54455  }
54456  assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
54457  return rc;
54458}
54459
54460/*
54461** This function is used to add page iPage to the database file free-list.
54462** It is assumed that the page is not already a part of the free-list.
54463**
54464** The value passed as the second argument to this function is optional.
54465** If the caller happens to have a pointer to the MemPage object
54466** corresponding to page iPage handy, it may pass it as the second value.
54467** Otherwise, it may pass NULL.
54468**
54469** If a pointer to a MemPage object is passed as the second argument,
54470** its reference count is not altered by this function.
54471*/
54472static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
54473  MemPage *pTrunk = 0;                /* Free-list trunk page */
54474  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */
54475  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
54476  MemPage *pPage;                     /* Page being freed. May be NULL. */
54477  int rc;                             /* Return Code */
54478  int nFree;                          /* Initial number of pages on free-list */
54479
54480  assert( sqlite3_mutex_held(pBt->mutex) );
54481  assert( iPage>1 );
54482  assert( !pMemPage || pMemPage->pgno==iPage );
54483
54484  if( pMemPage ){
54485    pPage = pMemPage;
54486    sqlite3PagerRef(pPage->pDbPage);
54487  }else{
54488    pPage = btreePageLookup(pBt, iPage);
54489  }
54490
54491  /* Increment the free page count on pPage1 */
54492  rc = sqlite3PagerWrite(pPage1->pDbPage);
54493  if( rc ) goto freepage_out;
54494  nFree = get4byte(&pPage1->aData[36]);
54495  put4byte(&pPage1->aData[36], nFree+1);
54496
54497  if( pBt->btsFlags & BTS_SECURE_DELETE ){
54498    /* If the secure_delete option is enabled, then
54499    ** always fully overwrite deleted information with zeros.
54500    */
54501    if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
54502     ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
54503    ){
54504      goto freepage_out;
54505    }
54506    memset(pPage->aData, 0, pPage->pBt->pageSize);
54507  }
54508
54509  /* If the database supports auto-vacuum, write an entry in the pointer-map
54510  ** to indicate that the page is free.
54511  */
54512  if( ISAUTOVACUUM ){
54513    ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
54514    if( rc ) goto freepage_out;
54515  }
54516
54517  /* Now manipulate the actual database free-list structure. There are two
54518  ** possibilities. If the free-list is currently empty, or if the first
54519  ** trunk page in the free-list is full, then this page will become a
54520  ** new free-list trunk page. Otherwise, it will become a leaf of the
54521  ** first trunk page in the current free-list. This block tests if it
54522  ** is possible to add the page as a new free-list leaf.
54523  */
54524  if( nFree!=0 ){
54525    u32 nLeaf;                /* Initial number of leaf cells on trunk page */
54526
54527    iTrunk = get4byte(&pPage1->aData[32]);
54528    rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
54529    if( rc!=SQLITE_OK ){
54530      goto freepage_out;
54531    }
54532
54533    nLeaf = get4byte(&pTrunk->aData[4]);
54534    assert( pBt->usableSize>32 );
54535    if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
54536      rc = SQLITE_CORRUPT_BKPT;
54537      goto freepage_out;
54538    }
54539    if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
54540      /* In this case there is room on the trunk page to insert the page
54541      ** being freed as a new leaf.
54542      **
54543      ** Note that the trunk page is not really full until it contains
54544      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
54545      ** coded.  But due to a coding error in versions of SQLite prior to
54546      ** 3.6.0, databases with freelist trunk pages holding more than
54547      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
54548      ** to maintain backwards compatibility with older versions of SQLite,
54549      ** we will continue to restrict the number of entries to usableSize/4 - 8
54550      ** for now.  At some point in the future (once everyone has upgraded
54551      ** to 3.6.0 or later) we should consider fixing the conditional above
54552      ** to read "usableSize/4-2" instead of "usableSize/4-8".
54553      */
54554      rc = sqlite3PagerWrite(pTrunk->pDbPage);
54555      if( rc==SQLITE_OK ){
54556        put4byte(&pTrunk->aData[4], nLeaf+1);
54557        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
54558        if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
54559          sqlite3PagerDontWrite(pPage->pDbPage);
54560        }
54561        rc = btreeSetHasContent(pBt, iPage);
54562      }
54563      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
54564      goto freepage_out;
54565    }
54566  }
54567
54568  /* If control flows to this point, then it was not possible to add the
54569  ** the page being freed as a leaf page of the first trunk in the free-list.
54570  ** Possibly because the free-list is empty, or possibly because the
54571  ** first trunk in the free-list is full. Either way, the page being freed
54572  ** will become the new first trunk page in the free-list.
54573  */
54574  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
54575    goto freepage_out;
54576  }
54577  rc = sqlite3PagerWrite(pPage->pDbPage);
54578  if( rc!=SQLITE_OK ){
54579    goto freepage_out;
54580  }
54581  put4byte(pPage->aData, iTrunk);
54582  put4byte(&pPage->aData[4], 0);
54583  put4byte(&pPage1->aData[32], iPage);
54584  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
54585
54586freepage_out:
54587  if( pPage ){
54588    pPage->isInit = 0;
54589  }
54590  releasePage(pPage);
54591  releasePage(pTrunk);
54592  return rc;
54593}
54594static void freePage(MemPage *pPage, int *pRC){
54595  if( (*pRC)==SQLITE_OK ){
54596    *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
54597  }
54598}
54599
54600/*
54601** Free any overflow pages associated with the given Cell.
54602*/
54603static int clearCell(MemPage *pPage, unsigned char *pCell){
54604  BtShared *pBt = pPage->pBt;
54605  CellInfo info;
54606  Pgno ovflPgno;
54607  int rc;
54608  int nOvfl;
54609  u32 ovflPageSize;
54610
54611  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54612  btreeParseCellPtr(pPage, pCell, &info);
54613  if( info.iOverflow==0 ){
54614    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
54615  }
54616  if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
54617    return SQLITE_CORRUPT;  /* Cell extends past end of page */
54618  }
54619  ovflPgno = get4byte(&pCell[info.iOverflow]);
54620  assert( pBt->usableSize > 4 );
54621  ovflPageSize = pBt->usableSize - 4;
54622  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
54623  assert( ovflPgno==0 || nOvfl>0 );
54624  while( nOvfl-- ){
54625    Pgno iNext = 0;
54626    MemPage *pOvfl = 0;
54627    if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
54628      /* 0 is not a legal page number and page 1 cannot be an
54629      ** overflow page. Therefore if ovflPgno<2 or past the end of the
54630      ** file the database must be corrupt. */
54631      return SQLITE_CORRUPT_BKPT;
54632    }
54633    if( nOvfl ){
54634      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
54635      if( rc ) return rc;
54636    }
54637
54638    if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
54639     && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
54640    ){
54641      /* There is no reason any cursor should have an outstanding reference
54642      ** to an overflow page belonging to a cell that is being deleted/updated.
54643      ** So if there exists more than one reference to this page, then it
54644      ** must not really be an overflow page and the database must be corrupt.
54645      ** It is helpful to detect this before calling freePage2(), as
54646      ** freePage2() may zero the page contents if secure-delete mode is
54647      ** enabled. If this 'overflow' page happens to be a page that the
54648      ** caller is iterating through or using in some other way, this
54649      ** can be problematic.
54650      */
54651      rc = SQLITE_CORRUPT_BKPT;
54652    }else{
54653      rc = freePage2(pBt, pOvfl, ovflPgno);
54654    }
54655
54656    if( pOvfl ){
54657      sqlite3PagerUnref(pOvfl->pDbPage);
54658    }
54659    if( rc ) return rc;
54660    ovflPgno = iNext;
54661  }
54662  return SQLITE_OK;
54663}
54664
54665/*
54666** Create the byte sequence used to represent a cell on page pPage
54667** and write that byte sequence into pCell[].  Overflow pages are
54668** allocated and filled in as necessary.  The calling procedure
54669** is responsible for making sure sufficient space has been allocated
54670** for pCell[].
54671**
54672** Note that pCell does not necessary need to point to the pPage->aData
54673** area.  pCell might point to some temporary storage.  The cell will
54674** be constructed in this temporary area then copied into pPage->aData
54675** later.
54676*/
54677static int fillInCell(
54678  MemPage *pPage,                /* The page that contains the cell */
54679  unsigned char *pCell,          /* Complete text of the cell */
54680  const void *pKey, i64 nKey,    /* The key */
54681  const void *pData,int nData,   /* The data */
54682  int nZero,                     /* Extra zero bytes to append to pData */
54683  int *pnSize                    /* Write cell size here */
54684){
54685  int nPayload;
54686  const u8 *pSrc;
54687  int nSrc, n, rc;
54688  int spaceLeft;
54689  MemPage *pOvfl = 0;
54690  MemPage *pToRelease = 0;
54691  unsigned char *pPrior;
54692  unsigned char *pPayload;
54693  BtShared *pBt = pPage->pBt;
54694  Pgno pgnoOvfl = 0;
54695  int nHeader;
54696  CellInfo info;
54697
54698  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54699
54700  /* pPage is not necessarily writeable since pCell might be auxiliary
54701  ** buffer space that is separate from the pPage buffer area */
54702  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
54703            || sqlite3PagerIswriteable(pPage->pDbPage) );
54704
54705  /* Fill in the header. */
54706  nHeader = 0;
54707  if( !pPage->leaf ){
54708    nHeader += 4;
54709  }
54710  if( pPage->hasData ){
54711    nHeader += putVarint(&pCell[nHeader], nData+nZero);
54712  }else{
54713    nData = nZero = 0;
54714  }
54715  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
54716  btreeParseCellPtr(pPage, pCell, &info);
54717  assert( info.nHeader==nHeader );
54718  assert( info.nKey==nKey );
54719  assert( info.nData==(u32)(nData+nZero) );
54720
54721  /* Fill in the payload */
54722  nPayload = nData + nZero;
54723  if( pPage->intKey ){
54724    pSrc = pData;
54725    nSrc = nData;
54726    nData = 0;
54727  }else{
54728    if( NEVER(nKey>0x7fffffff || pKey==0) ){
54729      return SQLITE_CORRUPT_BKPT;
54730    }
54731    nPayload += (int)nKey;
54732    pSrc = pKey;
54733    nSrc = (int)nKey;
54734  }
54735  *pnSize = info.nSize;
54736  spaceLeft = info.nLocal;
54737  pPayload = &pCell[nHeader];
54738  pPrior = &pCell[info.iOverflow];
54739
54740  while( nPayload>0 ){
54741    if( spaceLeft==0 ){
54742#ifndef SQLITE_OMIT_AUTOVACUUM
54743      Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
54744      if( pBt->autoVacuum ){
54745        do{
54746          pgnoOvfl++;
54747        } while(
54748          PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
54749        );
54750      }
54751#endif
54752      rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
54753#ifndef SQLITE_OMIT_AUTOVACUUM
54754      /* If the database supports auto-vacuum, and the second or subsequent
54755      ** overflow page is being allocated, add an entry to the pointer-map
54756      ** for that page now.
54757      **
54758      ** If this is the first overflow page, then write a partial entry
54759      ** to the pointer-map. If we write nothing to this pointer-map slot,
54760      ** then the optimistic overflow chain processing in clearCell()
54761      ** may misinterpret the uninitialised values and delete the
54762      ** wrong pages from the database.
54763      */
54764      if( pBt->autoVacuum && rc==SQLITE_OK ){
54765        u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
54766        ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
54767        if( rc ){
54768          releasePage(pOvfl);
54769        }
54770      }
54771#endif
54772      if( rc ){
54773        releasePage(pToRelease);
54774        return rc;
54775      }
54776
54777      /* If pToRelease is not zero than pPrior points into the data area
54778      ** of pToRelease.  Make sure pToRelease is still writeable. */
54779      assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
54780
54781      /* If pPrior is part of the data area of pPage, then make sure pPage
54782      ** is still writeable */
54783      assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
54784            || sqlite3PagerIswriteable(pPage->pDbPage) );
54785
54786      put4byte(pPrior, pgnoOvfl);
54787      releasePage(pToRelease);
54788      pToRelease = pOvfl;
54789      pPrior = pOvfl->aData;
54790      put4byte(pPrior, 0);
54791      pPayload = &pOvfl->aData[4];
54792      spaceLeft = pBt->usableSize - 4;
54793    }
54794    n = nPayload;
54795    if( n>spaceLeft ) n = spaceLeft;
54796
54797    /* If pToRelease is not zero than pPayload points into the data area
54798    ** of pToRelease.  Make sure pToRelease is still writeable. */
54799    assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
54800
54801    /* If pPayload is part of the data area of pPage, then make sure pPage
54802    ** is still writeable */
54803    assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
54804            || sqlite3PagerIswriteable(pPage->pDbPage) );
54805
54806    if( nSrc>0 ){
54807      if( n>nSrc ) n = nSrc;
54808      assert( pSrc );
54809      memcpy(pPayload, pSrc, n);
54810    }else{
54811      memset(pPayload, 0, n);
54812    }
54813    nPayload -= n;
54814    pPayload += n;
54815    pSrc += n;
54816    nSrc -= n;
54817    spaceLeft -= n;
54818    if( nSrc==0 ){
54819      nSrc = nData;
54820      pSrc = pData;
54821    }
54822  }
54823  releasePage(pToRelease);
54824  return SQLITE_OK;
54825}
54826
54827/*
54828** Remove the i-th cell from pPage.  This routine effects pPage only.
54829** The cell content is not freed or deallocated.  It is assumed that
54830** the cell content has been copied someplace else.  This routine just
54831** removes the reference to the cell from pPage.
54832**
54833** "sz" must be the number of bytes in the cell.
54834*/
54835static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
54836  u32 pc;         /* Offset to cell content of cell being deleted */
54837  u8 *data;       /* pPage->aData */
54838  u8 *ptr;        /* Used to move bytes around within data[] */
54839  u8 *endPtr;     /* End of loop */
54840  int rc;         /* The return code */
54841  int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
54842
54843  if( *pRC ) return;
54844
54845  assert( idx>=0 && idx<pPage->nCell );
54846  assert( sz==cellSize(pPage, idx) );
54847  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54848  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54849  data = pPage->aData;
54850  ptr = &pPage->aCellIdx[2*idx];
54851  pc = get2byte(ptr);
54852  hdr = pPage->hdrOffset;
54853  testcase( pc==get2byte(&data[hdr+5]) );
54854  testcase( pc+sz==pPage->pBt->usableSize );
54855  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
54856    *pRC = SQLITE_CORRUPT_BKPT;
54857    return;
54858  }
54859  rc = freeSpace(pPage, pc, sz);
54860  if( rc ){
54861    *pRC = rc;
54862    return;
54863  }
54864  endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
54865  assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54866  while( ptr<endPtr ){
54867    *(u16*)ptr = *(u16*)&ptr[2];
54868    ptr += 2;
54869  }
54870  pPage->nCell--;
54871  put2byte(&data[hdr+3], pPage->nCell);
54872  pPage->nFree += 2;
54873}
54874
54875/*
54876** Insert a new cell on pPage at cell index "i".  pCell points to the
54877** content of the cell.
54878**
54879** If the cell content will fit on the page, then put it there.  If it
54880** will not fit, then make a copy of the cell content into pTemp if
54881** pTemp is not null.  Regardless of pTemp, allocate a new entry
54882** in pPage->apOvfl[] and make it point to the cell content (either
54883** in pTemp or the original pCell) and also record its index.
54884** Allocating a new entry in pPage->aCell[] implies that
54885** pPage->nOverflow is incremented.
54886**
54887** If nSkip is non-zero, then do not copy the first nSkip bytes of the
54888** cell. The caller will overwrite them after this function returns. If
54889** nSkip is non-zero, then pCell may not point to an invalid memory location
54890** (but pCell+nSkip is always valid).
54891*/
54892static void insertCell(
54893  MemPage *pPage,   /* Page into which we are copying */
54894  int i,            /* New cell becomes the i-th cell of the page */
54895  u8 *pCell,        /* Content of the new cell */
54896  int sz,           /* Bytes of content in pCell */
54897  u8 *pTemp,        /* Temp storage space for pCell, if needed */
54898  Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
54899  int *pRC          /* Read and write return code from here */
54900){
54901  int idx = 0;      /* Where to write new cell content in data[] */
54902  int j;            /* Loop counter */
54903  int end;          /* First byte past the last cell pointer in data[] */
54904  int ins;          /* Index in data[] where new cell pointer is inserted */
54905  int cellOffset;   /* Address of first cell pointer in data[] */
54906  u8 *data;         /* The content of the whole page */
54907  u8 *ptr;          /* Used for moving information around in data[] */
54908  u8 *endPtr;       /* End of the loop */
54909
54910  int nSkip = (iChild ? 4 : 0);
54911
54912  if( *pRC ) return;
54913
54914  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
54915  assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
54916  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
54917  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
54918  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54919  /* The cell should normally be sized correctly.  However, when moving a
54920  ** malformed cell from a leaf page to an interior page, if the cell size
54921  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
54922  ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
54923  ** the term after the || in the following assert(). */
54924  assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
54925  if( pPage->nOverflow || sz+2>pPage->nFree ){
54926    if( pTemp ){
54927      memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
54928      pCell = pTemp;
54929    }
54930    if( iChild ){
54931      put4byte(pCell, iChild);
54932    }
54933    j = pPage->nOverflow++;
54934    assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
54935    pPage->apOvfl[j] = pCell;
54936    pPage->aiOvfl[j] = (u16)i;
54937  }else{
54938    int rc = sqlite3PagerWrite(pPage->pDbPage);
54939    if( rc!=SQLITE_OK ){
54940      *pRC = rc;
54941      return;
54942    }
54943    assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54944    data = pPage->aData;
54945    cellOffset = pPage->cellOffset;
54946    end = cellOffset + 2*pPage->nCell;
54947    ins = cellOffset + 2*i;
54948    rc = allocateSpace(pPage, sz, &idx);
54949    if( rc ){ *pRC = rc; return; }
54950    /* The allocateSpace() routine guarantees the following two properties
54951    ** if it returns success */
54952    assert( idx >= end+2 );
54953    assert( idx+sz <= (int)pPage->pBt->usableSize );
54954    pPage->nCell++;
54955    pPage->nFree -= (u16)(2 + sz);
54956    memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
54957    if( iChild ){
54958      put4byte(&data[idx], iChild);
54959    }
54960    ptr = &data[end];
54961    endPtr = &data[ins];
54962    assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
54963    while( ptr>endPtr ){
54964      *(u16*)ptr = *(u16*)&ptr[-2];
54965      ptr -= 2;
54966    }
54967    put2byte(&data[ins], idx);
54968    put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
54969#ifndef SQLITE_OMIT_AUTOVACUUM
54970    if( pPage->pBt->autoVacuum ){
54971      /* The cell may contain a pointer to an overflow page. If so, write
54972      ** the entry for the overflow page into the pointer map.
54973      */
54974      ptrmapPutOvflPtr(pPage, pCell, pRC);
54975    }
54976#endif
54977  }
54978}
54979
54980/*
54981** Add a list of cells to a page.  The page should be initially empty.
54982** The cells are guaranteed to fit on the page.
54983*/
54984static void assemblePage(
54985  MemPage *pPage,   /* The page to be assemblied */
54986  int nCell,        /* The number of cells to add to this page */
54987  u8 **apCell,      /* Pointers to cell bodies */
54988  u16 *aSize        /* Sizes of the cells */
54989){
54990  int i;            /* Loop counter */
54991  u8 *pCellptr;     /* Address of next cell pointer */
54992  int cellbody;     /* Address of next cell body */
54993  u8 * const data = pPage->aData;             /* Pointer to data for pPage */
54994  const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
54995  const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
54996
54997  assert( pPage->nOverflow==0 );
54998  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54999  assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
55000            && (int)MX_CELL(pPage->pBt)<=10921);
55001  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55002
55003  /* Check that the page has just been zeroed by zeroPage() */
55004  assert( pPage->nCell==0 );
55005  assert( get2byteNotZero(&data[hdr+5])==nUsable );
55006
55007  pCellptr = &pPage->aCellIdx[nCell*2];
55008  cellbody = nUsable;
55009  for(i=nCell-1; i>=0; i--){
55010    u16 sz = aSize[i];
55011    pCellptr -= 2;
55012    cellbody -= sz;
55013    put2byte(pCellptr, cellbody);
55014    memcpy(&data[cellbody], apCell[i], sz);
55015  }
55016  put2byte(&data[hdr+3], nCell);
55017  put2byte(&data[hdr+5], cellbody);
55018  pPage->nFree -= (nCell*2 + nUsable - cellbody);
55019  pPage->nCell = (u16)nCell;
55020}
55021
55022/*
55023** The following parameters determine how many adjacent pages get involved
55024** in a balancing operation.  NN is the number of neighbors on either side
55025** of the page that participate in the balancing operation.  NB is the
55026** total number of pages that participate, including the target page and
55027** NN neighbors on either side.
55028**
55029** The minimum value of NN is 1 (of course).  Increasing NN above 1
55030** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
55031** in exchange for a larger degradation in INSERT and UPDATE performance.
55032** The value of NN appears to give the best results overall.
55033*/
55034#define NN 1             /* Number of neighbors on either side of pPage */
55035#define NB (NN*2+1)      /* Total pages involved in the balance */
55036
55037
55038#ifndef SQLITE_OMIT_QUICKBALANCE
55039/*
55040** This version of balance() handles the common special case where
55041** a new entry is being inserted on the extreme right-end of the
55042** tree, in other words, when the new entry will become the largest
55043** entry in the tree.
55044**
55045** Instead of trying to balance the 3 right-most leaf pages, just add
55046** a new page to the right-hand side and put the one new entry in
55047** that page.  This leaves the right side of the tree somewhat
55048** unbalanced.  But odds are that we will be inserting new entries
55049** at the end soon afterwards so the nearly empty page will quickly
55050** fill up.  On average.
55051**
55052** pPage is the leaf page which is the right-most page in the tree.
55053** pParent is its parent.  pPage must have a single overflow entry
55054** which is also the right-most entry on the page.
55055**
55056** The pSpace buffer is used to store a temporary copy of the divider
55057** cell that will be inserted into pParent. Such a cell consists of a 4
55058** byte page number followed by a variable length integer. In other
55059** words, at most 13 bytes. Hence the pSpace buffer must be at
55060** least 13 bytes in size.
55061*/
55062static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
55063  BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
55064  MemPage *pNew;                       /* Newly allocated page */
55065  int rc;                              /* Return Code */
55066  Pgno pgnoNew;                        /* Page number of pNew */
55067
55068  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55069  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55070  assert( pPage->nOverflow==1 );
55071
55072  /* This error condition is now caught prior to reaching this function */
55073  if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
55074
55075  /* Allocate a new page. This page will become the right-sibling of
55076  ** pPage. Make the parent page writable, so that the new divider cell
55077  ** may be inserted. If both these operations are successful, proceed.
55078  */
55079  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
55080
55081  if( rc==SQLITE_OK ){
55082
55083    u8 *pOut = &pSpace[4];
55084    u8 *pCell = pPage->apOvfl[0];
55085    u16 szCell = cellSizePtr(pPage, pCell);
55086    u8 *pStop;
55087
55088    assert( sqlite3PagerIswriteable(pNew->pDbPage) );
55089    assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
55090    zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
55091    assemblePage(pNew, 1, &pCell, &szCell);
55092
55093    /* If this is an auto-vacuum database, update the pointer map
55094    ** with entries for the new page, and any pointer from the
55095    ** cell on the page to an overflow page. If either of these
55096    ** operations fails, the return code is set, but the contents
55097    ** of the parent page are still manipulated by thh code below.
55098    ** That is Ok, at this point the parent page is guaranteed to
55099    ** be marked as dirty. Returning an error code will cause a
55100    ** rollback, undoing any changes made to the parent page.
55101    */
55102    if( ISAUTOVACUUM ){
55103      ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
55104      if( szCell>pNew->minLocal ){
55105        ptrmapPutOvflPtr(pNew, pCell, &rc);
55106      }
55107    }
55108
55109    /* Create a divider cell to insert into pParent. The divider cell
55110    ** consists of a 4-byte page number (the page number of pPage) and
55111    ** a variable length key value (which must be the same value as the
55112    ** largest key on pPage).
55113    **
55114    ** To find the largest key value on pPage, first find the right-most
55115    ** cell on pPage. The first two fields of this cell are the
55116    ** record-length (a variable length integer at most 32-bits in size)
55117    ** and the key value (a variable length integer, may have any value).
55118    ** The first of the while(...) loops below skips over the record-length
55119    ** field. The second while(...) loop copies the key value from the
55120    ** cell on pPage into the pSpace buffer.
55121    */
55122    pCell = findCell(pPage, pPage->nCell-1);
55123    pStop = &pCell[9];
55124    while( (*(pCell++)&0x80) && pCell<pStop );
55125    pStop = &pCell[9];
55126    while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
55127
55128    /* Insert the new divider cell into pParent. */
55129    insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
55130               0, pPage->pgno, &rc);
55131
55132    /* Set the right-child pointer of pParent to point to the new page. */
55133    put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
55134
55135    /* Release the reference to the new page. */
55136    releasePage(pNew);
55137  }
55138
55139  return rc;
55140}
55141#endif /* SQLITE_OMIT_QUICKBALANCE */
55142
55143#if 0
55144/*
55145** This function does not contribute anything to the operation of SQLite.
55146** it is sometimes activated temporarily while debugging code responsible
55147** for setting pointer-map entries.
55148*/
55149static int ptrmapCheckPages(MemPage **apPage, int nPage){
55150  int i, j;
55151  for(i=0; i<nPage; i++){
55152    Pgno n;
55153    u8 e;
55154    MemPage *pPage = apPage[i];
55155    BtShared *pBt = pPage->pBt;
55156    assert( pPage->isInit );
55157
55158    for(j=0; j<pPage->nCell; j++){
55159      CellInfo info;
55160      u8 *z;
55161
55162      z = findCell(pPage, j);
55163      btreeParseCellPtr(pPage, z, &info);
55164      if( info.iOverflow ){
55165        Pgno ovfl = get4byte(&z[info.iOverflow]);
55166        ptrmapGet(pBt, ovfl, &e, &n);
55167        assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
55168      }
55169      if( !pPage->leaf ){
55170        Pgno child = get4byte(z);
55171        ptrmapGet(pBt, child, &e, &n);
55172        assert( n==pPage->pgno && e==PTRMAP_BTREE );
55173      }
55174    }
55175    if( !pPage->leaf ){
55176      Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55177      ptrmapGet(pBt, child, &e, &n);
55178      assert( n==pPage->pgno && e==PTRMAP_BTREE );
55179    }
55180  }
55181  return 1;
55182}
55183#endif
55184
55185/*
55186** This function is used to copy the contents of the b-tree node stored
55187** on page pFrom to page pTo. If page pFrom was not a leaf page, then
55188** the pointer-map entries for each child page are updated so that the
55189** parent page stored in the pointer map is page pTo. If pFrom contained
55190** any cells with overflow page pointers, then the corresponding pointer
55191** map entries are also updated so that the parent page is page pTo.
55192**
55193** If pFrom is currently carrying any overflow cells (entries in the
55194** MemPage.apOvfl[] array), they are not copied to pTo.
55195**
55196** Before returning, page pTo is reinitialized using btreeInitPage().
55197**
55198** The performance of this function is not critical. It is only used by
55199** the balance_shallower() and balance_deeper() procedures, neither of
55200** which are called often under normal circumstances.
55201*/
55202static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
55203  if( (*pRC)==SQLITE_OK ){
55204    BtShared * const pBt = pFrom->pBt;
55205    u8 * const aFrom = pFrom->aData;
55206    u8 * const aTo = pTo->aData;
55207    int const iFromHdr = pFrom->hdrOffset;
55208    int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
55209    int rc;
55210    int iData;
55211
55212
55213    assert( pFrom->isInit );
55214    assert( pFrom->nFree>=iToHdr );
55215    assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
55216
55217    /* Copy the b-tree node content from page pFrom to page pTo. */
55218    iData = get2byte(&aFrom[iFromHdr+5]);
55219    memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
55220    memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
55221
55222    /* Reinitialize page pTo so that the contents of the MemPage structure
55223    ** match the new data. The initialization of pTo can actually fail under
55224    ** fairly obscure circumstances, even though it is a copy of initialized
55225    ** page pFrom.
55226    */
55227    pTo->isInit = 0;
55228    rc = btreeInitPage(pTo);
55229    if( rc!=SQLITE_OK ){
55230      *pRC = rc;
55231      return;
55232    }
55233
55234    /* If this is an auto-vacuum database, update the pointer-map entries
55235    ** for any b-tree or overflow pages that pTo now contains the pointers to.
55236    */
55237    if( ISAUTOVACUUM ){
55238      *pRC = setChildPtrmaps(pTo);
55239    }
55240  }
55241}
55242
55243/*
55244** This routine redistributes cells on the iParentIdx'th child of pParent
55245** (hereafter "the page") and up to 2 siblings so that all pages have about the
55246** same amount of free space. Usually a single sibling on either side of the
55247** page are used in the balancing, though both siblings might come from one
55248** side if the page is the first or last child of its parent. If the page
55249** has fewer than 2 siblings (something which can only happen if the page
55250** is a root page or a child of a root page) then all available siblings
55251** participate in the balancing.
55252**
55253** The number of siblings of the page might be increased or decreased by
55254** one or two in an effort to keep pages nearly full but not over full.
55255**
55256** Note that when this routine is called, some of the cells on the page
55257** might not actually be stored in MemPage.aData[]. This can happen
55258** if the page is overfull. This routine ensures that all cells allocated
55259** to the page and its siblings fit into MemPage.aData[] before returning.
55260**
55261** In the course of balancing the page and its siblings, cells may be
55262** inserted into or removed from the parent page (pParent). Doing so
55263** may cause the parent page to become overfull or underfull. If this
55264** happens, it is the responsibility of the caller to invoke the correct
55265** balancing routine to fix this problem (see the balance() routine).
55266**
55267** If this routine fails for any reason, it might leave the database
55268** in a corrupted state. So if this routine fails, the database should
55269** be rolled back.
55270**
55271** The third argument to this function, aOvflSpace, is a pointer to a
55272** buffer big enough to hold one page. If while inserting cells into the parent
55273** page (pParent) the parent page becomes overfull, this buffer is
55274** used to store the parent's overflow cells. Because this function inserts
55275** a maximum of four divider cells into the parent page, and the maximum
55276** size of a cell stored within an internal node is always less than 1/4
55277** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
55278** enough for all overflow cells.
55279**
55280** If aOvflSpace is set to a null pointer, this function returns
55281** SQLITE_NOMEM.
55282*/
55283static int balance_nonroot(
55284  MemPage *pParent,               /* Parent page of siblings being balanced */
55285  int iParentIdx,                 /* Index of "the page" in pParent */
55286  u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
55287  int isRoot                      /* True if pParent is a root-page */
55288){
55289  BtShared *pBt;               /* The whole database */
55290  int nCell = 0;               /* Number of cells in apCell[] */
55291  int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
55292  int nNew = 0;                /* Number of pages in apNew[] */
55293  int nOld;                    /* Number of pages in apOld[] */
55294  int i, j, k;                 /* Loop counters */
55295  int nxDiv;                   /* Next divider slot in pParent->aCell[] */
55296  int rc = SQLITE_OK;          /* The return code */
55297  u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
55298  int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
55299  int usableSpace;             /* Bytes in pPage beyond the header */
55300  int pageFlags;               /* Value of pPage->aData[0] */
55301  int subtotal;                /* Subtotal of bytes in cells on one page */
55302  int iSpace1 = 0;             /* First unused byte of aSpace1[] */
55303  int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
55304  int szScratch;               /* Size of scratch memory requested */
55305  MemPage *apOld[NB];          /* pPage and up to two siblings */
55306  MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
55307  MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
55308  u8 *pRight;                  /* Location in parent of right-sibling pointer */
55309  u8 *apDiv[NB-1];             /* Divider cells in pParent */
55310  int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
55311  int szNew[NB+2];             /* Combined size of cells place on i-th page */
55312  u8 **apCell = 0;             /* All cells begin balanced */
55313  u16 *szCell;                 /* Local size of all cells in apCell[] */
55314  u8 *aSpace1;                 /* Space for copies of dividers cells */
55315  Pgno pgno;                   /* Temp var to store a page number in */
55316
55317  pBt = pParent->pBt;
55318  assert( sqlite3_mutex_held(pBt->mutex) );
55319  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55320
55321#if 0
55322  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
55323#endif
55324
55325  /* At this point pParent may have at most one overflow cell. And if
55326  ** this overflow cell is present, it must be the cell with
55327  ** index iParentIdx. This scenario comes about when this function
55328  ** is called (indirectly) from sqlite3BtreeDelete().
55329  */
55330  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
55331  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
55332
55333  if( !aOvflSpace ){
55334    return SQLITE_NOMEM;
55335  }
55336
55337  /* Find the sibling pages to balance. Also locate the cells in pParent
55338  ** that divide the siblings. An attempt is made to find NN siblings on
55339  ** either side of pPage. More siblings are taken from one side, however,
55340  ** if there are fewer than NN siblings on the other side. If pParent
55341  ** has NB or fewer children then all children of pParent are taken.
55342  **
55343  ** This loop also drops the divider cells from the parent page. This
55344  ** way, the remainder of the function does not have to deal with any
55345  ** overflow cells in the parent page, since if any existed they will
55346  ** have already been removed.
55347  */
55348  i = pParent->nOverflow + pParent->nCell;
55349  if( i<2 ){
55350    nxDiv = 0;
55351    nOld = i+1;
55352  }else{
55353    nOld = 3;
55354    if( iParentIdx==0 ){
55355      nxDiv = 0;
55356    }else if( iParentIdx==i ){
55357      nxDiv = i-2;
55358    }else{
55359      nxDiv = iParentIdx-1;
55360    }
55361    i = 2;
55362  }
55363  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
55364    pRight = &pParent->aData[pParent->hdrOffset+8];
55365  }else{
55366    pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
55367  }
55368  pgno = get4byte(pRight);
55369  while( 1 ){
55370    rc = getAndInitPage(pBt, pgno, &apOld[i]);
55371    if( rc ){
55372      memset(apOld, 0, (i+1)*sizeof(MemPage*));
55373      goto balance_cleanup;
55374    }
55375    nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
55376    if( (i--)==0 ) break;
55377
55378    if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
55379      apDiv[i] = pParent->apOvfl[0];
55380      pgno = get4byte(apDiv[i]);
55381      szNew[i] = cellSizePtr(pParent, apDiv[i]);
55382      pParent->nOverflow = 0;
55383    }else{
55384      apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
55385      pgno = get4byte(apDiv[i]);
55386      szNew[i] = cellSizePtr(pParent, apDiv[i]);
55387
55388      /* Drop the cell from the parent page. apDiv[i] still points to
55389      ** the cell within the parent, even though it has been dropped.
55390      ** This is safe because dropping a cell only overwrites the first
55391      ** four bytes of it, and this function does not need the first
55392      ** four bytes of the divider cell. So the pointer is safe to use
55393      ** later on.
55394      **
55395      ** But not if we are in secure-delete mode. In secure-delete mode,
55396      ** the dropCell() routine will overwrite the entire cell with zeroes.
55397      ** In this case, temporarily copy the cell into the aOvflSpace[]
55398      ** buffer. It will be copied out again as soon as the aSpace[] buffer
55399      ** is allocated.  */
55400      if( pBt->btsFlags & BTS_SECURE_DELETE ){
55401        int iOff;
55402
55403        iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
55404        if( (iOff+szNew[i])>(int)pBt->usableSize ){
55405          rc = SQLITE_CORRUPT_BKPT;
55406          memset(apOld, 0, (i+1)*sizeof(MemPage*));
55407          goto balance_cleanup;
55408        }else{
55409          memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
55410          apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
55411        }
55412      }
55413      dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
55414    }
55415  }
55416
55417  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
55418  ** alignment */
55419  nMaxCells = (nMaxCells + 3)&~3;
55420
55421  /*
55422  ** Allocate space for memory structures
55423  */
55424  k = pBt->pageSize + ROUND8(sizeof(MemPage));
55425  szScratch =
55426       nMaxCells*sizeof(u8*)                       /* apCell */
55427     + nMaxCells*sizeof(u16)                       /* szCell */
55428     + pBt->pageSize                               /* aSpace1 */
55429     + k*nOld;                                     /* Page copies (apCopy) */
55430  apCell = sqlite3ScratchMalloc( szScratch );
55431  if( apCell==0 ){
55432    rc = SQLITE_NOMEM;
55433    goto balance_cleanup;
55434  }
55435  szCell = (u16*)&apCell[nMaxCells];
55436  aSpace1 = (u8*)&szCell[nMaxCells];
55437  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
55438
55439  /*
55440  ** Load pointers to all cells on sibling pages and the divider cells
55441  ** into the local apCell[] array.  Make copies of the divider cells
55442  ** into space obtained from aSpace1[] and remove the the divider Cells
55443  ** from pParent.
55444  **
55445  ** If the siblings are on leaf pages, then the child pointers of the
55446  ** divider cells are stripped from the cells before they are copied
55447  ** into aSpace1[].  In this way, all cells in apCell[] are without
55448  ** child pointers.  If siblings are not leaves, then all cell in
55449  ** apCell[] include child pointers.  Either way, all cells in apCell[]
55450  ** are alike.
55451  **
55452  ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
55453  **       leafData:  1 if pPage holds key+data and pParent holds only keys.
55454  */
55455  leafCorrection = apOld[0]->leaf*4;
55456  leafData = apOld[0]->hasData;
55457  for(i=0; i<nOld; i++){
55458    int limit;
55459
55460    /* Before doing anything else, take a copy of the i'th original sibling
55461    ** The rest of this function will use data from the copies rather
55462    ** that the original pages since the original pages will be in the
55463    ** process of being overwritten.  */
55464    MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
55465    memcpy(pOld, apOld[i], sizeof(MemPage));
55466    pOld->aData = (void*)&pOld[1];
55467    memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
55468
55469    limit = pOld->nCell+pOld->nOverflow;
55470    if( pOld->nOverflow>0 ){
55471      for(j=0; j<limit; j++){
55472        assert( nCell<nMaxCells );
55473        apCell[nCell] = findOverflowCell(pOld, j);
55474        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55475        nCell++;
55476      }
55477    }else{
55478      u8 *aData = pOld->aData;
55479      u16 maskPage = pOld->maskPage;
55480      u16 cellOffset = pOld->cellOffset;
55481      for(j=0; j<limit; j++){
55482        assert( nCell<nMaxCells );
55483        apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
55484        szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55485        nCell++;
55486      }
55487    }
55488    if( i<nOld-1 && !leafData){
55489      u16 sz = (u16)szNew[i];
55490      u8 *pTemp;
55491      assert( nCell<nMaxCells );
55492      szCell[nCell] = sz;
55493      pTemp = &aSpace1[iSpace1];
55494      iSpace1 += sz;
55495      assert( sz<=pBt->maxLocal+23 );
55496      assert( iSpace1 <= (int)pBt->pageSize );
55497      memcpy(pTemp, apDiv[i], sz);
55498      apCell[nCell] = pTemp+leafCorrection;
55499      assert( leafCorrection==0 || leafCorrection==4 );
55500      szCell[nCell] = szCell[nCell] - leafCorrection;
55501      if( !pOld->leaf ){
55502        assert( leafCorrection==0 );
55503        assert( pOld->hdrOffset==0 );
55504        /* The right pointer of the child page pOld becomes the left
55505        ** pointer of the divider cell */
55506        memcpy(apCell[nCell], &pOld->aData[8], 4);
55507      }else{
55508        assert( leafCorrection==4 );
55509        if( szCell[nCell]<4 ){
55510          /* Do not allow any cells smaller than 4 bytes. */
55511          szCell[nCell] = 4;
55512        }
55513      }
55514      nCell++;
55515    }
55516  }
55517
55518  /*
55519  ** Figure out the number of pages needed to hold all nCell cells.
55520  ** Store this number in "k".  Also compute szNew[] which is the total
55521  ** size of all cells on the i-th page and cntNew[] which is the index
55522  ** in apCell[] of the cell that divides page i from page i+1.
55523  ** cntNew[k] should equal nCell.
55524  **
55525  ** Values computed by this block:
55526  **
55527  **           k: The total number of sibling pages
55528  **    szNew[i]: Spaced used on the i-th sibling page.
55529  **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
55530  **              the right of the i-th sibling page.
55531  ** usableSpace: Number of bytes of space available on each sibling.
55532  **
55533  */
55534  usableSpace = pBt->usableSize - 12 + leafCorrection;
55535  for(subtotal=k=i=0; i<nCell; i++){
55536    assert( i<nMaxCells );
55537    subtotal += szCell[i] + 2;
55538    if( subtotal > usableSpace ){
55539      szNew[k] = subtotal - szCell[i];
55540      cntNew[k] = i;
55541      if( leafData ){ i--; }
55542      subtotal = 0;
55543      k++;
55544      if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
55545    }
55546  }
55547  szNew[k] = subtotal;
55548  cntNew[k] = nCell;
55549  k++;
55550
55551  /*
55552  ** The packing computed by the previous block is biased toward the siblings
55553  ** on the left side.  The left siblings are always nearly full, while the
55554  ** right-most sibling might be nearly empty.  This block of code attempts
55555  ** to adjust the packing of siblings to get a better balance.
55556  **
55557  ** This adjustment is more than an optimization.  The packing above might
55558  ** be so out of balance as to be illegal.  For example, the right-most
55559  ** sibling might be completely empty.  This adjustment is not optional.
55560  */
55561  for(i=k-1; i>0; i--){
55562    int szRight = szNew[i];  /* Size of sibling on the right */
55563    int szLeft = szNew[i-1]; /* Size of sibling on the left */
55564    int r;              /* Index of right-most cell in left sibling */
55565    int d;              /* Index of first cell to the left of right sibling */
55566
55567    r = cntNew[i-1] - 1;
55568    d = r + 1 - leafData;
55569    assert( d<nMaxCells );
55570    assert( r<nMaxCells );
55571    while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
55572      szRight += szCell[d] + 2;
55573      szLeft -= szCell[r] + 2;
55574      cntNew[i-1]--;
55575      r = cntNew[i-1] - 1;
55576      d = r + 1 - leafData;
55577    }
55578    szNew[i] = szRight;
55579    szNew[i-1] = szLeft;
55580  }
55581
55582  /* Either we found one or more cells (cntnew[0])>0) or pPage is
55583  ** a virtual root page.  A virtual root page is when the real root
55584  ** page is page 1 and we are the only child of that page.
55585  **
55586  ** UPDATE:  The assert() below is not necessarily true if the database
55587  ** file is corrupt.  The corruption will be detected and reported later
55588  ** in this procedure so there is no need to act upon it now.
55589  */
55590#if 0
55591  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
55592#endif
55593
55594  TRACE(("BALANCE: old: %d %d %d  ",
55595    apOld[0]->pgno,
55596    nOld>=2 ? apOld[1]->pgno : 0,
55597    nOld>=3 ? apOld[2]->pgno : 0
55598  ));
55599
55600  /*
55601  ** Allocate k new pages.  Reuse old pages where possible.
55602  */
55603  if( apOld[0]->pgno<=1 ){
55604    rc = SQLITE_CORRUPT_BKPT;
55605    goto balance_cleanup;
55606  }
55607  pageFlags = apOld[0]->aData[0];
55608  for(i=0; i<k; i++){
55609    MemPage *pNew;
55610    if( i<nOld ){
55611      pNew = apNew[i] = apOld[i];
55612      apOld[i] = 0;
55613      rc = sqlite3PagerWrite(pNew->pDbPage);
55614      nNew++;
55615      if( rc ) goto balance_cleanup;
55616    }else{
55617      assert( i>0 );
55618      rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
55619      if( rc ) goto balance_cleanup;
55620      apNew[i] = pNew;
55621      nNew++;
55622
55623      /* Set the pointer-map entry for the new sibling page. */
55624      if( ISAUTOVACUUM ){
55625        ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
55626        if( rc!=SQLITE_OK ){
55627          goto balance_cleanup;
55628        }
55629      }
55630    }
55631  }
55632
55633  /* Free any old pages that were not reused as new pages.
55634  */
55635  while( i<nOld ){
55636    freePage(apOld[i], &rc);
55637    if( rc ) goto balance_cleanup;
55638    releasePage(apOld[i]);
55639    apOld[i] = 0;
55640    i++;
55641  }
55642
55643  /*
55644  ** Put the new pages in accending order.  This helps to
55645  ** keep entries in the disk file in order so that a scan
55646  ** of the table is a linear scan through the file.  That
55647  ** in turn helps the operating system to deliver pages
55648  ** from the disk more rapidly.
55649  **
55650  ** An O(n^2) insertion sort algorithm is used, but since
55651  ** n is never more than NB (a small constant), that should
55652  ** not be a problem.
55653  **
55654  ** When NB==3, this one optimization makes the database
55655  ** about 25% faster for large insertions and deletions.
55656  */
55657  for(i=0; i<k-1; i++){
55658    int minV = apNew[i]->pgno;
55659    int minI = i;
55660    for(j=i+1; j<k; j++){
55661      if( apNew[j]->pgno<(unsigned)minV ){
55662        minI = j;
55663        minV = apNew[j]->pgno;
55664      }
55665    }
55666    if( minI>i ){
55667      MemPage *pT;
55668      pT = apNew[i];
55669      apNew[i] = apNew[minI];
55670      apNew[minI] = pT;
55671    }
55672  }
55673  TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
55674    apNew[0]->pgno, szNew[0],
55675    nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
55676    nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
55677    nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
55678    nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
55679
55680  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55681  put4byte(pRight, apNew[nNew-1]->pgno);
55682
55683  /*
55684  ** Evenly distribute the data in apCell[] across the new pages.
55685  ** Insert divider cells into pParent as necessary.
55686  */
55687  j = 0;
55688  for(i=0; i<nNew; i++){
55689    /* Assemble the new sibling page. */
55690    MemPage *pNew = apNew[i];
55691    assert( j<nMaxCells );
55692    zeroPage(pNew, pageFlags);
55693    assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
55694    assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
55695    assert( pNew->nOverflow==0 );
55696
55697    j = cntNew[i];
55698
55699    /* If the sibling page assembled above was not the right-most sibling,
55700    ** insert a divider cell into the parent page.
55701    */
55702    assert( i<nNew-1 || j==nCell );
55703    if( j<nCell ){
55704      u8 *pCell;
55705      u8 *pTemp;
55706      int sz;
55707
55708      assert( j<nMaxCells );
55709      pCell = apCell[j];
55710      sz = szCell[j] + leafCorrection;
55711      pTemp = &aOvflSpace[iOvflSpace];
55712      if( !pNew->leaf ){
55713        memcpy(&pNew->aData[8], pCell, 4);
55714      }else if( leafData ){
55715        /* If the tree is a leaf-data tree, and the siblings are leaves,
55716        ** then there is no divider cell in apCell[]. Instead, the divider
55717        ** cell consists of the integer key for the right-most cell of
55718        ** the sibling-page assembled above only.
55719        */
55720        CellInfo info;
55721        j--;
55722        btreeParseCellPtr(pNew, apCell[j], &info);
55723        pCell = pTemp;
55724        sz = 4 + putVarint(&pCell[4], info.nKey);
55725        pTemp = 0;
55726      }else{
55727        pCell -= 4;
55728        /* Obscure case for non-leaf-data trees: If the cell at pCell was
55729        ** previously stored on a leaf node, and its reported size was 4
55730        ** bytes, then it may actually be smaller than this
55731        ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
55732        ** any cell). But it is important to pass the correct size to
55733        ** insertCell(), so reparse the cell now.
55734        **
55735        ** Note that this can never happen in an SQLite data file, as all
55736        ** cells are at least 4 bytes. It only happens in b-trees used
55737        ** to evaluate "IN (SELECT ...)" and similar clauses.
55738        */
55739        if( szCell[j]==4 ){
55740          assert(leafCorrection==4);
55741          sz = cellSizePtr(pParent, pCell);
55742        }
55743      }
55744      iOvflSpace += sz;
55745      assert( sz<=pBt->maxLocal+23 );
55746      assert( iOvflSpace <= (int)pBt->pageSize );
55747      insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
55748      if( rc!=SQLITE_OK ) goto balance_cleanup;
55749      assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55750
55751      j++;
55752      nxDiv++;
55753    }
55754  }
55755  assert( j==nCell );
55756  assert( nOld>0 );
55757  assert( nNew>0 );
55758  if( (pageFlags & PTF_LEAF)==0 ){
55759    u8 *zChild = &apCopy[nOld-1]->aData[8];
55760    memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
55761  }
55762
55763  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
55764    /* The root page of the b-tree now contains no cells. The only sibling
55765    ** page is the right-child of the parent. Copy the contents of the
55766    ** child page into the parent, decreasing the overall height of the
55767    ** b-tree structure by one. This is described as the "balance-shallower"
55768    ** sub-algorithm in some documentation.
55769    **
55770    ** If this is an auto-vacuum database, the call to copyNodeContent()
55771    ** sets all pointer-map entries corresponding to database image pages
55772    ** for which the pointer is stored within the content being copied.
55773    **
55774    ** The second assert below verifies that the child page is defragmented
55775    ** (it must be, as it was just reconstructed using assemblePage()). This
55776    ** is important if the parent page happens to be page 1 of the database
55777    ** image.  */
55778    assert( nNew==1 );
55779    assert( apNew[0]->nFree ==
55780        (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
55781    );
55782    copyNodeContent(apNew[0], pParent, &rc);
55783    freePage(apNew[0], &rc);
55784  }else if( ISAUTOVACUUM ){
55785    /* Fix the pointer-map entries for all the cells that were shifted around.
55786    ** There are several different types of pointer-map entries that need to
55787    ** be dealt with by this routine. Some of these have been set already, but
55788    ** many have not. The following is a summary:
55789    **
55790    **   1) The entries associated with new sibling pages that were not
55791    **      siblings when this function was called. These have already
55792    **      been set. We don't need to worry about old siblings that were
55793    **      moved to the free-list - the freePage() code has taken care
55794    **      of those.
55795    **
55796    **   2) The pointer-map entries associated with the first overflow
55797    **      page in any overflow chains used by new divider cells. These
55798    **      have also already been taken care of by the insertCell() code.
55799    **
55800    **   3) If the sibling pages are not leaves, then the child pages of
55801    **      cells stored on the sibling pages may need to be updated.
55802    **
55803    **   4) If the sibling pages are not internal intkey nodes, then any
55804    **      overflow pages used by these cells may need to be updated
55805    **      (internal intkey nodes never contain pointers to overflow pages).
55806    **
55807    **   5) If the sibling pages are not leaves, then the pointer-map
55808    **      entries for the right-child pages of each sibling may need
55809    **      to be updated.
55810    **
55811    ** Cases 1 and 2 are dealt with above by other code. The next
55812    ** block deals with cases 3 and 4 and the one after that, case 5. Since
55813    ** setting a pointer map entry is a relatively expensive operation, this
55814    ** code only sets pointer map entries for child or overflow pages that have
55815    ** actually moved between pages.  */
55816    MemPage *pNew = apNew[0];
55817    MemPage *pOld = apCopy[0];
55818    int nOverflow = pOld->nOverflow;
55819    int iNextOld = pOld->nCell + nOverflow;
55820    int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
55821    j = 0;                             /* Current 'old' sibling page */
55822    k = 0;                             /* Current 'new' sibling page */
55823    for(i=0; i<nCell; i++){
55824      int isDivider = 0;
55825      while( i==iNextOld ){
55826        /* Cell i is the cell immediately following the last cell on old
55827        ** sibling page j. If the siblings are not leaf pages of an
55828        ** intkey b-tree, then cell i was a divider cell. */
55829        assert( j+1 < ArraySize(apCopy) );
55830        pOld = apCopy[++j];
55831        iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
55832        if( pOld->nOverflow ){
55833          nOverflow = pOld->nOverflow;
55834          iOverflow = i + !leafData + pOld->aiOvfl[0];
55835        }
55836        isDivider = !leafData;
55837      }
55838
55839      assert(nOverflow>0 || iOverflow<i );
55840      assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
55841      assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
55842      if( i==iOverflow ){
55843        isDivider = 1;
55844        if( (--nOverflow)>0 ){
55845          iOverflow++;
55846        }
55847      }
55848
55849      if( i==cntNew[k] ){
55850        /* Cell i is the cell immediately following the last cell on new
55851        ** sibling page k. If the siblings are not leaf pages of an
55852        ** intkey b-tree, then cell i is a divider cell.  */
55853        pNew = apNew[++k];
55854        if( !leafData ) continue;
55855      }
55856      assert( j<nOld );
55857      assert( k<nNew );
55858
55859      /* If the cell was originally divider cell (and is not now) or
55860      ** an overflow cell, or if the cell was located on a different sibling
55861      ** page before the balancing, then the pointer map entries associated
55862      ** with any child or overflow pages need to be updated.  */
55863      if( isDivider || pOld->pgno!=pNew->pgno ){
55864        if( !leafCorrection ){
55865          ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
55866        }
55867        if( szCell[i]>pNew->minLocal ){
55868          ptrmapPutOvflPtr(pNew, apCell[i], &rc);
55869        }
55870      }
55871    }
55872
55873    if( !leafCorrection ){
55874      for(i=0; i<nNew; i++){
55875        u32 key = get4byte(&apNew[i]->aData[8]);
55876        ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
55877      }
55878    }
55879
55880#if 0
55881    /* The ptrmapCheckPages() contains assert() statements that verify that
55882    ** all pointer map pages are set correctly. This is helpful while
55883    ** debugging. This is usually disabled because a corrupt database may
55884    ** cause an assert() statement to fail.  */
55885    ptrmapCheckPages(apNew, nNew);
55886    ptrmapCheckPages(&pParent, 1);
55887#endif
55888  }
55889
55890  assert( pParent->isInit );
55891  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
55892          nOld, nNew, nCell));
55893
55894  /*
55895  ** Cleanup before returning.
55896  */
55897balance_cleanup:
55898  sqlite3ScratchFree(apCell);
55899  for(i=0; i<nOld; i++){
55900    releasePage(apOld[i]);
55901  }
55902  for(i=0; i<nNew; i++){
55903    releasePage(apNew[i]);
55904  }
55905
55906  return rc;
55907}
55908
55909
55910/*
55911** This function is called when the root page of a b-tree structure is
55912** overfull (has one or more overflow pages).
55913**
55914** A new child page is allocated and the contents of the current root
55915** page, including overflow cells, are copied into the child. The root
55916** page is then overwritten to make it an empty page with the right-child
55917** pointer pointing to the new page.
55918**
55919** Before returning, all pointer-map entries corresponding to pages
55920** that the new child-page now contains pointers to are updated. The
55921** entry corresponding to the new right-child pointer of the root
55922** page is also updated.
55923**
55924** If successful, *ppChild is set to contain a reference to the child
55925** page and SQLITE_OK is returned. In this case the caller is required
55926** to call releasePage() on *ppChild exactly once. If an error occurs,
55927** an error code is returned and *ppChild is set to 0.
55928*/
55929static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
55930  int rc;                        /* Return value from subprocedures */
55931  MemPage *pChild = 0;           /* Pointer to a new child page */
55932  Pgno pgnoChild = 0;            /* Page number of the new child page */
55933  BtShared *pBt = pRoot->pBt;    /* The BTree */
55934
55935  assert( pRoot->nOverflow>0 );
55936  assert( sqlite3_mutex_held(pBt->mutex) );
55937
55938  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
55939  ** page that will become the new right-child of pPage. Copy the contents
55940  ** of the node stored on pRoot into the new child page.
55941  */
55942  rc = sqlite3PagerWrite(pRoot->pDbPage);
55943  if( rc==SQLITE_OK ){
55944    rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
55945    copyNodeContent(pRoot, pChild, &rc);
55946    if( ISAUTOVACUUM ){
55947      ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
55948    }
55949  }
55950  if( rc ){
55951    *ppChild = 0;
55952    releasePage(pChild);
55953    return rc;
55954  }
55955  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
55956  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
55957  assert( pChild->nCell==pRoot->nCell );
55958
55959  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
55960
55961  /* Copy the overflow cells from pRoot to pChild */
55962  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
55963         pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
55964  memcpy(pChild->apOvfl, pRoot->apOvfl,
55965         pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
55966  pChild->nOverflow = pRoot->nOverflow;
55967
55968  /* Zero the contents of pRoot. Then install pChild as the right-child. */
55969  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
55970  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
55971
55972  *ppChild = pChild;
55973  return SQLITE_OK;
55974}
55975
55976/*
55977** The page that pCur currently points to has just been modified in
55978** some way. This function figures out if this modification means the
55979** tree needs to be balanced, and if so calls the appropriate balancing
55980** routine. Balancing routines are:
55981**
55982**   balance_quick()
55983**   balance_deeper()
55984**   balance_nonroot()
55985*/
55986static int balance(BtCursor *pCur){
55987  int rc = SQLITE_OK;
55988  const int nMin = pCur->pBt->usableSize * 2 / 3;
55989  u8 aBalanceQuickSpace[13];
55990  u8 *pFree = 0;
55991
55992  TESTONLY( int balance_quick_called = 0 );
55993  TESTONLY( int balance_deeper_called = 0 );
55994
55995  do {
55996    int iPage = pCur->iPage;
55997    MemPage *pPage = pCur->apPage[iPage];
55998
55999    if( iPage==0 ){
56000      if( pPage->nOverflow ){
56001        /* The root page of the b-tree is overfull. In this case call the
56002        ** balance_deeper() function to create a new child for the root-page
56003        ** and copy the current contents of the root-page to it. The
56004        ** next iteration of the do-loop will balance the child page.
56005        */
56006        assert( (balance_deeper_called++)==0 );
56007        rc = balance_deeper(pPage, &pCur->apPage[1]);
56008        if( rc==SQLITE_OK ){
56009          pCur->iPage = 1;
56010          pCur->aiIdx[0] = 0;
56011          pCur->aiIdx[1] = 0;
56012          assert( pCur->apPage[1]->nOverflow );
56013        }
56014      }else{
56015        break;
56016      }
56017    }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
56018      break;
56019    }else{
56020      MemPage * const pParent = pCur->apPage[iPage-1];
56021      int const iIdx = pCur->aiIdx[iPage-1];
56022
56023      rc = sqlite3PagerWrite(pParent->pDbPage);
56024      if( rc==SQLITE_OK ){
56025#ifndef SQLITE_OMIT_QUICKBALANCE
56026        if( pPage->hasData
56027         && pPage->nOverflow==1
56028         && pPage->aiOvfl[0]==pPage->nCell
56029         && pParent->pgno!=1
56030         && pParent->nCell==iIdx
56031        ){
56032          /* Call balance_quick() to create a new sibling of pPage on which
56033          ** to store the overflow cell. balance_quick() inserts a new cell
56034          ** into pParent, which may cause pParent overflow. If this
56035          ** happens, the next interation of the do-loop will balance pParent
56036          ** use either balance_nonroot() or balance_deeper(). Until this
56037          ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
56038          ** buffer.
56039          **
56040          ** The purpose of the following assert() is to check that only a
56041          ** single call to balance_quick() is made for each call to this
56042          ** function. If this were not verified, a subtle bug involving reuse
56043          ** of the aBalanceQuickSpace[] might sneak in.
56044          */
56045          assert( (balance_quick_called++)==0 );
56046          rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
56047        }else
56048#endif
56049        {
56050          /* In this case, call balance_nonroot() to redistribute cells
56051          ** between pPage and up to 2 of its sibling pages. This involves
56052          ** modifying the contents of pParent, which may cause pParent to
56053          ** become overfull or underfull. The next iteration of the do-loop
56054          ** will balance the parent page to correct this.
56055          **
56056          ** If the parent page becomes overfull, the overflow cell or cells
56057          ** are stored in the pSpace buffer allocated immediately below.
56058          ** A subsequent iteration of the do-loop will deal with this by
56059          ** calling balance_nonroot() (balance_deeper() may be called first,
56060          ** but it doesn't deal with overflow cells - just moves them to a
56061          ** different page). Once this subsequent call to balance_nonroot()
56062          ** has completed, it is safe to release the pSpace buffer used by
56063          ** the previous call, as the overflow cell data will have been
56064          ** copied either into the body of a database page or into the new
56065          ** pSpace buffer passed to the latter call to balance_nonroot().
56066          */
56067          u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
56068          rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
56069          if( pFree ){
56070            /* If pFree is not NULL, it points to the pSpace buffer used
56071            ** by a previous call to balance_nonroot(). Its contents are
56072            ** now stored either on real database pages or within the
56073            ** new pSpace buffer, so it may be safely freed here. */
56074            sqlite3PageFree(pFree);
56075          }
56076
56077          /* The pSpace buffer will be freed after the next call to
56078          ** balance_nonroot(), or just before this function returns, whichever
56079          ** comes first. */
56080          pFree = pSpace;
56081        }
56082      }
56083
56084      pPage->nOverflow = 0;
56085
56086      /* The next iteration of the do-loop balances the parent page. */
56087      releasePage(pPage);
56088      pCur->iPage--;
56089    }
56090  }while( rc==SQLITE_OK );
56091
56092  if( pFree ){
56093    sqlite3PageFree(pFree);
56094  }
56095  return rc;
56096}
56097
56098
56099/*
56100** Insert a new record into the BTree.  The key is given by (pKey,nKey)
56101** and the data is given by (pData,nData).  The cursor is used only to
56102** define what table the record should be inserted into.  The cursor
56103** is left pointing at a random location.
56104**
56105** For an INTKEY table, only the nKey value of the key is used.  pKey is
56106** ignored.  For a ZERODATA table, the pData and nData are both ignored.
56107**
56108** If the seekResult parameter is non-zero, then a successful call to
56109** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
56110** been performed. seekResult is the search result returned (a negative
56111** number if pCur points at an entry that is smaller than (pKey, nKey), or
56112** a positive value if pCur points at an etry that is larger than
56113** (pKey, nKey)).
56114**
56115** If the seekResult parameter is non-zero, then the caller guarantees that
56116** cursor pCur is pointing at the existing copy of a row that is to be
56117** overwritten.  If the seekResult parameter is 0, then cursor pCur may
56118** point to any entry or to no entry at all and so this function has to seek
56119** the cursor before the new key can be inserted.
56120*/
56121SQLITE_PRIVATE int sqlite3BtreeInsert(
56122  BtCursor *pCur,                /* Insert data into the table of this cursor */
56123  const void *pKey, i64 nKey,    /* The key of the new record */
56124  const void *pData, int nData,  /* The data of the new record */
56125  int nZero,                     /* Number of extra 0 bytes to append to data */
56126  int appendBias,                /* True if this is likely an append */
56127  int seekResult                 /* Result of prior MovetoUnpacked() call */
56128){
56129  int rc;
56130  int loc = seekResult;          /* -1: before desired location  +1: after */
56131  int szNew = 0;
56132  int idx;
56133  MemPage *pPage;
56134  Btree *p = pCur->pBtree;
56135  BtShared *pBt = p->pBt;
56136  unsigned char *oldCell;
56137  unsigned char *newCell = 0;
56138
56139  if( pCur->eState==CURSOR_FAULT ){
56140    assert( pCur->skipNext!=SQLITE_OK );
56141    return pCur->skipNext;
56142  }
56143
56144  assert( cursorHoldsMutex(pCur) );
56145  assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
56146              && (pBt->btsFlags & BTS_READ_ONLY)==0 );
56147  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56148
56149  /* Assert that the caller has been consistent. If this cursor was opened
56150  ** expecting an index b-tree, then the caller should be inserting blob
56151  ** keys with no associated data. If the cursor was opened expecting an
56152  ** intkey table, the caller should be inserting integer keys with a
56153  ** blob of associated data.  */
56154  assert( (pKey==0)==(pCur->pKeyInfo==0) );
56155
56156  /* If this is an insert into a table b-tree, invalidate any incrblob
56157  ** cursors open on the row being replaced (assuming this is a replace
56158  ** operation - if it is not, the following is a no-op).  */
56159  if( pCur->pKeyInfo==0 ){
56160    invalidateIncrblobCursors(p, nKey, 0);
56161  }
56162
56163  /* Save the positions of any other cursors open on this table.
56164  **
56165  ** In some cases, the call to btreeMoveto() below is a no-op. For
56166  ** example, when inserting data into a table with auto-generated integer
56167  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
56168  ** integer key to use. It then calls this function to actually insert the
56169  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
56170  ** that the cursor is already where it needs to be and returns without
56171  ** doing any work. To avoid thwarting these optimizations, it is important
56172  ** not to clear the cursor here.
56173  */
56174  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56175  if( rc ) return rc;
56176  if( !loc ){
56177    rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
56178    if( rc ) return rc;
56179  }
56180  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
56181
56182  pPage = pCur->apPage[pCur->iPage];
56183  assert( pPage->intKey || nKey>=0 );
56184  assert( pPage->leaf || !pPage->intKey );
56185
56186  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
56187          pCur->pgnoRoot, nKey, nData, pPage->pgno,
56188          loc==0 ? "overwrite" : "new entry"));
56189  assert( pPage->isInit );
56190  allocateTempSpace(pBt);
56191  newCell = pBt->pTmpSpace;
56192  if( newCell==0 ) return SQLITE_NOMEM;
56193  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
56194  if( rc ) goto end_insert;
56195  assert( szNew==cellSizePtr(pPage, newCell) );
56196  assert( szNew <= MX_CELL_SIZE(pBt) );
56197  idx = pCur->aiIdx[pCur->iPage];
56198  if( loc==0 ){
56199    u16 szOld;
56200    assert( idx<pPage->nCell );
56201    rc = sqlite3PagerWrite(pPage->pDbPage);
56202    if( rc ){
56203      goto end_insert;
56204    }
56205    oldCell = findCell(pPage, idx);
56206    if( !pPage->leaf ){
56207      memcpy(newCell, oldCell, 4);
56208    }
56209    szOld = cellSizePtr(pPage, oldCell);
56210    rc = clearCell(pPage, oldCell);
56211    dropCell(pPage, idx, szOld, &rc);
56212    if( rc ) goto end_insert;
56213  }else if( loc<0 && pPage->nCell>0 ){
56214    assert( pPage->leaf );
56215    idx = ++pCur->aiIdx[pCur->iPage];
56216  }else{
56217    assert( pPage->leaf );
56218  }
56219  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
56220  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
56221
56222  /* If no error has occured and pPage has an overflow cell, call balance()
56223  ** to redistribute the cells within the tree. Since balance() may move
56224  ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
56225  ** variables.
56226  **
56227  ** Previous versions of SQLite called moveToRoot() to move the cursor
56228  ** back to the root page as balance() used to invalidate the contents
56229  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
56230  ** set the cursor state to "invalid". This makes common insert operations
56231  ** slightly faster.
56232  **
56233  ** There is a subtle but important optimization here too. When inserting
56234  ** multiple records into an intkey b-tree using a single cursor (as can
56235  ** happen while processing an "INSERT INTO ... SELECT" statement), it
56236  ** is advantageous to leave the cursor pointing to the last entry in
56237  ** the b-tree if possible. If the cursor is left pointing to the last
56238  ** entry in the table, and the next row inserted has an integer key
56239  ** larger than the largest existing key, it is possible to insert the
56240  ** row without seeking the cursor. This can be a big performance boost.
56241  */
56242  pCur->info.nSize = 0;
56243  pCur->validNKey = 0;
56244  if( rc==SQLITE_OK && pPage->nOverflow ){
56245    rc = balance(pCur);
56246
56247    /* Must make sure nOverflow is reset to zero even if the balance()
56248    ** fails. Internal data structure corruption will result otherwise.
56249    ** Also, set the cursor state to invalid. This stops saveCursorPosition()
56250    ** from trying to save the current position of the cursor.  */
56251    pCur->apPage[pCur->iPage]->nOverflow = 0;
56252    pCur->eState = CURSOR_INVALID;
56253  }
56254  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
56255
56256end_insert:
56257  return rc;
56258}
56259
56260/*
56261** Delete the entry that the cursor is pointing to.  The cursor
56262** is left pointing at a arbitrary location.
56263*/
56264SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
56265  Btree *p = pCur->pBtree;
56266  BtShared *pBt = p->pBt;
56267  int rc;                              /* Return code */
56268  MemPage *pPage;                      /* Page to delete cell from */
56269  unsigned char *pCell;                /* Pointer to cell to delete */
56270  int iCellIdx;                        /* Index of cell to delete */
56271  int iCellDepth;                      /* Depth of node containing pCell */
56272
56273  assert( cursorHoldsMutex(pCur) );
56274  assert( pBt->inTransaction==TRANS_WRITE );
56275  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56276  assert( pCur->wrFlag );
56277  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56278  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
56279
56280  if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
56281   || NEVER(pCur->eState!=CURSOR_VALID)
56282  ){
56283    return SQLITE_ERROR;  /* Something has gone awry. */
56284  }
56285
56286  /* If this is a delete operation to remove a row from a table b-tree,
56287  ** invalidate any incrblob cursors open on the row being deleted.  */
56288  if( pCur->pKeyInfo==0 ){
56289    invalidateIncrblobCursors(p, pCur->info.nKey, 0);
56290  }
56291
56292  iCellDepth = pCur->iPage;
56293  iCellIdx = pCur->aiIdx[iCellDepth];
56294  pPage = pCur->apPage[iCellDepth];
56295  pCell = findCell(pPage, iCellIdx);
56296
56297  /* If the page containing the entry to delete is not a leaf page, move
56298  ** the cursor to the largest entry in the tree that is smaller than
56299  ** the entry being deleted. This cell will replace the cell being deleted
56300  ** from the internal node. The 'previous' entry is used for this instead
56301  ** of the 'next' entry, as the previous entry is always a part of the
56302  ** sub-tree headed by the child page of the cell being deleted. This makes
56303  ** balancing the tree following the delete operation easier.  */
56304  if( !pPage->leaf ){
56305    int notUsed;
56306    rc = sqlite3BtreePrevious(pCur, &notUsed);
56307    if( rc ) return rc;
56308  }
56309
56310  /* Save the positions of any other cursors open on this table before
56311  ** making any modifications. Make the page containing the entry to be
56312  ** deleted writable. Then free any overflow pages associated with the
56313  ** entry and finally remove the cell itself from within the page.
56314  */
56315  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56316  if( rc ) return rc;
56317  rc = sqlite3PagerWrite(pPage->pDbPage);
56318  if( rc ) return rc;
56319  rc = clearCell(pPage, pCell);
56320  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
56321  if( rc ) return rc;
56322
56323  /* If the cell deleted was not located on a leaf page, then the cursor
56324  ** is currently pointing to the largest entry in the sub-tree headed
56325  ** by the child-page of the cell that was just deleted from an internal
56326  ** node. The cell from the leaf node needs to be moved to the internal
56327  ** node to replace the deleted cell.  */
56328  if( !pPage->leaf ){
56329    MemPage *pLeaf = pCur->apPage[pCur->iPage];
56330    int nCell;
56331    Pgno n = pCur->apPage[iCellDepth+1]->pgno;
56332    unsigned char *pTmp;
56333
56334    pCell = findCell(pLeaf, pLeaf->nCell-1);
56335    nCell = cellSizePtr(pLeaf, pCell);
56336    assert( MX_CELL_SIZE(pBt) >= nCell );
56337
56338    allocateTempSpace(pBt);
56339    pTmp = pBt->pTmpSpace;
56340
56341    rc = sqlite3PagerWrite(pLeaf->pDbPage);
56342    insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
56343    dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
56344    if( rc ) return rc;
56345  }
56346
56347  /* Balance the tree. If the entry deleted was located on a leaf page,
56348  ** then the cursor still points to that page. In this case the first
56349  ** call to balance() repairs the tree, and the if(...) condition is
56350  ** never true.
56351  **
56352  ** Otherwise, if the entry deleted was on an internal node page, then
56353  ** pCur is pointing to the leaf page from which a cell was removed to
56354  ** replace the cell deleted from the internal node. This is slightly
56355  ** tricky as the leaf node may be underfull, and the internal node may
56356  ** be either under or overfull. In this case run the balancing algorithm
56357  ** on the leaf node first. If the balance proceeds far enough up the
56358  ** tree that we can be sure that any problem in the internal node has
56359  ** been corrected, so be it. Otherwise, after balancing the leaf node,
56360  ** walk the cursor up the tree to the internal node and balance it as
56361  ** well.  */
56362  rc = balance(pCur);
56363  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
56364    while( pCur->iPage>iCellDepth ){
56365      releasePage(pCur->apPage[pCur->iPage--]);
56366    }
56367    rc = balance(pCur);
56368  }
56369
56370  if( rc==SQLITE_OK ){
56371    moveToRoot(pCur);
56372  }
56373  return rc;
56374}
56375
56376/*
56377** Create a new BTree table.  Write into *piTable the page
56378** number for the root page of the new table.
56379**
56380** The type of type is determined by the flags parameter.  Only the
56381** following values of flags are currently in use.  Other values for
56382** flags might not work:
56383**
56384**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
56385**     BTREE_ZERODATA                  Used for SQL indices
56386*/
56387static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
56388  BtShared *pBt = p->pBt;
56389  MemPage *pRoot;
56390  Pgno pgnoRoot;
56391  int rc;
56392  int ptfFlags;          /* Page-type flage for the root page of new table */
56393
56394  assert( sqlite3BtreeHoldsMutex(p) );
56395  assert( pBt->inTransaction==TRANS_WRITE );
56396  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56397
56398#ifdef SQLITE_OMIT_AUTOVACUUM
56399  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56400  if( rc ){
56401    return rc;
56402  }
56403#else
56404  if( pBt->autoVacuum ){
56405    Pgno pgnoMove;      /* Move a page here to make room for the root-page */
56406    MemPage *pPageMove; /* The page to move to. */
56407
56408    /* Creating a new table may probably require moving an existing database
56409    ** to make room for the new tables root page. In case this page turns
56410    ** out to be an overflow page, delete all overflow page-map caches
56411    ** held by open cursors.
56412    */
56413    invalidateAllOverflowCache(pBt);
56414
56415    /* Read the value of meta[3] from the database to determine where the
56416    ** root page of the new table should go. meta[3] is the largest root-page
56417    ** created so far, so the new root-page is (meta[3]+1).
56418    */
56419    sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
56420    pgnoRoot++;
56421
56422    /* The new root-page may not be allocated on a pointer-map page, or the
56423    ** PENDING_BYTE page.
56424    */
56425    while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
56426        pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
56427      pgnoRoot++;
56428    }
56429    assert( pgnoRoot>=3 );
56430
56431    /* Allocate a page. The page that currently resides at pgnoRoot will
56432    ** be moved to the allocated page (unless the allocated page happens
56433    ** to reside at pgnoRoot).
56434    */
56435    rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
56436    if( rc!=SQLITE_OK ){
56437      return rc;
56438    }
56439
56440    if( pgnoMove!=pgnoRoot ){
56441      /* pgnoRoot is the page that will be used for the root-page of
56442      ** the new table (assuming an error did not occur). But we were
56443      ** allocated pgnoMove. If required (i.e. if it was not allocated
56444      ** by extending the file), the current page at position pgnoMove
56445      ** is already journaled.
56446      */
56447      u8 eType = 0;
56448      Pgno iPtrPage = 0;
56449
56450      releasePage(pPageMove);
56451
56452      /* Move the page currently at pgnoRoot to pgnoMove. */
56453      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56454      if( rc!=SQLITE_OK ){
56455        return rc;
56456      }
56457      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
56458      if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
56459        rc = SQLITE_CORRUPT_BKPT;
56460      }
56461      if( rc!=SQLITE_OK ){
56462        releasePage(pRoot);
56463        return rc;
56464      }
56465      assert( eType!=PTRMAP_ROOTPAGE );
56466      assert( eType!=PTRMAP_FREEPAGE );
56467      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
56468      releasePage(pRoot);
56469
56470      /* Obtain the page at pgnoRoot */
56471      if( rc!=SQLITE_OK ){
56472        return rc;
56473      }
56474      rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
56475      if( rc!=SQLITE_OK ){
56476        return rc;
56477      }
56478      rc = sqlite3PagerWrite(pRoot->pDbPage);
56479      if( rc!=SQLITE_OK ){
56480        releasePage(pRoot);
56481        return rc;
56482      }
56483    }else{
56484      pRoot = pPageMove;
56485    }
56486
56487    /* Update the pointer-map and meta-data with the new root-page number. */
56488    ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
56489    if( rc ){
56490      releasePage(pRoot);
56491      return rc;
56492    }
56493
56494    /* When the new root page was allocated, page 1 was made writable in
56495    ** order either to increase the database filesize, or to decrement the
56496    ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
56497    */
56498    assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
56499    rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
56500    if( NEVER(rc) ){
56501      releasePage(pRoot);
56502      return rc;
56503    }
56504
56505  }else{
56506    rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56507    if( rc ) return rc;
56508  }
56509#endif
56510  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56511  if( createTabFlags & BTREE_INTKEY ){
56512    ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
56513  }else{
56514    ptfFlags = PTF_ZERODATA | PTF_LEAF;
56515  }
56516  zeroPage(pRoot, ptfFlags);
56517  sqlite3PagerUnref(pRoot->pDbPage);
56518  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
56519  *piTable = (int)pgnoRoot;
56520  return SQLITE_OK;
56521}
56522SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
56523  int rc;
56524  sqlite3BtreeEnter(p);
56525  rc = btreeCreateTable(p, piTable, flags);
56526  sqlite3BtreeLeave(p);
56527  return rc;
56528}
56529
56530/*
56531** Erase the given database page and all its children.  Return
56532** the page to the freelist.
56533*/
56534static int clearDatabasePage(
56535  BtShared *pBt,           /* The BTree that contains the table */
56536  Pgno pgno,               /* Page number to clear */
56537  int freePageFlag,        /* Deallocate page if true */
56538  int *pnChange            /* Add number of Cells freed to this counter */
56539){
56540  MemPage *pPage;
56541  int rc;
56542  unsigned char *pCell;
56543  int i;
56544
56545  assert( sqlite3_mutex_held(pBt->mutex) );
56546  if( pgno>btreePagecount(pBt) ){
56547    return SQLITE_CORRUPT_BKPT;
56548  }
56549
56550  rc = getAndInitPage(pBt, pgno, &pPage);
56551  if( rc ) return rc;
56552  for(i=0; i<pPage->nCell; i++){
56553    pCell = findCell(pPage, i);
56554    if( !pPage->leaf ){
56555      rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
56556      if( rc ) goto cleardatabasepage_out;
56557    }
56558    rc = clearCell(pPage, pCell);
56559    if( rc ) goto cleardatabasepage_out;
56560  }
56561  if( !pPage->leaf ){
56562    rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
56563    if( rc ) goto cleardatabasepage_out;
56564  }else if( pnChange ){
56565    assert( pPage->intKey );
56566    *pnChange += pPage->nCell;
56567  }
56568  if( freePageFlag ){
56569    freePage(pPage, &rc);
56570  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
56571    zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
56572  }
56573
56574cleardatabasepage_out:
56575  releasePage(pPage);
56576  return rc;
56577}
56578
56579/*
56580** Delete all information from a single table in the database.  iTable is
56581** the page number of the root of the table.  After this routine returns,
56582** the root page is empty, but still exists.
56583**
56584** This routine will fail with SQLITE_LOCKED if there are any open
56585** read cursors on the table.  Open write cursors are moved to the
56586** root of the table.
56587**
56588** If pnChange is not NULL, then table iTable must be an intkey table. The
56589** integer value pointed to by pnChange is incremented by the number of
56590** entries in the table.
56591*/
56592SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
56593  int rc;
56594  BtShared *pBt = p->pBt;
56595  sqlite3BtreeEnter(p);
56596  assert( p->inTrans==TRANS_WRITE );
56597
56598  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
56599  ** is the root of a table b-tree - if it is not, the following call is
56600  ** a no-op).  */
56601  invalidateIncrblobCursors(p, 0, 1);
56602
56603  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
56604  if( SQLITE_OK==rc ){
56605    rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
56606  }
56607  sqlite3BtreeLeave(p);
56608  return rc;
56609}
56610
56611/*
56612** Erase all information in a table and add the root of the table to
56613** the freelist.  Except, the root of the principle table (the one on
56614** page 1) is never added to the freelist.
56615**
56616** This routine will fail with SQLITE_LOCKED if there are any open
56617** cursors on the table.
56618**
56619** If AUTOVACUUM is enabled and the page at iTable is not the last
56620** root page in the database file, then the last root page
56621** in the database file is moved into the slot formerly occupied by
56622** iTable and that last slot formerly occupied by the last root page
56623** is added to the freelist instead of iTable.  In this say, all
56624** root pages are kept at the beginning of the database file, which
56625** is necessary for AUTOVACUUM to work right.  *piMoved is set to the
56626** page number that used to be the last root page in the file before
56627** the move.  If no page gets moved, *piMoved is set to 0.
56628** The last root page is recorded in meta[3] and the value of
56629** meta[3] is updated by this procedure.
56630*/
56631static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
56632  int rc;
56633  MemPage *pPage = 0;
56634  BtShared *pBt = p->pBt;
56635
56636  assert( sqlite3BtreeHoldsMutex(p) );
56637  assert( p->inTrans==TRANS_WRITE );
56638
56639  /* It is illegal to drop a table if any cursors are open on the
56640  ** database. This is because in auto-vacuum mode the backend may
56641  ** need to move another root-page to fill a gap left by the deleted
56642  ** root page. If an open cursor was using this page a problem would
56643  ** occur.
56644  **
56645  ** This error is caught long before control reaches this point.
56646  */
56647  if( NEVER(pBt->pCursor) ){
56648    sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
56649    return SQLITE_LOCKED_SHAREDCACHE;
56650  }
56651
56652  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
56653  if( rc ) return rc;
56654  rc = sqlite3BtreeClearTable(p, iTable, 0);
56655  if( rc ){
56656    releasePage(pPage);
56657    return rc;
56658  }
56659
56660  *piMoved = 0;
56661
56662  if( iTable>1 ){
56663#ifdef SQLITE_OMIT_AUTOVACUUM
56664    freePage(pPage, &rc);
56665    releasePage(pPage);
56666#else
56667    if( pBt->autoVacuum ){
56668      Pgno maxRootPgno;
56669      sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
56670
56671      if( iTable==maxRootPgno ){
56672        /* If the table being dropped is the table with the largest root-page
56673        ** number in the database, put the root page on the free list.
56674        */
56675        freePage(pPage, &rc);
56676        releasePage(pPage);
56677        if( rc!=SQLITE_OK ){
56678          return rc;
56679        }
56680      }else{
56681        /* The table being dropped does not have the largest root-page
56682        ** number in the database. So move the page that does into the
56683        ** gap left by the deleted root-page.
56684        */
56685        MemPage *pMove;
56686        releasePage(pPage);
56687        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
56688        if( rc!=SQLITE_OK ){
56689          return rc;
56690        }
56691        rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
56692        releasePage(pMove);
56693        if( rc!=SQLITE_OK ){
56694          return rc;
56695        }
56696        pMove = 0;
56697        rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
56698        freePage(pMove, &rc);
56699        releasePage(pMove);
56700        if( rc!=SQLITE_OK ){
56701          return rc;
56702        }
56703        *piMoved = maxRootPgno;
56704      }
56705
56706      /* Set the new 'max-root-page' value in the database header. This
56707      ** is the old value less one, less one more if that happens to
56708      ** be a root-page number, less one again if that is the
56709      ** PENDING_BYTE_PAGE.
56710      */
56711      maxRootPgno--;
56712      while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
56713             || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
56714        maxRootPgno--;
56715      }
56716      assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
56717
56718      rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
56719    }else{
56720      freePage(pPage, &rc);
56721      releasePage(pPage);
56722    }
56723#endif
56724  }else{
56725    /* If sqlite3BtreeDropTable was called on page 1.
56726    ** This really never should happen except in a corrupt
56727    ** database.
56728    */
56729    zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
56730    releasePage(pPage);
56731  }
56732  return rc;
56733}
56734SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
56735  int rc;
56736  sqlite3BtreeEnter(p);
56737  rc = btreeDropTable(p, iTable, piMoved);
56738  sqlite3BtreeLeave(p);
56739  return rc;
56740}
56741
56742
56743/*
56744** This function may only be called if the b-tree connection already
56745** has a read or write transaction open on the database.
56746**
56747** Read the meta-information out of a database file.  Meta[0]
56748** is the number of free pages currently in the database.  Meta[1]
56749** through meta[15] are available for use by higher layers.  Meta[0]
56750** is read-only, the others are read/write.
56751**
56752** The schema layer numbers meta values differently.  At the schema
56753** layer (and the SetCookie and ReadCookie opcodes) the number of
56754** free pages is not visible.  So Cookie[0] is the same as Meta[1].
56755*/
56756SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
56757  BtShared *pBt = p->pBt;
56758
56759  sqlite3BtreeEnter(p);
56760  assert( p->inTrans>TRANS_NONE );
56761  assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
56762  assert( pBt->pPage1 );
56763  assert( idx>=0 && idx<=15 );
56764
56765  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
56766
56767  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
56768  ** database, mark the database as read-only.  */
56769#ifdef SQLITE_OMIT_AUTOVACUUM
56770  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
56771    pBt->btsFlags |= BTS_READ_ONLY;
56772  }
56773#endif
56774
56775  sqlite3BtreeLeave(p);
56776}
56777
56778/*
56779** Write meta-information back into the database.  Meta[0] is
56780** read-only and may not be written.
56781*/
56782SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
56783  BtShared *pBt = p->pBt;
56784  unsigned char *pP1;
56785  int rc;
56786  assert( idx>=1 && idx<=15 );
56787  sqlite3BtreeEnter(p);
56788  assert( p->inTrans==TRANS_WRITE );
56789  assert( pBt->pPage1!=0 );
56790  pP1 = pBt->pPage1->aData;
56791  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56792  if( rc==SQLITE_OK ){
56793    put4byte(&pP1[36 + idx*4], iMeta);
56794#ifndef SQLITE_OMIT_AUTOVACUUM
56795    if( idx==BTREE_INCR_VACUUM ){
56796      assert( pBt->autoVacuum || iMeta==0 );
56797      assert( iMeta==0 || iMeta==1 );
56798      pBt->incrVacuum = (u8)iMeta;
56799    }
56800#endif
56801  }
56802  sqlite3BtreeLeave(p);
56803  return rc;
56804}
56805
56806#ifndef SQLITE_OMIT_BTREECOUNT
56807/*
56808** The first argument, pCur, is a cursor opened on some b-tree. Count the
56809** number of entries in the b-tree and write the result to *pnEntry.
56810**
56811** SQLITE_OK is returned if the operation is successfully executed.
56812** Otherwise, if an error is encountered (i.e. an IO error or database
56813** corruption) an SQLite error code is returned.
56814*/
56815SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
56816  i64 nEntry = 0;                      /* Value to return in *pnEntry */
56817  int rc;                              /* Return code */
56818
56819  if( pCur->pgnoRoot==0 ){
56820    *pnEntry = 0;
56821    return SQLITE_OK;
56822  }
56823  rc = moveToRoot(pCur);
56824
56825  /* Unless an error occurs, the following loop runs one iteration for each
56826  ** page in the B-Tree structure (not including overflow pages).
56827  */
56828  while( rc==SQLITE_OK ){
56829    int iIdx;                          /* Index of child node in parent */
56830    MemPage *pPage;                    /* Current page of the b-tree */
56831
56832    /* If this is a leaf page or the tree is not an int-key tree, then
56833    ** this page contains countable entries. Increment the entry counter
56834    ** accordingly.
56835    */
56836    pPage = pCur->apPage[pCur->iPage];
56837    if( pPage->leaf || !pPage->intKey ){
56838      nEntry += pPage->nCell;
56839    }
56840
56841    /* pPage is a leaf node. This loop navigates the cursor so that it
56842    ** points to the first interior cell that it points to the parent of
56843    ** the next page in the tree that has not yet been visited. The
56844    ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
56845    ** of the page, or to the number of cells in the page if the next page
56846    ** to visit is the right-child of its parent.
56847    **
56848    ** If all pages in the tree have been visited, return SQLITE_OK to the
56849    ** caller.
56850    */
56851    if( pPage->leaf ){
56852      do {
56853        if( pCur->iPage==0 ){
56854          /* All pages of the b-tree have been visited. Return successfully. */
56855          *pnEntry = nEntry;
56856          return SQLITE_OK;
56857        }
56858        moveToParent(pCur);
56859      }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
56860
56861      pCur->aiIdx[pCur->iPage]++;
56862      pPage = pCur->apPage[pCur->iPage];
56863    }
56864
56865    /* Descend to the child node of the cell that the cursor currently
56866    ** points at. This is the right-child if (iIdx==pPage->nCell).
56867    */
56868    iIdx = pCur->aiIdx[pCur->iPage];
56869    if( iIdx==pPage->nCell ){
56870      rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
56871    }else{
56872      rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
56873    }
56874  }
56875
56876  /* An error has occurred. Return an error code. */
56877  return rc;
56878}
56879#endif
56880
56881/*
56882** Return the pager associated with a BTree.  This routine is used for
56883** testing and debugging only.
56884*/
56885SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
56886  return p->pBt->pPager;
56887}
56888
56889#ifndef SQLITE_OMIT_INTEGRITY_CHECK
56890/*
56891** Append a message to the error message string.
56892*/
56893static void checkAppendMsg(
56894  IntegrityCk *pCheck,
56895  char *zMsg1,
56896  const char *zFormat,
56897  ...
56898){
56899  va_list ap;
56900  if( !pCheck->mxErr ) return;
56901  pCheck->mxErr--;
56902  pCheck->nErr++;
56903  va_start(ap, zFormat);
56904  if( pCheck->errMsg.nChar ){
56905    sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
56906  }
56907  if( zMsg1 ){
56908    sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
56909  }
56910  sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
56911  va_end(ap);
56912  if( pCheck->errMsg.mallocFailed ){
56913    pCheck->mallocFailed = 1;
56914  }
56915}
56916#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
56917
56918#ifndef SQLITE_OMIT_INTEGRITY_CHECK
56919/*
56920** Add 1 to the reference count for page iPage.  If this is the second
56921** reference to the page, add an error message to pCheck->zErrMsg.
56922** Return 1 if there are 2 ore more references to the page and 0 if
56923** if this is the first reference to the page.
56924**
56925** Also check that the page number is in bounds.
56926*/
56927static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
56928  if( iPage==0 ) return 1;
56929  if( iPage>pCheck->nPage ){
56930    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
56931    return 1;
56932  }
56933  if( pCheck->anRef[iPage]==1 ){
56934    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
56935    return 1;
56936  }
56937  return  (pCheck->anRef[iPage]++)>1;
56938}
56939
56940#ifndef SQLITE_OMIT_AUTOVACUUM
56941/*
56942** Check that the entry in the pointer-map for page iChild maps to
56943** page iParent, pointer type ptrType. If not, append an error message
56944** to pCheck.
56945*/
56946static void checkPtrmap(
56947  IntegrityCk *pCheck,   /* Integrity check context */
56948  Pgno iChild,           /* Child page number */
56949  u8 eType,              /* Expected pointer map type */
56950  Pgno iParent,          /* Expected pointer map parent page number */
56951  char *zContext         /* Context description (used for error msg) */
56952){
56953  int rc;
56954  u8 ePtrmapType;
56955  Pgno iPtrmapParent;
56956
56957  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
56958  if( rc!=SQLITE_OK ){
56959    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
56960    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
56961    return;
56962  }
56963
56964  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
56965    checkAppendMsg(pCheck, zContext,
56966      "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
56967      iChild, eType, iParent, ePtrmapType, iPtrmapParent);
56968  }
56969}
56970#endif
56971
56972/*
56973** Check the integrity of the freelist or of an overflow page list.
56974** Verify that the number of pages on the list is N.
56975*/
56976static void checkList(
56977  IntegrityCk *pCheck,  /* Integrity checking context */
56978  int isFreeList,       /* True for a freelist.  False for overflow page list */
56979  int iPage,            /* Page number for first page in the list */
56980  int N,                /* Expected number of pages in the list */
56981  char *zContext        /* Context for error messages */
56982){
56983  int i;
56984  int expected = N;
56985  int iFirst = iPage;
56986  while( N-- > 0 && pCheck->mxErr ){
56987    DbPage *pOvflPage;
56988    unsigned char *pOvflData;
56989    if( iPage<1 ){
56990      checkAppendMsg(pCheck, zContext,
56991         "%d of %d pages missing from overflow list starting at %d",
56992          N+1, expected, iFirst);
56993      break;
56994    }
56995    if( checkRef(pCheck, iPage, zContext) ) break;
56996    if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
56997      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
56998      break;
56999    }
57000    pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
57001    if( isFreeList ){
57002      int n = get4byte(&pOvflData[4]);
57003#ifndef SQLITE_OMIT_AUTOVACUUM
57004      if( pCheck->pBt->autoVacuum ){
57005        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
57006      }
57007#endif
57008      if( n>(int)pCheck->pBt->usableSize/4-2 ){
57009        checkAppendMsg(pCheck, zContext,
57010           "freelist leaf count too big on page %d", iPage);
57011        N--;
57012      }else{
57013        for(i=0; i<n; i++){
57014          Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
57015#ifndef SQLITE_OMIT_AUTOVACUUM
57016          if( pCheck->pBt->autoVacuum ){
57017            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
57018          }
57019#endif
57020          checkRef(pCheck, iFreePage, zContext);
57021        }
57022        N -= n;
57023      }
57024    }
57025#ifndef SQLITE_OMIT_AUTOVACUUM
57026    else{
57027      /* If this database supports auto-vacuum and iPage is not the last
57028      ** page in this overflow list, check that the pointer-map entry for
57029      ** the following page matches iPage.
57030      */
57031      if( pCheck->pBt->autoVacuum && N>0 ){
57032        i = get4byte(pOvflData);
57033        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
57034      }
57035    }
57036#endif
57037    iPage = get4byte(pOvflData);
57038    sqlite3PagerUnref(pOvflPage);
57039  }
57040}
57041#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57042
57043#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57044/*
57045** Do various sanity checks on a single page of a tree.  Return
57046** the tree depth.  Root pages return 0.  Parents of root pages
57047** return 1, and so forth.
57048**
57049** These checks are done:
57050**
57051**      1.  Make sure that cells and freeblocks do not overlap
57052**          but combine to completely cover the page.
57053**  NO  2.  Make sure cell keys are in order.
57054**  NO  3.  Make sure no key is less than or equal to zLowerBound.
57055**  NO  4.  Make sure no key is greater than or equal to zUpperBound.
57056**      5.  Check the integrity of overflow pages.
57057**      6.  Recursively call checkTreePage on all children.
57058**      7.  Verify that the depth of all children is the same.
57059**      8.  Make sure this page is at least 33% full or else it is
57060**          the root of the tree.
57061*/
57062static int checkTreePage(
57063  IntegrityCk *pCheck,  /* Context for the sanity check */
57064  int iPage,            /* Page number of the page to check */
57065  char *zParentContext, /* Parent context */
57066  i64 *pnParentMinKey,
57067  i64 *pnParentMaxKey
57068){
57069  MemPage *pPage;
57070  int i, rc, depth, d2, pgno, cnt;
57071  int hdr, cellStart;
57072  int nCell;
57073  u8 *data;
57074  BtShared *pBt;
57075  int usableSize;
57076  char zContext[100];
57077  char *hit = 0;
57078  i64 nMinKey = 0;
57079  i64 nMaxKey = 0;
57080
57081  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
57082
57083  /* Check that the page exists
57084  */
57085  pBt = pCheck->pBt;
57086  usableSize = pBt->usableSize;
57087  if( iPage==0 ) return 0;
57088  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
57089  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
57090    checkAppendMsg(pCheck, zContext,
57091       "unable to get the page. error code=%d", rc);
57092    return 0;
57093  }
57094
57095  /* Clear MemPage.isInit to make sure the corruption detection code in
57096  ** btreeInitPage() is executed.  */
57097  pPage->isInit = 0;
57098  if( (rc = btreeInitPage(pPage))!=0 ){
57099    assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
57100    checkAppendMsg(pCheck, zContext,
57101                   "btreeInitPage() returns error code %d", rc);
57102    releasePage(pPage);
57103    return 0;
57104  }
57105
57106  /* Check out all the cells.
57107  */
57108  depth = 0;
57109  for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
57110    u8 *pCell;
57111    u32 sz;
57112    CellInfo info;
57113
57114    /* Check payload overflow pages
57115    */
57116    sqlite3_snprintf(sizeof(zContext), zContext,
57117             "On tree page %d cell %d: ", iPage, i);
57118    pCell = findCell(pPage,i);
57119    btreeParseCellPtr(pPage, pCell, &info);
57120    sz = info.nData;
57121    if( !pPage->intKey ) sz += (int)info.nKey;
57122    /* For intKey pages, check that the keys are in order.
57123    */
57124    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
57125    else{
57126      if( info.nKey <= nMaxKey ){
57127        checkAppendMsg(pCheck, zContext,
57128            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
57129      }
57130      nMaxKey = info.nKey;
57131    }
57132    assert( sz==info.nPayload );
57133    if( (sz>info.nLocal)
57134     && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
57135    ){
57136      int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
57137      Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
57138#ifndef SQLITE_OMIT_AUTOVACUUM
57139      if( pBt->autoVacuum ){
57140        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
57141      }
57142#endif
57143      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
57144    }
57145
57146    /* Check sanity of left child page.
57147    */
57148    if( !pPage->leaf ){
57149      pgno = get4byte(pCell);
57150#ifndef SQLITE_OMIT_AUTOVACUUM
57151      if( pBt->autoVacuum ){
57152        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57153      }
57154#endif
57155      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
57156      if( i>0 && d2!=depth ){
57157        checkAppendMsg(pCheck, zContext, "Child page depth differs");
57158      }
57159      depth = d2;
57160    }
57161  }
57162
57163  if( !pPage->leaf ){
57164    pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57165    sqlite3_snprintf(sizeof(zContext), zContext,
57166                     "On page %d at right child: ", iPage);
57167#ifndef SQLITE_OMIT_AUTOVACUUM
57168    if( pBt->autoVacuum ){
57169      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57170    }
57171#endif
57172    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
57173  }
57174
57175  /* For intKey leaf pages, check that the min/max keys are in order
57176  ** with any left/parent/right pages.
57177  */
57178  if( pPage->leaf && pPage->intKey ){
57179    /* if we are a left child page */
57180    if( pnParentMinKey ){
57181      /* if we are the left most child page */
57182      if( !pnParentMaxKey ){
57183        if( nMaxKey > *pnParentMinKey ){
57184          checkAppendMsg(pCheck, zContext,
57185              "Rowid %lld out of order (max larger than parent min of %lld)",
57186              nMaxKey, *pnParentMinKey);
57187        }
57188      }else{
57189        if( nMinKey <= *pnParentMinKey ){
57190          checkAppendMsg(pCheck, zContext,
57191              "Rowid %lld out of order (min less than parent min of %lld)",
57192              nMinKey, *pnParentMinKey);
57193        }
57194        if( nMaxKey > *pnParentMaxKey ){
57195          checkAppendMsg(pCheck, zContext,
57196              "Rowid %lld out of order (max larger than parent max of %lld)",
57197              nMaxKey, *pnParentMaxKey);
57198        }
57199        *pnParentMinKey = nMaxKey;
57200      }
57201    /* else if we're a right child page */
57202    } else if( pnParentMaxKey ){
57203      if( nMinKey <= *pnParentMaxKey ){
57204        checkAppendMsg(pCheck, zContext,
57205            "Rowid %lld out of order (min less than parent max of %lld)",
57206            nMinKey, *pnParentMaxKey);
57207      }
57208    }
57209  }
57210
57211  /* Check for complete coverage of the page
57212  */
57213  data = pPage->aData;
57214  hdr = pPage->hdrOffset;
57215  hit = sqlite3PageMalloc( pBt->pageSize );
57216  if( hit==0 ){
57217    pCheck->mallocFailed = 1;
57218  }else{
57219    int contentOffset = get2byteNotZero(&data[hdr+5]);
57220    assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
57221    memset(hit+contentOffset, 0, usableSize-contentOffset);
57222    memset(hit, 1, contentOffset);
57223    nCell = get2byte(&data[hdr+3]);
57224    cellStart = hdr + 12 - 4*pPage->leaf;
57225    for(i=0; i<nCell; i++){
57226      int pc = get2byte(&data[cellStart+i*2]);
57227      u32 size = 65536;
57228      int j;
57229      if( pc<=usableSize-4 ){
57230        size = cellSizePtr(pPage, &data[pc]);
57231      }
57232      if( (int)(pc+size-1)>=usableSize ){
57233        checkAppendMsg(pCheck, 0,
57234            "Corruption detected in cell %d on page %d",i,iPage);
57235      }else{
57236        for(j=pc+size-1; j>=pc; j--) hit[j]++;
57237      }
57238    }
57239    i = get2byte(&data[hdr+1]);
57240    while( i>0 ){
57241      int size, j;
57242      assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
57243      size = get2byte(&data[i+2]);
57244      assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
57245      for(j=i+size-1; j>=i; j--) hit[j]++;
57246      j = get2byte(&data[i]);
57247      assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
57248      assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
57249      i = j;
57250    }
57251    for(i=cnt=0; i<usableSize; i++){
57252      if( hit[i]==0 ){
57253        cnt++;
57254      }else if( hit[i]>1 ){
57255        checkAppendMsg(pCheck, 0,
57256          "Multiple uses for byte %d of page %d", i, iPage);
57257        break;
57258      }
57259    }
57260    if( cnt!=data[hdr+7] ){
57261      checkAppendMsg(pCheck, 0,
57262          "Fragmentation of %d bytes reported as %d on page %d",
57263          cnt, data[hdr+7], iPage);
57264    }
57265  }
57266  sqlite3PageFree(hit);
57267  releasePage(pPage);
57268  return depth+1;
57269}
57270#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57271
57272#ifndef SQLITE_OMIT_INTEGRITY_CHECK
57273/*
57274** This routine does a complete check of the given BTree file.  aRoot[] is
57275** an array of pages numbers were each page number is the root page of
57276** a table.  nRoot is the number of entries in aRoot.
57277**
57278** A read-only or read-write transaction must be opened before calling
57279** this function.
57280**
57281** Write the number of error seen in *pnErr.  Except for some memory
57282** allocation errors,  an error message held in memory obtained from
57283** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
57284** returned.  If a memory allocation error occurs, NULL is returned.
57285*/
57286SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
57287  Btree *p,     /* The btree to be checked */
57288  int *aRoot,   /* An array of root pages numbers for individual trees */
57289  int nRoot,    /* Number of entries in aRoot[] */
57290  int mxErr,    /* Stop reporting errors after this many */
57291  int *pnErr    /* Write number of errors seen to this variable */
57292){
57293  Pgno i;
57294  int nRef;
57295  IntegrityCk sCheck;
57296  BtShared *pBt = p->pBt;
57297  char zErr[100];
57298
57299  sqlite3BtreeEnter(p);
57300  assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
57301  nRef = sqlite3PagerRefcount(pBt->pPager);
57302  sCheck.pBt = pBt;
57303  sCheck.pPager = pBt->pPager;
57304  sCheck.nPage = btreePagecount(sCheck.pBt);
57305  sCheck.mxErr = mxErr;
57306  sCheck.nErr = 0;
57307  sCheck.mallocFailed = 0;
57308  *pnErr = 0;
57309  if( sCheck.nPage==0 ){
57310    sqlite3BtreeLeave(p);
57311    return 0;
57312  }
57313  sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
57314  if( !sCheck.anRef ){
57315    *pnErr = 1;
57316    sqlite3BtreeLeave(p);
57317    return 0;
57318  }
57319  for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
57320  i = PENDING_BYTE_PAGE(pBt);
57321  if( i<=sCheck.nPage ){
57322    sCheck.anRef[i] = 1;
57323  }
57324  sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
57325  sCheck.errMsg.useMalloc = 2;
57326
57327  /* Check the integrity of the freelist
57328  */
57329  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
57330            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
57331
57332  /* Check all the tables.
57333  */
57334  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
57335    if( aRoot[i]==0 ) continue;
57336#ifndef SQLITE_OMIT_AUTOVACUUM
57337    if( pBt->autoVacuum && aRoot[i]>1 ){
57338      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
57339    }
57340#endif
57341    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
57342  }
57343
57344  /* Make sure every page in the file is referenced
57345  */
57346  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
57347#ifdef SQLITE_OMIT_AUTOVACUUM
57348    if( sCheck.anRef[i]==0 ){
57349      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57350    }
57351#else
57352    /* If the database supports auto-vacuum, make sure no tables contain
57353    ** references to pointer-map pages.
57354    */
57355    if( sCheck.anRef[i]==0 &&
57356       (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
57357      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57358    }
57359    if( sCheck.anRef[i]!=0 &&
57360       (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
57361      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
57362    }
57363#endif
57364  }
57365
57366  /* Make sure this analysis did not leave any unref() pages.
57367  ** This is an internal consistency check; an integrity check
57368  ** of the integrity check.
57369  */
57370  if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
57371    checkAppendMsg(&sCheck, 0,
57372      "Outstanding page count goes from %d to %d during this analysis",
57373      nRef, sqlite3PagerRefcount(pBt->pPager)
57374    );
57375  }
57376
57377  /* Clean  up and report errors.
57378  */
57379  sqlite3BtreeLeave(p);
57380  sqlite3_free(sCheck.anRef);
57381  if( sCheck.mallocFailed ){
57382    sqlite3StrAccumReset(&sCheck.errMsg);
57383    *pnErr = sCheck.nErr+1;
57384    return 0;
57385  }
57386  *pnErr = sCheck.nErr;
57387  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
57388  return sqlite3StrAccumFinish(&sCheck.errMsg);
57389}
57390#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57391
57392/*
57393** Return the full pathname of the underlying database file.
57394**
57395** The pager filename is invariant as long as the pager is
57396** open so it is safe to access without the BtShared mutex.
57397*/
57398SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
57399  assert( p->pBt->pPager!=0 );
57400  return sqlite3PagerFilename(p->pBt->pPager);
57401}
57402
57403/*
57404** Return the pathname of the journal file for this database. The return
57405** value of this routine is the same regardless of whether the journal file
57406** has been created or not.
57407**
57408** The pager journal filename is invariant as long as the pager is
57409** open so it is safe to access without the BtShared mutex.
57410*/
57411SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
57412  assert( p->pBt->pPager!=0 );
57413  return sqlite3PagerJournalname(p->pBt->pPager);
57414}
57415
57416/*
57417** Return non-zero if a transaction is active.
57418*/
57419SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
57420  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
57421  return (p && (p->inTrans==TRANS_WRITE));
57422}
57423
57424#ifndef SQLITE_OMIT_WAL
57425/*
57426** Run a checkpoint on the Btree passed as the first argument.
57427**
57428** Return SQLITE_LOCKED if this or any other connection has an open
57429** transaction on the shared-cache the argument Btree is connected to.
57430**
57431** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
57432*/
57433SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
57434  int rc = SQLITE_OK;
57435  if( p ){
57436    BtShared *pBt = p->pBt;
57437    sqlite3BtreeEnter(p);
57438    if( pBt->inTransaction!=TRANS_NONE ){
57439      rc = SQLITE_LOCKED;
57440    }else{
57441      rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
57442    }
57443    sqlite3BtreeLeave(p);
57444  }
57445  return rc;
57446}
57447#endif
57448
57449/*
57450** Return non-zero if a read (or write) transaction is active.
57451*/
57452SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
57453  assert( p );
57454  assert( sqlite3_mutex_held(p->db->mutex) );
57455  return p->inTrans!=TRANS_NONE;
57456}
57457
57458SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
57459  assert( p );
57460  assert( sqlite3_mutex_held(p->db->mutex) );
57461  return p->nBackup!=0;
57462}
57463
57464/*
57465** This function returns a pointer to a blob of memory associated with
57466** a single shared-btree. The memory is used by client code for its own
57467** purposes (for example, to store a high-level schema associated with
57468** the shared-btree). The btree layer manages reference counting issues.
57469**
57470** The first time this is called on a shared-btree, nBytes bytes of memory
57471** are allocated, zeroed, and returned to the caller. For each subsequent
57472** call the nBytes parameter is ignored and a pointer to the same blob
57473** of memory returned.
57474**
57475** If the nBytes parameter is 0 and the blob of memory has not yet been
57476** allocated, a null pointer is returned. If the blob has already been
57477** allocated, it is returned as normal.
57478**
57479** Just before the shared-btree is closed, the function passed as the
57480** xFree argument when the memory allocation was made is invoked on the
57481** blob of allocated memory. The xFree function should not call sqlite3_free()
57482** on the memory, the btree layer does that.
57483*/
57484SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
57485  BtShared *pBt = p->pBt;
57486  sqlite3BtreeEnter(p);
57487  if( !pBt->pSchema && nBytes ){
57488    pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
57489    pBt->xFreeSchema = xFree;
57490  }
57491  sqlite3BtreeLeave(p);
57492  return pBt->pSchema;
57493}
57494
57495/*
57496** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
57497** btree as the argument handle holds an exclusive lock on the
57498** sqlite_master table. Otherwise SQLITE_OK.
57499*/
57500SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
57501  int rc;
57502  assert( sqlite3_mutex_held(p->db->mutex) );
57503  sqlite3BtreeEnter(p);
57504  rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
57505  assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
57506  sqlite3BtreeLeave(p);
57507  return rc;
57508}
57509
57510
57511#ifndef SQLITE_OMIT_SHARED_CACHE
57512/*
57513** Obtain a lock on the table whose root page is iTab.  The
57514** lock is a write lock if isWritelock is true or a read lock
57515** if it is false.
57516*/
57517SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
57518  int rc = SQLITE_OK;
57519  assert( p->inTrans!=TRANS_NONE );
57520  if( p->sharable ){
57521    u8 lockType = READ_LOCK + isWriteLock;
57522    assert( READ_LOCK+1==WRITE_LOCK );
57523    assert( isWriteLock==0 || isWriteLock==1 );
57524
57525    sqlite3BtreeEnter(p);
57526    rc = querySharedCacheTableLock(p, iTab, lockType);
57527    if( rc==SQLITE_OK ){
57528      rc = setSharedCacheTableLock(p, iTab, lockType);
57529    }
57530    sqlite3BtreeLeave(p);
57531  }
57532  return rc;
57533}
57534#endif
57535
57536#ifndef SQLITE_OMIT_INCRBLOB
57537/*
57538** Argument pCsr must be a cursor opened for writing on an
57539** INTKEY table currently pointing at a valid table entry.
57540** This function modifies the data stored as part of that entry.
57541**
57542** Only the data content may only be modified, it is not possible to
57543** change the length of the data stored. If this function is called with
57544** parameters that attempt to write past the end of the existing data,
57545** no modifications are made and SQLITE_CORRUPT is returned.
57546*/
57547SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
57548  int rc;
57549  assert( cursorHoldsMutex(pCsr) );
57550  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
57551  assert( pCsr->isIncrblobHandle );
57552
57553  rc = restoreCursorPosition(pCsr);
57554  if( rc!=SQLITE_OK ){
57555    return rc;
57556  }
57557  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
57558  if( pCsr->eState!=CURSOR_VALID ){
57559    return SQLITE_ABORT;
57560  }
57561
57562  /* Check some assumptions:
57563  **   (a) the cursor is open for writing,
57564  **   (b) there is a read/write transaction open,
57565  **   (c) the connection holds a write-lock on the table (if required),
57566  **   (d) there are no conflicting read-locks, and
57567  **   (e) the cursor points at a valid row of an intKey table.
57568  */
57569  if( !pCsr->wrFlag ){
57570    return SQLITE_READONLY;
57571  }
57572  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
57573              && pCsr->pBt->inTransaction==TRANS_WRITE );
57574  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
57575  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
57576  assert( pCsr->apPage[pCsr->iPage]->intKey );
57577
57578  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
57579}
57580
57581/*
57582** Set a flag on this cursor to cache the locations of pages from the
57583** overflow list for the current row. This is used by cursors opened
57584** for incremental blob IO only.
57585**
57586** This function sets a flag only. The actual page location cache
57587** (stored in BtCursor.aOverflow[]) is allocated and used by function
57588** accessPayload() (the worker function for sqlite3BtreeData() and
57589** sqlite3BtreePutData()).
57590*/
57591SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
57592  assert( cursorHoldsMutex(pCur) );
57593  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57594  invalidateOverflowCache(pCur);
57595  pCur->isIncrblobHandle = 1;
57596}
57597#endif
57598
57599/*
57600** Set both the "read version" (single byte at byte offset 18) and
57601** "write version" (single byte at byte offset 19) fields in the database
57602** header to iVersion.
57603*/
57604SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
57605  BtShared *pBt = pBtree->pBt;
57606  int rc;                         /* Return code */
57607
57608  assert( iVersion==1 || iVersion==2 );
57609
57610  /* If setting the version fields to 1, do not automatically open the
57611  ** WAL connection, even if the version fields are currently set to 2.
57612  */
57613  pBt->btsFlags &= ~BTS_NO_WAL;
57614  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
57615
57616  rc = sqlite3BtreeBeginTrans(pBtree, 0);
57617  if( rc==SQLITE_OK ){
57618    u8 *aData = pBt->pPage1->aData;
57619    if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
57620      rc = sqlite3BtreeBeginTrans(pBtree, 2);
57621      if( rc==SQLITE_OK ){
57622        rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57623        if( rc==SQLITE_OK ){
57624          aData[18] = (u8)iVersion;
57625          aData[19] = (u8)iVersion;
57626        }
57627      }
57628    }
57629  }
57630
57631  pBt->btsFlags &= ~BTS_NO_WAL;
57632  return rc;
57633}
57634
57635/************** End of btree.c ***********************************************/
57636/************** Begin file backup.c ******************************************/
57637/*
57638** 2009 January 28
57639**
57640** The author disclaims copyright to this source code.  In place of
57641** a legal notice, here is a blessing:
57642**
57643**    May you do good and not evil.
57644**    May you find forgiveness for yourself and forgive others.
57645**    May you share freely, never taking more than you give.
57646**
57647*************************************************************************
57648** This file contains the implementation of the sqlite3_backup_XXX()
57649** API functions and the related features.
57650*/
57651
57652/* Macro to find the minimum of two numeric values.
57653*/
57654#ifndef MIN
57655# define MIN(x,y) ((x)<(y)?(x):(y))
57656#endif
57657
57658/*
57659** Structure allocated for each backup operation.
57660*/
57661struct sqlite3_backup {
57662  sqlite3* pDestDb;        /* Destination database handle */
57663  Btree *pDest;            /* Destination b-tree file */
57664  u32 iDestSchema;         /* Original schema cookie in destination */
57665  int bDestLocked;         /* True once a write-transaction is open on pDest */
57666
57667  Pgno iNext;              /* Page number of the next source page to copy */
57668  sqlite3* pSrcDb;         /* Source database handle */
57669  Btree *pSrc;             /* Source b-tree file */
57670
57671  int rc;                  /* Backup process error code */
57672
57673  /* These two variables are set by every call to backup_step(). They are
57674  ** read by calls to backup_remaining() and backup_pagecount().
57675  */
57676  Pgno nRemaining;         /* Number of pages left to copy */
57677  Pgno nPagecount;         /* Total number of pages to copy */
57678
57679  int isAttached;          /* True once backup has been registered with pager */
57680  sqlite3_backup *pNext;   /* Next backup associated with source pager */
57681};
57682
57683/*
57684** THREAD SAFETY NOTES:
57685**
57686**   Once it has been created using backup_init(), a single sqlite3_backup
57687**   structure may be accessed via two groups of thread-safe entry points:
57688**
57689**     * Via the sqlite3_backup_XXX() API function backup_step() and
57690**       backup_finish(). Both these functions obtain the source database
57691**       handle mutex and the mutex associated with the source BtShared
57692**       structure, in that order.
57693**
57694**     * Via the BackupUpdate() and BackupRestart() functions, which are
57695**       invoked by the pager layer to report various state changes in
57696**       the page cache associated with the source database. The mutex
57697**       associated with the source database BtShared structure will always
57698**       be held when either of these functions are invoked.
57699**
57700**   The other sqlite3_backup_XXX() API functions, backup_remaining() and
57701**   backup_pagecount() are not thread-safe functions. If they are called
57702**   while some other thread is calling backup_step() or backup_finish(),
57703**   the values returned may be invalid. There is no way for a call to
57704**   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
57705**   or backup_pagecount().
57706**
57707**   Depending on the SQLite configuration, the database handles and/or
57708**   the Btree objects may have their own mutexes that require locking.
57709**   Non-sharable Btrees (in-memory databases for example), do not have
57710**   associated mutexes.
57711*/
57712
57713/*
57714** Return a pointer corresponding to database zDb (i.e. "main", "temp")
57715** in connection handle pDb. If such a database cannot be found, return
57716** a NULL pointer and write an error message to pErrorDb.
57717**
57718** If the "temp" database is requested, it may need to be opened by this
57719** function. If an error occurs while doing so, return 0 and write an
57720** error message to pErrorDb.
57721*/
57722static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
57723  int i = sqlite3FindDbName(pDb, zDb);
57724
57725  if( i==1 ){
57726    Parse *pParse;
57727    int rc = 0;
57728    pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
57729    if( pParse==0 ){
57730      sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
57731      rc = SQLITE_NOMEM;
57732    }else{
57733      pParse->db = pDb;
57734      if( sqlite3OpenTempDatabase(pParse) ){
57735        sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
57736        rc = SQLITE_ERROR;
57737      }
57738      sqlite3DbFree(pErrorDb, pParse->zErrMsg);
57739      sqlite3StackFree(pErrorDb, pParse);
57740    }
57741    if( rc ){
57742      return 0;
57743    }
57744  }
57745
57746  if( i<0 ){
57747    sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
57748    return 0;
57749  }
57750
57751  return pDb->aDb[i].pBt;
57752}
57753
57754/*
57755** Attempt to set the page size of the destination to match the page size
57756** of the source.
57757*/
57758static int setDestPgsz(sqlite3_backup *p){
57759  int rc;
57760  rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
57761  return rc;
57762}
57763
57764/*
57765** Create an sqlite3_backup process to copy the contents of zSrcDb from
57766** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
57767** a pointer to the new sqlite3_backup object.
57768**
57769** If an error occurs, NULL is returned and an error code and error message
57770** stored in database handle pDestDb.
57771*/
57772SQLITE_API sqlite3_backup *sqlite3_backup_init(
57773  sqlite3* pDestDb,                     /* Database to write to */
57774  const char *zDestDb,                  /* Name of database within pDestDb */
57775  sqlite3* pSrcDb,                      /* Database connection to read from */
57776  const char *zSrcDb                    /* Name of database within pSrcDb */
57777){
57778  sqlite3_backup *p;                    /* Value to return */
57779
57780  /* Lock the source database handle. The destination database
57781  ** handle is not locked in this routine, but it is locked in
57782  ** sqlite3_backup_step(). The user is required to ensure that no
57783  ** other thread accesses the destination handle for the duration
57784  ** of the backup operation.  Any attempt to use the destination
57785  ** database connection while a backup is in progress may cause
57786  ** a malfunction or a deadlock.
57787  */
57788  sqlite3_mutex_enter(pSrcDb->mutex);
57789  sqlite3_mutex_enter(pDestDb->mutex);
57790
57791  if( pSrcDb==pDestDb ){
57792    sqlite3Error(
57793        pDestDb, SQLITE_ERROR, "source and destination must be distinct"
57794    );
57795    p = 0;
57796  }else {
57797    /* Allocate space for a new sqlite3_backup object...
57798    ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
57799    ** call to sqlite3_backup_init() and is destroyed by a call to
57800    ** sqlite3_backup_finish(). */
57801    p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
57802    if( !p ){
57803      sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
57804    }
57805  }
57806
57807  /* If the allocation succeeded, populate the new object. */
57808  if( p ){
57809    memset(p, 0, sizeof(sqlite3_backup));
57810    p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
57811    p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
57812    p->pDestDb = pDestDb;
57813    p->pSrcDb = pSrcDb;
57814    p->iNext = 1;
57815    p->isAttached = 0;
57816
57817    if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
57818      /* One (or both) of the named databases did not exist or an OOM
57819      ** error was hit.  The error has already been written into the
57820      ** pDestDb handle.  All that is left to do here is free the
57821      ** sqlite3_backup structure.
57822      */
57823      sqlite3_free(p);
57824      p = 0;
57825    }
57826  }
57827  if( p ){
57828    p->pSrc->nBackup++;
57829  }
57830
57831  sqlite3_mutex_leave(pDestDb->mutex);
57832  sqlite3_mutex_leave(pSrcDb->mutex);
57833  return p;
57834}
57835
57836/*
57837** Argument rc is an SQLite error code. Return true if this error is
57838** considered fatal if encountered during a backup operation. All errors
57839** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
57840*/
57841static int isFatalError(int rc){
57842  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
57843}
57844
57845/*
57846** Parameter zSrcData points to a buffer containing the data for
57847** page iSrcPg from the source database. Copy this data into the
57848** destination database.
57849*/
57850static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
57851  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
57852  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
57853  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
57854  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
57855  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
57856#ifdef SQLITE_HAS_CODEC
57857  int nSrcReserve = sqlite3BtreeGetReserve(p->pSrc);
57858  int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
57859#endif
57860
57861  int rc = SQLITE_OK;
57862  i64 iOff;
57863
57864  assert( p->bDestLocked );
57865  assert( !isFatalError(p->rc) );
57866  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
57867  assert( zSrcData );
57868
57869  /* Catch the case where the destination is an in-memory database and the
57870  ** page sizes of the source and destination differ.
57871  */
57872  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
57873    rc = SQLITE_READONLY;
57874  }
57875
57876#ifdef SQLITE_HAS_CODEC
57877  /* Backup is not possible if the page size of the destination is changing
57878  ** and a codec is in use.
57879  */
57880  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
57881    rc = SQLITE_READONLY;
57882  }
57883
57884  /* Backup is not possible if the number of bytes of reserve space differ
57885  ** between source and destination.  If there is a difference, try to
57886  ** fix the destination to agree with the source.  If that is not possible,
57887  ** then the backup cannot proceed.
57888  */
57889  if( nSrcReserve!=nDestReserve ){
57890    u32 newPgsz = nSrcPgsz;
57891    rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
57892    if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
57893  }
57894#endif
57895
57896  /* This loop runs once for each destination page spanned by the source
57897  ** page. For each iteration, variable iOff is set to the byte offset
57898  ** of the destination page.
57899  */
57900  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
57901    DbPage *pDestPg = 0;
57902    Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
57903    if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
57904    if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
57905     && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
57906    ){
57907      const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
57908      u8 *zDestData = sqlite3PagerGetData(pDestPg);
57909      u8 *zOut = &zDestData[iOff%nDestPgsz];
57910
57911      /* Copy the data from the source page into the destination page.
57912      ** Then clear the Btree layer MemPage.isInit flag. Both this module
57913      ** and the pager code use this trick (clearing the first byte
57914      ** of the page 'extra' space to invalidate the Btree layers
57915      ** cached parse of the page). MemPage.isInit is marked
57916      ** "MUST BE FIRST" for this purpose.
57917      */
57918      memcpy(zOut, zIn, nCopy);
57919      ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
57920    }
57921    sqlite3PagerUnref(pDestPg);
57922  }
57923
57924  return rc;
57925}
57926
57927/*
57928** If pFile is currently larger than iSize bytes, then truncate it to
57929** exactly iSize bytes. If pFile is not larger than iSize bytes, then
57930** this function is a no-op.
57931**
57932** Return SQLITE_OK if everything is successful, or an SQLite error
57933** code if an error occurs.
57934*/
57935static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
57936  i64 iCurrent;
57937  int rc = sqlite3OsFileSize(pFile, &iCurrent);
57938  if( rc==SQLITE_OK && iCurrent>iSize ){
57939    rc = sqlite3OsTruncate(pFile, iSize);
57940  }
57941  return rc;
57942}
57943
57944/*
57945** Register this backup object with the associated source pager for
57946** callbacks when pages are changed or the cache invalidated.
57947*/
57948static void attachBackupObject(sqlite3_backup *p){
57949  sqlite3_backup **pp;
57950  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
57951  pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
57952  p->pNext = *pp;
57953  *pp = p;
57954  p->isAttached = 1;
57955}
57956
57957/*
57958** Copy nPage pages from the source b-tree to the destination.
57959*/
57960SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
57961  int rc;
57962  int destMode;       /* Destination journal mode */
57963  int pgszSrc = 0;    /* Source page size */
57964  int pgszDest = 0;   /* Destination page size */
57965
57966  sqlite3_mutex_enter(p->pSrcDb->mutex);
57967  sqlite3BtreeEnter(p->pSrc);
57968  if( p->pDestDb ){
57969    sqlite3_mutex_enter(p->pDestDb->mutex);
57970  }
57971
57972  rc = p->rc;
57973  if( !isFatalError(rc) ){
57974    Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
57975    Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
57976    int ii;                            /* Iterator variable */
57977    int nSrcPage = -1;                 /* Size of source db in pages */
57978    int bCloseTrans = 0;               /* True if src db requires unlocking */
57979
57980    /* If the source pager is currently in a write-transaction, return
57981    ** SQLITE_BUSY immediately.
57982    */
57983    if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
57984      rc = SQLITE_BUSY;
57985    }else{
57986      rc = SQLITE_OK;
57987    }
57988
57989    /* Lock the destination database, if it is not locked already. */
57990    if( SQLITE_OK==rc && p->bDestLocked==0
57991     && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
57992    ){
57993      p->bDestLocked = 1;
57994      sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
57995    }
57996
57997    /* If there is no open read-transaction on the source database, open
57998    ** one now. If a transaction is opened here, then it will be closed
57999    ** before this function exits.
58000    */
58001    if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
58002      rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
58003      bCloseTrans = 1;
58004    }
58005
58006    /* Do not allow backup if the destination database is in WAL mode
58007    ** and the page sizes are different between source and destination */
58008    pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
58009    pgszDest = sqlite3BtreeGetPageSize(p->pDest);
58010    destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
58011    if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
58012      rc = SQLITE_READONLY;
58013    }
58014
58015    /* Now that there is a read-lock on the source database, query the
58016    ** source pager for the number of pages in the database.
58017    */
58018    nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
58019    assert( nSrcPage>=0 );
58020    for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
58021      const Pgno iSrcPg = p->iNext;                 /* Source page number */
58022      if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
58023        DbPage *pSrcPg;                             /* Source page object */
58024        rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58025        if( rc==SQLITE_OK ){
58026          rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
58027          sqlite3PagerUnref(pSrcPg);
58028        }
58029      }
58030      p->iNext++;
58031    }
58032    if( rc==SQLITE_OK ){
58033      p->nPagecount = nSrcPage;
58034      p->nRemaining = nSrcPage+1-p->iNext;
58035      if( p->iNext>(Pgno)nSrcPage ){
58036        rc = SQLITE_DONE;
58037      }else if( !p->isAttached ){
58038        attachBackupObject(p);
58039      }
58040    }
58041
58042    /* Update the schema version field in the destination database. This
58043    ** is to make sure that the schema-version really does change in
58044    ** the case where the source and destination databases have the
58045    ** same schema version.
58046    */
58047    if( rc==SQLITE_DONE ){
58048      rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
58049      if( rc==SQLITE_OK ){
58050        if( p->pDestDb ){
58051          sqlite3ResetInternalSchema(p->pDestDb, -1);
58052        }
58053        if( destMode==PAGER_JOURNALMODE_WAL ){
58054          rc = sqlite3BtreeSetVersion(p->pDest, 2);
58055        }
58056      }
58057      if( rc==SQLITE_OK ){
58058        int nDestTruncate;
58059        /* Set nDestTruncate to the final number of pages in the destination
58060        ** database. The complication here is that the destination page
58061        ** size may be different to the source page size.
58062        **
58063        ** If the source page size is smaller than the destination page size,
58064        ** round up. In this case the call to sqlite3OsTruncate() below will
58065        ** fix the size of the file. However it is important to call
58066        ** sqlite3PagerTruncateImage() here so that any pages in the
58067        ** destination file that lie beyond the nDestTruncate page mark are
58068        ** journalled by PagerCommitPhaseOne() before they are destroyed
58069        ** by the file truncation.
58070        */
58071        assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
58072        assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
58073        if( pgszSrc<pgszDest ){
58074          int ratio = pgszDest/pgszSrc;
58075          nDestTruncate = (nSrcPage+ratio-1)/ratio;
58076          if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
58077            nDestTruncate--;
58078          }
58079        }else{
58080          nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
58081        }
58082        sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
58083
58084        if( pgszSrc<pgszDest ){
58085          /* If the source page-size is smaller than the destination page-size,
58086          ** two extra things may need to happen:
58087          **
58088          **   * The destination may need to be truncated, and
58089          **
58090          **   * Data stored on the pages immediately following the
58091          **     pending-byte page in the source database may need to be
58092          **     copied into the destination database.
58093          */
58094          const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
58095          sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
58096          i64 iOff;
58097          i64 iEnd;
58098
58099          assert( pFile );
58100          assert( (i64)nDestTruncate*(i64)pgszDest >= iSize || (
58101                nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
58102             && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
58103          ));
58104
58105          /* This call ensures that all data required to recreate the original
58106          ** database has been stored in the journal for pDestPager and the
58107          ** journal synced to disk. So at this point we may safely modify
58108          ** the database file in any way, knowing that if a power failure
58109          ** occurs, the original database will be reconstructed from the
58110          ** journal file.  */
58111          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
58112
58113          /* Write the extra pages and truncate the database file as required */
58114          iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
58115          for(
58116            iOff=PENDING_BYTE+pgszSrc;
58117            rc==SQLITE_OK && iOff<iEnd;
58118            iOff+=pgszSrc
58119          ){
58120            PgHdr *pSrcPg = 0;
58121            const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
58122            rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58123            if( rc==SQLITE_OK ){
58124              u8 *zData = sqlite3PagerGetData(pSrcPg);
58125              rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
58126            }
58127            sqlite3PagerUnref(pSrcPg);
58128          }
58129          if( rc==SQLITE_OK ){
58130            rc = backupTruncateFile(pFile, iSize);
58131          }
58132
58133          /* Sync the database file to disk. */
58134          if( rc==SQLITE_OK ){
58135            rc = sqlite3PagerSync(pDestPager);
58136          }
58137        }else{
58138          rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
58139        }
58140
58141        /* Finish committing the transaction to the destination database. */
58142        if( SQLITE_OK==rc
58143         && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
58144        ){
58145          rc = SQLITE_DONE;
58146        }
58147      }
58148    }
58149
58150    /* If bCloseTrans is true, then this function opened a read transaction
58151    ** on the source database. Close the read transaction here. There is
58152    ** no need to check the return values of the btree methods here, as
58153    ** "committing" a read-only transaction cannot fail.
58154    */
58155    if( bCloseTrans ){
58156      TESTONLY( int rc2 );
58157      TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
58158      TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
58159      assert( rc2==SQLITE_OK );
58160    }
58161
58162    if( rc==SQLITE_IOERR_NOMEM ){
58163      rc = SQLITE_NOMEM;
58164    }
58165    p->rc = rc;
58166  }
58167  if( p->pDestDb ){
58168    sqlite3_mutex_leave(p->pDestDb->mutex);
58169  }
58170  sqlite3BtreeLeave(p->pSrc);
58171  sqlite3_mutex_leave(p->pSrcDb->mutex);
58172  return rc;
58173}
58174
58175/*
58176** Release all resources associated with an sqlite3_backup* handle.
58177*/
58178SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
58179  sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
58180  MUTEX_LOGIC( sqlite3_mutex *mutex; ) /* Mutex to protect source database */
58181  int rc;                              /* Value to return */
58182
58183  /* Enter the mutexes */
58184  if( p==0 ) return SQLITE_OK;
58185  sqlite3_mutex_enter(p->pSrcDb->mutex);
58186  sqlite3BtreeEnter(p->pSrc);
58187  MUTEX_LOGIC( mutex = p->pSrcDb->mutex; )
58188  if( p->pDestDb ){
58189    sqlite3_mutex_enter(p->pDestDb->mutex);
58190  }
58191
58192  /* Detach this backup from the source pager. */
58193  if( p->pDestDb ){
58194    p->pSrc->nBackup--;
58195  }
58196  if( p->isAttached ){
58197    pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58198    while( *pp!=p ){
58199      pp = &(*pp)->pNext;
58200    }
58201    *pp = p->pNext;
58202  }
58203
58204  /* If a transaction is still open on the Btree, roll it back. */
58205  sqlite3BtreeRollback(p->pDest, SQLITE_OK);
58206
58207  /* Set the error code of the destination database handle. */
58208  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
58209  sqlite3Error(p->pDestDb, rc, 0);
58210
58211  /* Exit the mutexes and free the backup context structure. */
58212  if( p->pDestDb ){
58213    sqlite3_mutex_leave(p->pDestDb->mutex);
58214  }
58215  sqlite3BtreeLeave(p->pSrc);
58216  if( p->pDestDb ){
58217    /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58218    ** call to sqlite3_backup_init() and is destroyed by a call to
58219    ** sqlite3_backup_finish(). */
58220    sqlite3_free(p);
58221  }
58222  sqlite3_mutex_leave(mutex);
58223  return rc;
58224}
58225
58226/*
58227** Return the number of pages still to be backed up as of the most recent
58228** call to sqlite3_backup_step().
58229*/
58230SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
58231  return p->nRemaining;
58232}
58233
58234/*
58235** Return the total number of pages in the source database as of the most
58236** recent call to sqlite3_backup_step().
58237*/
58238SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
58239  return p->nPagecount;
58240}
58241
58242/*
58243** This function is called after the contents of page iPage of the
58244** source database have been modified. If page iPage has already been
58245** copied into the destination database, then the data written to the
58246** destination is now invalidated. The destination copy of iPage needs
58247** to be updated with the new data before the backup operation is
58248** complete.
58249**
58250** It is assumed that the mutex associated with the BtShared object
58251** corresponding to the source database is held when this function is
58252** called.
58253*/
58254SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
58255  sqlite3_backup *p;                   /* Iterator variable */
58256  for(p=pBackup; p; p=p->pNext){
58257    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58258    if( !isFatalError(p->rc) && iPage<p->iNext ){
58259      /* The backup process p has already copied page iPage. But now it
58260      ** has been modified by a transaction on the source pager. Copy
58261      ** the new data into the backup.
58262      */
58263      int rc;
58264      assert( p->pDestDb );
58265      sqlite3_mutex_enter(p->pDestDb->mutex);
58266      rc = backupOnePage(p, iPage, aData);
58267      sqlite3_mutex_leave(p->pDestDb->mutex);
58268      assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
58269      if( rc!=SQLITE_OK ){
58270        p->rc = rc;
58271      }
58272    }
58273  }
58274}
58275
58276/*
58277** Restart the backup process. This is called when the pager layer
58278** detects that the database has been modified by an external database
58279** connection. In this case there is no way of knowing which of the
58280** pages that have been copied into the destination database are still
58281** valid and which are not, so the entire process needs to be restarted.
58282**
58283** It is assumed that the mutex associated with the BtShared object
58284** corresponding to the source database is held when this function is
58285** called.
58286*/
58287SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
58288  sqlite3_backup *p;                   /* Iterator variable */
58289  for(p=pBackup; p; p=p->pNext){
58290    assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58291    p->iNext = 1;
58292  }
58293}
58294
58295#ifndef SQLITE_OMIT_VACUUM
58296/*
58297** Copy the complete content of pBtFrom into pBtTo.  A transaction
58298** must be active for both files.
58299**
58300** The size of file pTo may be reduced by this operation. If anything
58301** goes wrong, the transaction on pTo is rolled back. If successful, the
58302** transaction is committed before returning.
58303*/
58304SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
58305  int rc;
58306  sqlite3_file *pFd;              /* File descriptor for database pTo */
58307  sqlite3_backup b;
58308  sqlite3BtreeEnter(pTo);
58309  sqlite3BtreeEnter(pFrom);
58310
58311  assert( sqlite3BtreeIsInTrans(pTo) );
58312  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
58313  if( pFd->pMethods ){
58314    i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
58315    rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
58316    if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
58317    if( rc ) goto copy_finished;
58318  }
58319
58320  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
58321  ** to 0. This is used by the implementations of sqlite3_backup_step()
58322  ** and sqlite3_backup_finish() to detect that they are being called
58323  ** from this function, not directly by the user.
58324  */
58325  memset(&b, 0, sizeof(b));
58326  b.pSrcDb = pFrom->db;
58327  b.pSrc = pFrom;
58328  b.pDest = pTo;
58329  b.iNext = 1;
58330
58331  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
58332  ** file. By passing this as the number of pages to copy to
58333  ** sqlite3_backup_step(), we can guarantee that the copy finishes
58334  ** within a single call (unless an error occurs). The assert() statement
58335  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
58336  ** or an error code.
58337  */
58338  sqlite3_backup_step(&b, 0x7FFFFFFF);
58339  assert( b.rc!=SQLITE_OK );
58340  rc = sqlite3_backup_finish(&b);
58341  if( rc==SQLITE_OK ){
58342    pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
58343  }else{
58344    sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
58345  }
58346
58347  assert( sqlite3BtreeIsInTrans(pTo)==0 );
58348copy_finished:
58349  sqlite3BtreeLeave(pFrom);
58350  sqlite3BtreeLeave(pTo);
58351  return rc;
58352}
58353#endif /* SQLITE_OMIT_VACUUM */
58354
58355/************** End of backup.c **********************************************/
58356/************** Begin file vdbemem.c *****************************************/
58357/*
58358** 2004 May 26
58359**
58360** The author disclaims copyright to this source code.  In place of
58361** a legal notice, here is a blessing:
58362**
58363**    May you do good and not evil.
58364**    May you find forgiveness for yourself and forgive others.
58365**    May you share freely, never taking more than you give.
58366**
58367*************************************************************************
58368**
58369** This file contains code use to manipulate "Mem" structure.  A "Mem"
58370** stores a single value in the VDBE.  Mem is an opaque structure visible
58371** only within the VDBE.  Interface routines refer to a Mem using the
58372** name sqlite_value
58373*/
58374
58375/*
58376** If pMem is an object with a valid string representation, this routine
58377** ensures the internal encoding for the string representation is
58378** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
58379**
58380** If pMem is not a string object, or the encoding of the string
58381** representation is already stored using the requested encoding, then this
58382** routine is a no-op.
58383**
58384** SQLITE_OK is returned if the conversion is successful (or not required).
58385** SQLITE_NOMEM may be returned if a malloc() fails during conversion
58386** between formats.
58387*/
58388SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
58389  int rc;
58390  assert( (pMem->flags&MEM_RowSet)==0 );
58391  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
58392           || desiredEnc==SQLITE_UTF16BE );
58393  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
58394    return SQLITE_OK;
58395  }
58396  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58397#ifdef SQLITE_OMIT_UTF16
58398  return SQLITE_ERROR;
58399#else
58400
58401  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
58402  ** then the encoding of the value may not have changed.
58403  */
58404  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
58405  assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
58406  assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
58407  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
58408  return rc;
58409#endif
58410}
58411
58412/*
58413** Make sure pMem->z points to a writable allocation of at least
58414** n bytes.
58415**
58416** If the memory cell currently contains string or blob data
58417** and the third argument passed to this function is true, the
58418** current content of the cell is preserved. Otherwise, it may
58419** be discarded.
58420**
58421** This function sets the MEM_Dyn flag and clears any xDel callback.
58422** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
58423** not set, Mem.n is zeroed.
58424*/
58425SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
58426  assert( 1 >=
58427    ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
58428    (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
58429    ((pMem->flags&MEM_Ephem) ? 1 : 0) +
58430    ((pMem->flags&MEM_Static) ? 1 : 0)
58431  );
58432  assert( (pMem->flags&MEM_RowSet)==0 );
58433
58434  if( n<32 ) n = 32;
58435  if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
58436    if( preserve && pMem->z==pMem->zMalloc ){
58437      pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
58438      preserve = 0;
58439    }else{
58440      sqlite3DbFree(pMem->db, pMem->zMalloc);
58441      pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
58442    }
58443  }
58444
58445  if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
58446    memcpy(pMem->zMalloc, pMem->z, pMem->n);
58447  }
58448  if( pMem->flags&MEM_Dyn && pMem->xDel ){
58449    assert( pMem->xDel!=SQLITE_DYNAMIC );
58450    pMem->xDel((void *)(pMem->z));
58451  }
58452
58453  pMem->z = pMem->zMalloc;
58454  if( pMem->z==0 ){
58455    pMem->flags = MEM_Null;
58456  }else{
58457    pMem->flags &= ~(MEM_Ephem|MEM_Static);
58458  }
58459  pMem->xDel = 0;
58460  return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
58461}
58462
58463/*
58464** Make the given Mem object MEM_Dyn.  In other words, make it so
58465** that any TEXT or BLOB content is stored in memory obtained from
58466** malloc().  In this way, we know that the memory is safe to be
58467** overwritten or altered.
58468**
58469** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
58470*/
58471SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
58472  int f;
58473  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58474  assert( (pMem->flags&MEM_RowSet)==0 );
58475  ExpandBlob(pMem);
58476  f = pMem->flags;
58477  if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
58478    if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
58479      return SQLITE_NOMEM;
58480    }
58481    pMem->z[pMem->n] = 0;
58482    pMem->z[pMem->n+1] = 0;
58483    pMem->flags |= MEM_Term;
58484#ifdef SQLITE_DEBUG
58485    pMem->pScopyFrom = 0;
58486#endif
58487  }
58488
58489  return SQLITE_OK;
58490}
58491
58492/*
58493** If the given Mem* has a zero-filled tail, turn it into an ordinary
58494** blob stored in dynamically allocated space.
58495*/
58496#ifndef SQLITE_OMIT_INCRBLOB
58497SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
58498  if( pMem->flags & MEM_Zero ){
58499    int nByte;
58500    assert( pMem->flags&MEM_Blob );
58501    assert( (pMem->flags&MEM_RowSet)==0 );
58502    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58503
58504    /* Set nByte to the number of bytes required to store the expanded blob. */
58505    nByte = pMem->n + pMem->u.nZero;
58506    if( nByte<=0 ){
58507      nByte = 1;
58508    }
58509    if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
58510      return SQLITE_NOMEM;
58511    }
58512
58513    memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
58514    pMem->n += pMem->u.nZero;
58515    pMem->flags &= ~(MEM_Zero|MEM_Term);
58516  }
58517  return SQLITE_OK;
58518}
58519#endif
58520
58521
58522/*
58523** Make sure the given Mem is \u0000 terminated.
58524*/
58525SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
58526  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58527  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
58528    return SQLITE_OK;   /* Nothing to do */
58529  }
58530  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
58531    return SQLITE_NOMEM;
58532  }
58533  pMem->z[pMem->n] = 0;
58534  pMem->z[pMem->n+1] = 0;
58535  pMem->flags |= MEM_Term;
58536  return SQLITE_OK;
58537}
58538
58539/*
58540** Add MEM_Str to the set of representations for the given Mem.  Numbers
58541** are converted using sqlite3_snprintf().  Converting a BLOB to a string
58542** is a no-op.
58543**
58544** Existing representations MEM_Int and MEM_Real are *not* invalidated.
58545**
58546** A MEM_Null value will never be passed to this function. This function is
58547** used for converting values to text for returning to the user (i.e. via
58548** sqlite3_value_text()), or for ensuring that values to be used as btree
58549** keys are strings. In the former case a NULL pointer is returned the
58550** user and the later is an internal programming error.
58551*/
58552SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
58553  int rc = SQLITE_OK;
58554  int fg = pMem->flags;
58555  const int nByte = 32;
58556
58557  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58558  assert( !(fg&MEM_Zero) );
58559  assert( !(fg&(MEM_Str|MEM_Blob)) );
58560  assert( fg&(MEM_Int|MEM_Real) );
58561  assert( (pMem->flags&MEM_RowSet)==0 );
58562  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58563
58564
58565  if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
58566    return SQLITE_NOMEM;
58567  }
58568
58569  /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
58570  ** string representation of the value. Then, if the required encoding
58571  ** is UTF-16le or UTF-16be do a translation.
58572  **
58573  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
58574  */
58575  if( fg & MEM_Int ){
58576    sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
58577  }else{
58578    assert( fg & MEM_Real );
58579    sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
58580  }
58581  pMem->n = sqlite3Strlen30(pMem->z);
58582  pMem->enc = SQLITE_UTF8;
58583  pMem->flags |= MEM_Str|MEM_Term;
58584  sqlite3VdbeChangeEncoding(pMem, enc);
58585  return rc;
58586}
58587
58588/*
58589** Memory cell pMem contains the context of an aggregate function.
58590** This routine calls the finalize method for that function.  The
58591** result of the aggregate is stored back into pMem.
58592**
58593** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
58594** otherwise.
58595*/
58596SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
58597  int rc = SQLITE_OK;
58598  if( ALWAYS(pFunc && pFunc->xFinalize) ){
58599    sqlite3_context ctx;
58600    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
58601    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58602    memset(&ctx, 0, sizeof(ctx));
58603    ctx.s.flags = MEM_Null;
58604    ctx.s.db = pMem->db;
58605    ctx.pMem = pMem;
58606    ctx.pFunc = pFunc;
58607    pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
58608    assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
58609    sqlite3DbFree(pMem->db, pMem->zMalloc);
58610    memcpy(pMem, &ctx.s, sizeof(ctx.s));
58611    rc = ctx.isError;
58612  }
58613  return rc;
58614}
58615
58616/*
58617** If the memory cell contains a string value that must be freed by
58618** invoking an external callback, free it now. Calling this function
58619** does not free any Mem.zMalloc buffer.
58620*/
58621SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
58622  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
58623  if( p->flags&MEM_Agg ){
58624    sqlite3VdbeMemFinalize(p, p->u.pDef);
58625    assert( (p->flags & MEM_Agg)==0 );
58626    sqlite3VdbeMemRelease(p);
58627  }else if( p->flags&MEM_Dyn && p->xDel ){
58628    assert( (p->flags&MEM_RowSet)==0 );
58629    assert( p->xDel!=SQLITE_DYNAMIC );
58630    p->xDel((void *)p->z);
58631    p->xDel = 0;
58632  }else if( p->flags&MEM_RowSet ){
58633    sqlite3RowSetClear(p->u.pRowSet);
58634  }else if( p->flags&MEM_Frame ){
58635    sqlite3VdbeMemSetNull(p);
58636  }
58637}
58638
58639/*
58640** Release any memory held by the Mem. This may leave the Mem in an
58641** inconsistent state, for example with (Mem.z==0) and
58642** (Mem.type==SQLITE_TEXT).
58643*/
58644SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
58645  VdbeMemRelease(p);
58646  sqlite3DbFree(p->db, p->zMalloc);
58647  p->z = 0;
58648  p->zMalloc = 0;
58649  p->xDel = 0;
58650}
58651
58652/*
58653** Convert a 64-bit IEEE double into a 64-bit signed integer.
58654** If the double is too large, return 0x8000000000000000.
58655**
58656** Most systems appear to do this simply by assigning
58657** variables and without the extra range tests.  But
58658** there are reports that windows throws an expection
58659** if the floating point value is out of range. (See ticket #2880.)
58660** Because we do not completely understand the problem, we will
58661** take the conservative approach and always do range tests
58662** before attempting the conversion.
58663*/
58664static i64 doubleToInt64(double r){
58665#ifdef SQLITE_OMIT_FLOATING_POINT
58666  /* When floating-point is omitted, double and int64 are the same thing */
58667  return r;
58668#else
58669  /*
58670  ** Many compilers we encounter do not define constants for the
58671  ** minimum and maximum 64-bit integers, or they define them
58672  ** inconsistently.  And many do not understand the "LL" notation.
58673  ** So we define our own static constants here using nothing
58674  ** larger than a 32-bit integer constant.
58675  */
58676  static const i64 maxInt = LARGEST_INT64;
58677  static const i64 minInt = SMALLEST_INT64;
58678
58679  if( r<(double)minInt ){
58680    return minInt;
58681  }else if( r>(double)maxInt ){
58682    /* minInt is correct here - not maxInt.  It turns out that assigning
58683    ** a very large positive number to an integer results in a very large
58684    ** negative integer.  This makes no sense, but it is what x86 hardware
58685    ** does so for compatibility we will do the same in software. */
58686    return minInt;
58687  }else{
58688    return (i64)r;
58689  }
58690#endif
58691}
58692
58693/*
58694** Return some kind of integer value which is the best we can do
58695** at representing the value that *pMem describes as an integer.
58696** If pMem is an integer, then the value is exact.  If pMem is
58697** a floating-point then the value returned is the integer part.
58698** If pMem is a string or blob, then we make an attempt to convert
58699** it into a integer and return that.  If pMem represents an
58700** an SQL-NULL value, return 0.
58701**
58702** If pMem represents a string value, its encoding might be changed.
58703*/
58704SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
58705  int flags;
58706  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58707  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58708  flags = pMem->flags;
58709  if( flags & MEM_Int ){
58710    return pMem->u.i;
58711  }else if( flags & MEM_Real ){
58712    return doubleToInt64(pMem->r);
58713  }else if( flags & (MEM_Str|MEM_Blob) ){
58714    i64 value = 0;
58715    assert( pMem->z || pMem->n==0 );
58716    testcase( pMem->z==0 );
58717    sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
58718    return value;
58719  }else{
58720    return 0;
58721  }
58722}
58723
58724/*
58725** Return the best representation of pMem that we can get into a
58726** double.  If pMem is already a double or an integer, return its
58727** value.  If it is a string or blob, try to convert it to a double.
58728** If it is a NULL, return 0.0.
58729*/
58730SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
58731  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58732  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58733  if( pMem->flags & MEM_Real ){
58734    return pMem->r;
58735  }else if( pMem->flags & MEM_Int ){
58736    return (double)pMem->u.i;
58737  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
58738    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
58739    double val = (double)0;
58740    sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
58741    return val;
58742  }else{
58743    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
58744    return (double)0;
58745  }
58746}
58747
58748/*
58749** The MEM structure is already a MEM_Real.  Try to also make it a
58750** MEM_Int if we can.
58751*/
58752SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
58753  assert( pMem->flags & MEM_Real );
58754  assert( (pMem->flags & MEM_RowSet)==0 );
58755  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58756  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58757
58758  pMem->u.i = doubleToInt64(pMem->r);
58759
58760  /* Only mark the value as an integer if
58761  **
58762  **    (1) the round-trip conversion real->int->real is a no-op, and
58763  **    (2) The integer is neither the largest nor the smallest
58764  **        possible integer (ticket #3922)
58765  **
58766  ** The second and third terms in the following conditional enforces
58767  ** the second condition under the assumption that addition overflow causes
58768  ** values to wrap around.  On x86 hardware, the third term is always
58769  ** true and could be omitted.  But we leave it in because other
58770  ** architectures might behave differently.
58771  */
58772  if( pMem->r==(double)pMem->u.i
58773   && pMem->u.i>SMALLEST_INT64
58774#if defined(__i486__) || defined(__x86_64__)
58775   && ALWAYS(pMem->u.i<LARGEST_INT64)
58776#else
58777   && pMem->u.i<LARGEST_INT64
58778#endif
58779  ){
58780    pMem->flags |= MEM_Int;
58781  }
58782}
58783
58784/*
58785** Convert pMem to type integer.  Invalidate any prior representations.
58786*/
58787SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
58788  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58789  assert( (pMem->flags & MEM_RowSet)==0 );
58790  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58791
58792  pMem->u.i = sqlite3VdbeIntValue(pMem);
58793  MemSetTypeFlag(pMem, MEM_Int);
58794  return SQLITE_OK;
58795}
58796
58797/*
58798** Convert pMem so that it is of type MEM_Real.
58799** Invalidate any prior representations.
58800*/
58801SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
58802  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58803  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
58804
58805  pMem->r = sqlite3VdbeRealValue(pMem);
58806  MemSetTypeFlag(pMem, MEM_Real);
58807  return SQLITE_OK;
58808}
58809
58810/*
58811** Convert pMem so that it has types MEM_Real or MEM_Int or both.
58812** Invalidate any prior representations.
58813**
58814** Every effort is made to force the conversion, even if the input
58815** is a string that does not look completely like a number.  Convert
58816** as much of the string as we can and ignore the rest.
58817*/
58818SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
58819  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
58820    assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
58821    assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58822    if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
58823      MemSetTypeFlag(pMem, MEM_Int);
58824    }else{
58825      pMem->r = sqlite3VdbeRealValue(pMem);
58826      MemSetTypeFlag(pMem, MEM_Real);
58827      sqlite3VdbeIntegerAffinity(pMem);
58828    }
58829  }
58830  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
58831  pMem->flags &= ~(MEM_Str|MEM_Blob);
58832  return SQLITE_OK;
58833}
58834
58835/*
58836** Delete any previous value and set the value stored in *pMem to NULL.
58837*/
58838SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
58839  if( pMem->flags & MEM_Frame ){
58840    VdbeFrame *pFrame = pMem->u.pFrame;
58841    pFrame->pParent = pFrame->v->pDelFrame;
58842    pFrame->v->pDelFrame = pFrame;
58843  }
58844  if( pMem->flags & MEM_RowSet ){
58845    sqlite3RowSetClear(pMem->u.pRowSet);
58846  }
58847  MemSetTypeFlag(pMem, MEM_Null);
58848  pMem->type = SQLITE_NULL;
58849}
58850
58851/*
58852** Delete any previous value and set the value to be a BLOB of length
58853** n containing all zeros.
58854*/
58855SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
58856  sqlite3VdbeMemRelease(pMem);
58857  pMem->flags = MEM_Blob|MEM_Zero;
58858  pMem->type = SQLITE_BLOB;
58859  pMem->n = 0;
58860  if( n<0 ) n = 0;
58861  pMem->u.nZero = n;
58862  pMem->enc = SQLITE_UTF8;
58863
58864#ifdef SQLITE_OMIT_INCRBLOB
58865  sqlite3VdbeMemGrow(pMem, n, 0);
58866  if( pMem->z ){
58867    pMem->n = n;
58868    memset(pMem->z, 0, n);
58869  }
58870#endif
58871}
58872
58873/*
58874** Delete any previous value and set the value stored in *pMem to val,
58875** manifest type INTEGER.
58876*/
58877SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
58878  sqlite3VdbeMemRelease(pMem);
58879  pMem->u.i = val;
58880  pMem->flags = MEM_Int;
58881  pMem->type = SQLITE_INTEGER;
58882}
58883
58884#ifndef SQLITE_OMIT_FLOATING_POINT
58885/*
58886** Delete any previous value and set the value stored in *pMem to val,
58887** manifest type REAL.
58888*/
58889SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
58890  if( sqlite3IsNaN(val) ){
58891    sqlite3VdbeMemSetNull(pMem);
58892  }else{
58893    sqlite3VdbeMemRelease(pMem);
58894    pMem->r = val;
58895    pMem->flags = MEM_Real;
58896    pMem->type = SQLITE_FLOAT;
58897  }
58898}
58899#endif
58900
58901/*
58902** Delete any previous value and set the value of pMem to be an
58903** empty boolean index.
58904*/
58905SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
58906  sqlite3 *db = pMem->db;
58907  assert( db!=0 );
58908  assert( (pMem->flags & MEM_RowSet)==0 );
58909  sqlite3VdbeMemRelease(pMem);
58910  pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
58911  if( db->mallocFailed ){
58912    pMem->flags = MEM_Null;
58913  }else{
58914    assert( pMem->zMalloc );
58915    pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
58916                                       sqlite3DbMallocSize(db, pMem->zMalloc));
58917    assert( pMem->u.pRowSet!=0 );
58918    pMem->flags = MEM_RowSet;
58919  }
58920}
58921
58922/*
58923** Return true if the Mem object contains a TEXT or BLOB that is
58924** too large - whose size exceeds SQLITE_MAX_LENGTH.
58925*/
58926SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
58927  assert( p->db!=0 );
58928  if( p->flags & (MEM_Str|MEM_Blob) ){
58929    int n = p->n;
58930    if( p->flags & MEM_Zero ){
58931      n += p->u.nZero;
58932    }
58933    return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
58934  }
58935  return 0;
58936}
58937
58938#ifdef SQLITE_DEBUG
58939/*
58940** This routine prepares a memory cell for modication by breaking
58941** its link to a shallow copy and by marking any current shallow
58942** copies of this cell as invalid.
58943**
58944** This is used for testing and debugging only - to make sure shallow
58945** copies are not misused.
58946*/
58947SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
58948  int i;
58949  Mem *pX;
58950  for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
58951    if( pX->pScopyFrom==pMem ){
58952      pX->flags |= MEM_Invalid;
58953      pX->pScopyFrom = 0;
58954    }
58955  }
58956  pMem->pScopyFrom = 0;
58957}
58958#endif /* SQLITE_DEBUG */
58959
58960/*
58961** Size of struct Mem not including the Mem.zMalloc member.
58962*/
58963#define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
58964
58965/*
58966** Make an shallow copy of pFrom into pTo.  Prior contents of
58967** pTo are freed.  The pFrom->z field is not duplicated.  If
58968** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
58969** and flags gets srcType (either MEM_Ephem or MEM_Static).
58970*/
58971SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
58972  assert( (pFrom->flags & MEM_RowSet)==0 );
58973  VdbeMemRelease(pTo);
58974  memcpy(pTo, pFrom, MEMCELLSIZE);
58975  pTo->xDel = 0;
58976  if( (pFrom->flags&MEM_Static)==0 ){
58977    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
58978    assert( srcType==MEM_Ephem || srcType==MEM_Static );
58979    pTo->flags |= srcType;
58980  }
58981}
58982
58983/*
58984** Make a full copy of pFrom into pTo.  Prior contents of pTo are
58985** freed before the copy is made.
58986*/
58987SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
58988  int rc = SQLITE_OK;
58989
58990  assert( (pFrom->flags & MEM_RowSet)==0 );
58991  VdbeMemRelease(pTo);
58992  memcpy(pTo, pFrom, MEMCELLSIZE);
58993  pTo->flags &= ~MEM_Dyn;
58994
58995  if( pTo->flags&(MEM_Str|MEM_Blob) ){
58996    if( 0==(pFrom->flags&MEM_Static) ){
58997      pTo->flags |= MEM_Ephem;
58998      rc = sqlite3VdbeMemMakeWriteable(pTo);
58999    }
59000  }
59001
59002  return rc;
59003}
59004
59005/*
59006** Transfer the contents of pFrom to pTo. Any existing value in pTo is
59007** freed. If pFrom contains ephemeral data, a copy is made.
59008**
59009** pFrom contains an SQL NULL when this routine returns.
59010*/
59011SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
59012  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
59013  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
59014  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
59015
59016  sqlite3VdbeMemRelease(pTo);
59017  memcpy(pTo, pFrom, sizeof(Mem));
59018  pFrom->flags = MEM_Null;
59019  pFrom->xDel = 0;
59020  pFrom->zMalloc = 0;
59021}
59022
59023/*
59024** Change the value of a Mem to be a string or a BLOB.
59025**
59026** The memory management strategy depends on the value of the xDel
59027** parameter. If the value passed is SQLITE_TRANSIENT, then the
59028** string is copied into a (possibly existing) buffer managed by the
59029** Mem structure. Otherwise, any existing buffer is freed and the
59030** pointer copied.
59031**
59032** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
59033** size limit) then no memory allocation occurs.  If the string can be
59034** stored without allocating memory, then it is.  If a memory allocation
59035** is required to store the string, then value of pMem is unchanged.  In
59036** either case, SQLITE_TOOBIG is returned.
59037*/
59038SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
59039  Mem *pMem,          /* Memory cell to set to string value */
59040  const char *z,      /* String pointer */
59041  int n,              /* Bytes in string, or negative */
59042  u8 enc,             /* Encoding of z.  0 for BLOBs */
59043  void (*xDel)(void*) /* Destructor function */
59044){
59045  int nByte = n;      /* New value for pMem->n */
59046  int iLimit;         /* Maximum allowed string or blob size */
59047  u16 flags = 0;      /* New value for pMem->flags */
59048
59049  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59050  assert( (pMem->flags & MEM_RowSet)==0 );
59051
59052  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
59053  if( !z ){
59054    sqlite3VdbeMemSetNull(pMem);
59055    return SQLITE_OK;
59056  }
59057
59058  if( pMem->db ){
59059    iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
59060  }else{
59061    iLimit = SQLITE_MAX_LENGTH;
59062  }
59063  flags = (enc==0?MEM_Blob:MEM_Str);
59064  if( nByte<0 ){
59065    assert( enc!=0 );
59066    if( enc==SQLITE_UTF8 ){
59067      for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
59068    }else{
59069      for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
59070    }
59071    flags |= MEM_Term;
59072  }
59073
59074  /* The following block sets the new values of Mem.z and Mem.xDel. It
59075  ** also sets a flag in local variable "flags" to indicate the memory
59076  ** management (one of MEM_Dyn or MEM_Static).
59077  */
59078  if( xDel==SQLITE_TRANSIENT ){
59079    int nAlloc = nByte;
59080    if( flags&MEM_Term ){
59081      nAlloc += (enc==SQLITE_UTF8?1:2);
59082    }
59083    if( nByte>iLimit ){
59084      return SQLITE_TOOBIG;
59085    }
59086    if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
59087      return SQLITE_NOMEM;
59088    }
59089    memcpy(pMem->z, z, nAlloc);
59090  }else if( xDel==SQLITE_DYNAMIC ){
59091    sqlite3VdbeMemRelease(pMem);
59092    pMem->zMalloc = pMem->z = (char *)z;
59093    pMem->xDel = 0;
59094  }else{
59095    sqlite3VdbeMemRelease(pMem);
59096    pMem->z = (char *)z;
59097    pMem->xDel = xDel;
59098    flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
59099  }
59100
59101  pMem->n = nByte;
59102  pMem->flags = flags;
59103  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
59104  pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
59105
59106#ifndef SQLITE_OMIT_UTF16
59107  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
59108    return SQLITE_NOMEM;
59109  }
59110#endif
59111
59112  if( nByte>iLimit ){
59113    return SQLITE_TOOBIG;
59114  }
59115
59116  return SQLITE_OK;
59117}
59118
59119/*
59120** Compare the values contained by the two memory cells, returning
59121** negative, zero or positive if pMem1 is less than, equal to, or greater
59122** than pMem2. Sorting order is NULL's first, followed by numbers (integers
59123** and reals) sorted numerically, followed by text ordered by the collating
59124** sequence pColl and finally blob's ordered by memcmp().
59125**
59126** Two NULL values are considered equal by this function.
59127*/
59128SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
59129  int rc;
59130  int f1, f2;
59131  int combined_flags;
59132
59133  f1 = pMem1->flags;
59134  f2 = pMem2->flags;
59135  combined_flags = f1|f2;
59136  assert( (combined_flags & MEM_RowSet)==0 );
59137
59138  /* If one value is NULL, it is less than the other. If both values
59139  ** are NULL, return 0.
59140  */
59141  if( combined_flags&MEM_Null ){
59142    return (f2&MEM_Null) - (f1&MEM_Null);
59143  }
59144
59145  /* If one value is a number and the other is not, the number is less.
59146  ** If both are numbers, compare as reals if one is a real, or as integers
59147  ** if both values are integers.
59148  */
59149  if( combined_flags&(MEM_Int|MEM_Real) ){
59150    if( !(f1&(MEM_Int|MEM_Real)) ){
59151      return 1;
59152    }
59153    if( !(f2&(MEM_Int|MEM_Real)) ){
59154      return -1;
59155    }
59156    if( (f1 & f2 & MEM_Int)==0 ){
59157      double r1, r2;
59158      if( (f1&MEM_Real)==0 ){
59159        r1 = (double)pMem1->u.i;
59160      }else{
59161        r1 = pMem1->r;
59162      }
59163      if( (f2&MEM_Real)==0 ){
59164        r2 = (double)pMem2->u.i;
59165      }else{
59166        r2 = pMem2->r;
59167      }
59168      if( r1<r2 ) return -1;
59169      if( r1>r2 ) return 1;
59170      return 0;
59171    }else{
59172      assert( f1&MEM_Int );
59173      assert( f2&MEM_Int );
59174      if( pMem1->u.i < pMem2->u.i ) return -1;
59175      if( pMem1->u.i > pMem2->u.i ) return 1;
59176      return 0;
59177    }
59178  }
59179
59180  /* If one value is a string and the other is a blob, the string is less.
59181  ** If both are strings, compare using the collating functions.
59182  */
59183  if( combined_flags&MEM_Str ){
59184    if( (f1 & MEM_Str)==0 ){
59185      return 1;
59186    }
59187    if( (f2 & MEM_Str)==0 ){
59188      return -1;
59189    }
59190
59191    assert( pMem1->enc==pMem2->enc );
59192    assert( pMem1->enc==SQLITE_UTF8 ||
59193            pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
59194
59195    /* The collation sequence must be defined at this point, even if
59196    ** the user deletes the collation sequence after the vdbe program is
59197    ** compiled (this was not always the case).
59198    */
59199    assert( !pColl || pColl->xCmp );
59200
59201    if( pColl ){
59202      if( pMem1->enc==pColl->enc ){
59203        /* The strings are already in the correct encoding.  Call the
59204        ** comparison function directly */
59205        return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
59206      }else{
59207        const void *v1, *v2;
59208        int n1, n2;
59209        Mem c1;
59210        Mem c2;
59211        memset(&c1, 0, sizeof(c1));
59212        memset(&c2, 0, sizeof(c2));
59213        sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
59214        sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
59215        v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
59216        n1 = v1==0 ? 0 : c1.n;
59217        v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
59218        n2 = v2==0 ? 0 : c2.n;
59219        rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
59220        sqlite3VdbeMemRelease(&c1);
59221        sqlite3VdbeMemRelease(&c2);
59222        return rc;
59223      }
59224    }
59225    /* If a NULL pointer was passed as the collate function, fall through
59226    ** to the blob case and use memcmp().  */
59227  }
59228
59229  /* Both values must be blobs.  Compare using memcmp().  */
59230  rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
59231  if( rc==0 ){
59232    rc = pMem1->n - pMem2->n;
59233  }
59234  return rc;
59235}
59236
59237/*
59238** Move data out of a btree key or data field and into a Mem structure.
59239** The data or key is taken from the entry that pCur is currently pointing
59240** to.  offset and amt determine what portion of the data or key to retrieve.
59241** key is true to get the key or false to get data.  The result is written
59242** into the pMem element.
59243**
59244** The pMem structure is assumed to be uninitialized.  Any prior content
59245** is overwritten without being freed.
59246**
59247** If this routine fails for any reason (malloc returns NULL or unable
59248** to read from the disk) then the pMem is left in an inconsistent state.
59249*/
59250SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
59251  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
59252  int offset,       /* Offset from the start of data to return bytes from. */
59253  int amt,          /* Number of bytes to return. */
59254  int key,          /* If true, retrieve from the btree key, not data. */
59255  Mem *pMem         /* OUT: Return data in this Mem structure. */
59256){
59257  char *zData;        /* Data from the btree layer */
59258  int available = 0;  /* Number of bytes available on the local btree page */
59259  int rc = SQLITE_OK; /* Return code */
59260
59261  assert( sqlite3BtreeCursorIsValid(pCur) );
59262
59263  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
59264  ** that both the BtShared and database handle mutexes are held. */
59265  assert( (pMem->flags & MEM_RowSet)==0 );
59266  if( key ){
59267    zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
59268  }else{
59269    zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
59270  }
59271  assert( zData!=0 );
59272
59273  if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
59274    sqlite3VdbeMemRelease(pMem);
59275    pMem->z = &zData[offset];
59276    pMem->flags = MEM_Blob|MEM_Ephem;
59277  }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
59278    pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
59279    pMem->enc = 0;
59280    pMem->type = SQLITE_BLOB;
59281    if( key ){
59282      rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
59283    }else{
59284      rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
59285    }
59286    pMem->z[amt] = 0;
59287    pMem->z[amt+1] = 0;
59288    if( rc!=SQLITE_OK ){
59289      sqlite3VdbeMemRelease(pMem);
59290    }
59291  }
59292  pMem->n = amt;
59293
59294  return rc;
59295}
59296
59297/* This function is only available internally, it is not part of the
59298** external API. It works in a similar way to sqlite3_value_text(),
59299** except the data returned is in the encoding specified by the second
59300** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
59301** SQLITE_UTF8.
59302**
59303** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
59304** If that is the case, then the result must be aligned on an even byte
59305** boundary.
59306*/
59307SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
59308  if( !pVal ) return 0;
59309
59310  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
59311  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
59312  assert( (pVal->flags & MEM_RowSet)==0 );
59313
59314  if( pVal->flags&MEM_Null ){
59315    return 0;
59316  }
59317  assert( (MEM_Blob>>3) == MEM_Str );
59318  pVal->flags |= (pVal->flags & MEM_Blob)>>3;
59319  ExpandBlob(pVal);
59320  if( pVal->flags&MEM_Str ){
59321    sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
59322    if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
59323      assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
59324      if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
59325        return 0;
59326      }
59327    }
59328    sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
59329  }else{
59330    assert( (pVal->flags&MEM_Blob)==0 );
59331    sqlite3VdbeMemStringify(pVal, enc);
59332    assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
59333  }
59334  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
59335              || pVal->db->mallocFailed );
59336  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
59337    return pVal->z;
59338  }else{
59339    return 0;
59340  }
59341}
59342
59343/*
59344** Create a new sqlite3_value object.
59345*/
59346SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
59347  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
59348  if( p ){
59349    p->flags = MEM_Null;
59350    p->type = SQLITE_NULL;
59351    p->db = db;
59352  }
59353  return p;
59354}
59355
59356/*
59357** Create a new sqlite3_value object, containing the value of pExpr.
59358**
59359** This only works for very simple expressions that consist of one constant
59360** token (i.e. "5", "5.1", "'a string'"). If the expression can
59361** be converted directly into a value, then the value is allocated and
59362** a pointer written to *ppVal. The caller is responsible for deallocating
59363** the value by passing it to sqlite3ValueFree() later on. If the expression
59364** cannot be converted to a value, then *ppVal is set to NULL.
59365*/
59366SQLITE_PRIVATE int sqlite3ValueFromExpr(
59367  sqlite3 *db,              /* The database connection */
59368  Expr *pExpr,              /* The expression to evaluate */
59369  u8 enc,                   /* Encoding to use */
59370  u8 affinity,              /* Affinity to use */
59371  sqlite3_value **ppVal     /* Write the new value here */
59372){
59373  int op;
59374  char *zVal = 0;
59375  sqlite3_value *pVal = 0;
59376  int negInt = 1;
59377  const char *zNeg = "";
59378
59379  if( !pExpr ){
59380    *ppVal = 0;
59381    return SQLITE_OK;
59382  }
59383  op = pExpr->op;
59384
59385  /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
59386  ** The ifdef here is to enable us to achieve 100% branch test coverage even
59387  ** when SQLITE_ENABLE_STAT3 is omitted.
59388  */
59389#ifdef SQLITE_ENABLE_STAT3
59390  if( op==TK_REGISTER ) op = pExpr->op2;
59391#else
59392  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
59393#endif
59394
59395  /* Handle negative integers in a single step.  This is needed in the
59396  ** case when the value is -9223372036854775808.
59397  */
59398  if( op==TK_UMINUS
59399   && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
59400    pExpr = pExpr->pLeft;
59401    op = pExpr->op;
59402    negInt = -1;
59403    zNeg = "-";
59404  }
59405
59406  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
59407    pVal = sqlite3ValueNew(db);
59408    if( pVal==0 ) goto no_mem;
59409    if( ExprHasProperty(pExpr, EP_IntValue) ){
59410      sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
59411    }else{
59412      zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
59413      if( zVal==0 ) goto no_mem;
59414      sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
59415      if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
59416    }
59417    if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
59418      sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
59419    }else{
59420      sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
59421    }
59422    if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
59423    if( enc!=SQLITE_UTF8 ){
59424      sqlite3VdbeChangeEncoding(pVal, enc);
59425    }
59426  }else if( op==TK_UMINUS ) {
59427    /* This branch happens for multiple negative signs.  Ex: -(-5) */
59428    if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
59429      sqlite3VdbeMemNumerify(pVal);
59430      if( pVal->u.i==SMALLEST_INT64 ){
59431        pVal->flags &= MEM_Int;
59432        pVal->flags |= MEM_Real;
59433        pVal->r = (double)LARGEST_INT64;
59434      }else{
59435        pVal->u.i = -pVal->u.i;
59436      }
59437      pVal->r = -pVal->r;
59438      sqlite3ValueApplyAffinity(pVal, affinity, enc);
59439    }
59440  }else if( op==TK_NULL ){
59441    pVal = sqlite3ValueNew(db);
59442    if( pVal==0 ) goto no_mem;
59443  }
59444#ifndef SQLITE_OMIT_BLOB_LITERAL
59445  else if( op==TK_BLOB ){
59446    int nVal;
59447    assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
59448    assert( pExpr->u.zToken[1]=='\'' );
59449    pVal = sqlite3ValueNew(db);
59450    if( !pVal ) goto no_mem;
59451    zVal = &pExpr->u.zToken[2];
59452    nVal = sqlite3Strlen30(zVal)-1;
59453    assert( zVal[nVal]=='\'' );
59454    sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
59455                         0, SQLITE_DYNAMIC);
59456  }
59457#endif
59458
59459  if( pVal ){
59460    sqlite3VdbeMemStoreType(pVal);
59461  }
59462  *ppVal = pVal;
59463  return SQLITE_OK;
59464
59465no_mem:
59466  db->mallocFailed = 1;
59467  sqlite3DbFree(db, zVal);
59468  sqlite3ValueFree(pVal);
59469  *ppVal = 0;
59470  return SQLITE_NOMEM;
59471}
59472
59473/*
59474** Change the string value of an sqlite3_value object
59475*/
59476SQLITE_PRIVATE void sqlite3ValueSetStr(
59477  sqlite3_value *v,     /* Value to be set */
59478  int n,                /* Length of string z */
59479  const void *z,        /* Text of the new string */
59480  u8 enc,               /* Encoding to use */
59481  void (*xDel)(void*)   /* Destructor for the string */
59482){
59483  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
59484}
59485
59486/*
59487** Free an sqlite3_value object
59488*/
59489SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
59490  if( !v ) return;
59491  sqlite3VdbeMemRelease((Mem *)v);
59492  sqlite3DbFree(((Mem*)v)->db, v);
59493}
59494
59495/*
59496** Return the number of bytes in the sqlite3_value object assuming
59497** that it uses the encoding "enc"
59498*/
59499SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
59500  Mem *p = (Mem*)pVal;
59501  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
59502    if( p->flags & MEM_Zero ){
59503      return p->n + p->u.nZero;
59504    }else{
59505      return p->n;
59506    }
59507  }
59508  return 0;
59509}
59510
59511/************** End of vdbemem.c *********************************************/
59512/************** Begin file vdbeaux.c *****************************************/
59513/*
59514** 2003 September 6
59515**
59516** The author disclaims copyright to this source code.  In place of
59517** a legal notice, here is a blessing:
59518**
59519**    May you do good and not evil.
59520**    May you find forgiveness for yourself and forgive others.
59521**    May you share freely, never taking more than you give.
59522**
59523*************************************************************************
59524** This file contains code used for creating, destroying, and populating
59525** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
59526** to version 2.8.7, all this code was combined into the vdbe.c source file.
59527** But that file was getting too big so this subroutines were split out.
59528*/
59529
59530
59531
59532/*
59533** When debugging the code generator in a symbolic debugger, one can
59534** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
59535** as they are added to the instruction stream.
59536*/
59537#ifdef SQLITE_DEBUG
59538SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
59539#endif
59540
59541
59542/*
59543** Create a new virtual database engine.
59544*/
59545SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
59546  Vdbe *p;
59547  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
59548  if( p==0 ) return 0;
59549  p->db = db;
59550  if( db->pVdbe ){
59551    db->pVdbe->pPrev = p;
59552  }
59553  p->pNext = db->pVdbe;
59554  p->pPrev = 0;
59555  db->pVdbe = p;
59556  p->magic = VDBE_MAGIC_INIT;
59557  return p;
59558}
59559
59560/*
59561** Remember the SQL string for a prepared statement.
59562*/
59563SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
59564  assert( isPrepareV2==1 || isPrepareV2==0 );
59565  if( p==0 ) return;
59566#ifdef SQLITE_OMIT_TRACE
59567  if( !isPrepareV2 ) return;
59568#endif
59569  assert( p->zSql==0 );
59570  p->zSql = sqlite3DbStrNDup(p->db, z, n);
59571  p->isPrepareV2 = (u8)isPrepareV2;
59572}
59573
59574/*
59575** Return the SQL associated with a prepared statement
59576*/
59577SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
59578  Vdbe *p = (Vdbe *)pStmt;
59579  return (p && p->isPrepareV2) ? p->zSql : 0;
59580}
59581
59582/*
59583** Swap all content between two VDBE structures.
59584*/
59585SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
59586  Vdbe tmp, *pTmp;
59587  char *zTmp;
59588  tmp = *pA;
59589  *pA = *pB;
59590  *pB = tmp;
59591  pTmp = pA->pNext;
59592  pA->pNext = pB->pNext;
59593  pB->pNext = pTmp;
59594  pTmp = pA->pPrev;
59595  pA->pPrev = pB->pPrev;
59596  pB->pPrev = pTmp;
59597  zTmp = pA->zSql;
59598  pA->zSql = pB->zSql;
59599  pB->zSql = zTmp;
59600  pB->isPrepareV2 = pA->isPrepareV2;
59601}
59602
59603#ifdef SQLITE_DEBUG
59604/*
59605** Turn tracing on or off
59606*/
59607SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
59608  p->trace = trace;
59609}
59610#endif
59611
59612/*
59613** Resize the Vdbe.aOp array so that it is at least one op larger than
59614** it was.
59615**
59616** If an out-of-memory error occurs while resizing the array, return
59617** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
59618** unchanged (this is so that any opcodes already allocated can be
59619** correctly deallocated along with the rest of the Vdbe).
59620*/
59621static int growOpArray(Vdbe *p){
59622  VdbeOp *pNew;
59623  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
59624  pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
59625  if( pNew ){
59626    p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
59627    p->aOp = pNew;
59628  }
59629  return (pNew ? SQLITE_OK : SQLITE_NOMEM);
59630}
59631
59632/*
59633** Add a new instruction to the list of instructions current in the
59634** VDBE.  Return the address of the new instruction.
59635**
59636** Parameters:
59637**
59638**    p               Pointer to the VDBE
59639**
59640**    op              The opcode for this instruction
59641**
59642**    p1, p2, p3      Operands
59643**
59644** Use the sqlite3VdbeResolveLabel() function to fix an address and
59645** the sqlite3VdbeChangeP4() function to change the value of the P4
59646** operand.
59647*/
59648SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
59649  int i;
59650  VdbeOp *pOp;
59651
59652  i = p->nOp;
59653  assert( p->magic==VDBE_MAGIC_INIT );
59654  assert( op>0 && op<0xff );
59655  if( p->nOpAlloc<=i ){
59656    if( growOpArray(p) ){
59657      return 1;
59658    }
59659  }
59660  p->nOp++;
59661  pOp = &p->aOp[i];
59662  pOp->opcode = (u8)op;
59663  pOp->p5 = 0;
59664  pOp->p1 = p1;
59665  pOp->p2 = p2;
59666  pOp->p3 = p3;
59667  pOp->p4.p = 0;
59668  pOp->p4type = P4_NOTUSED;
59669#ifdef SQLITE_DEBUG
59670  pOp->zComment = 0;
59671  if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
59672#endif
59673#ifdef VDBE_PROFILE
59674  pOp->cycles = 0;
59675  pOp->cnt = 0;
59676#endif
59677  return i;
59678}
59679SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
59680  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
59681}
59682SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
59683  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
59684}
59685SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
59686  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
59687}
59688
59689
59690/*
59691** Add an opcode that includes the p4 value as a pointer.
59692*/
59693SQLITE_PRIVATE int sqlite3VdbeAddOp4(
59694  Vdbe *p,            /* Add the opcode to this VM */
59695  int op,             /* The new opcode */
59696  int p1,             /* The P1 operand */
59697  int p2,             /* The P2 operand */
59698  int p3,             /* The P3 operand */
59699  const char *zP4,    /* The P4 operand */
59700  int p4type          /* P4 operand type */
59701){
59702  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
59703  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
59704  return addr;
59705}
59706
59707/*
59708** Add an OP_ParseSchema opcode.  This routine is broken out from
59709** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
59710** as having been used.
59711**
59712** The zWhere string must have been obtained from sqlite3_malloc().
59713** This routine will take ownership of the allocated memory.
59714*/
59715SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
59716  int j;
59717  int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
59718  sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
59719  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
59720}
59721
59722/*
59723** Add an opcode that includes the p4 value as an integer.
59724*/
59725SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
59726  Vdbe *p,            /* Add the opcode to this VM */
59727  int op,             /* The new opcode */
59728  int p1,             /* The P1 operand */
59729  int p2,             /* The P2 operand */
59730  int p3,             /* The P3 operand */
59731  int p4              /* The P4 operand as an integer */
59732){
59733  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
59734  sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
59735  return addr;
59736}
59737
59738/*
59739** Create a new symbolic label for an instruction that has yet to be
59740** coded.  The symbolic label is really just a negative number.  The
59741** label can be used as the P2 value of an operation.  Later, when
59742** the label is resolved to a specific address, the VDBE will scan
59743** through its operation list and change all values of P2 which match
59744** the label into the resolved address.
59745**
59746** The VDBE knows that a P2 value is a label because labels are
59747** always negative and P2 values are suppose to be non-negative.
59748** Hence, a negative P2 value is a label that has yet to be resolved.
59749**
59750** Zero is returned if a malloc() fails.
59751*/
59752SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
59753  int i = p->nLabel++;
59754  assert( p->magic==VDBE_MAGIC_INIT );
59755  if( (i & (i-1))==0 ){
59756    p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
59757                                       (i*2+1)*sizeof(p->aLabel[0]));
59758  }
59759  if( p->aLabel ){
59760    p->aLabel[i] = -1;
59761  }
59762  return -1-i;
59763}
59764
59765/*
59766** Resolve label "x" to be the address of the next instruction to
59767** be inserted.  The parameter "x" must have been obtained from
59768** a prior call to sqlite3VdbeMakeLabel().
59769*/
59770SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
59771  int j = -1-x;
59772  assert( p->magic==VDBE_MAGIC_INIT );
59773  assert( j>=0 && j<p->nLabel );
59774  if( p->aLabel ){
59775    p->aLabel[j] = p->nOp;
59776  }
59777}
59778
59779/*
59780** Mark the VDBE as one that can only be run one time.
59781*/
59782SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
59783  p->runOnlyOnce = 1;
59784}
59785
59786#ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
59787
59788/*
59789** The following type and function are used to iterate through all opcodes
59790** in a Vdbe main program and each of the sub-programs (triggers) it may
59791** invoke directly or indirectly. It should be used as follows:
59792**
59793**   Op *pOp;
59794**   VdbeOpIter sIter;
59795**
59796**   memset(&sIter, 0, sizeof(sIter));
59797**   sIter.v = v;                            // v is of type Vdbe*
59798**   while( (pOp = opIterNext(&sIter)) ){
59799**     // Do something with pOp
59800**   }
59801**   sqlite3DbFree(v->db, sIter.apSub);
59802**
59803*/
59804typedef struct VdbeOpIter VdbeOpIter;
59805struct VdbeOpIter {
59806  Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
59807  SubProgram **apSub;        /* Array of subprograms */
59808  int nSub;                  /* Number of entries in apSub */
59809  int iAddr;                 /* Address of next instruction to return */
59810  int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
59811};
59812static Op *opIterNext(VdbeOpIter *p){
59813  Vdbe *v = p->v;
59814  Op *pRet = 0;
59815  Op *aOp;
59816  int nOp;
59817
59818  if( p->iSub<=p->nSub ){
59819
59820    if( p->iSub==0 ){
59821      aOp = v->aOp;
59822      nOp = v->nOp;
59823    }else{
59824      aOp = p->apSub[p->iSub-1]->aOp;
59825      nOp = p->apSub[p->iSub-1]->nOp;
59826    }
59827    assert( p->iAddr<nOp );
59828
59829    pRet = &aOp[p->iAddr];
59830    p->iAddr++;
59831    if( p->iAddr==nOp ){
59832      p->iSub++;
59833      p->iAddr = 0;
59834    }
59835
59836    if( pRet->p4type==P4_SUBPROGRAM ){
59837      int nByte = (p->nSub+1)*sizeof(SubProgram*);
59838      int j;
59839      for(j=0; j<p->nSub; j++){
59840        if( p->apSub[j]==pRet->p4.pProgram ) break;
59841      }
59842      if( j==p->nSub ){
59843        p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
59844        if( !p->apSub ){
59845          pRet = 0;
59846        }else{
59847          p->apSub[p->nSub++] = pRet->p4.pProgram;
59848        }
59849      }
59850    }
59851  }
59852
59853  return pRet;
59854}
59855
59856/*
59857** Check if the program stored in the VM associated with pParse may
59858** throw an ABORT exception (causing the statement, but not entire transaction
59859** to be rolled back). This condition is true if the main program or any
59860** sub-programs contains any of the following:
59861**
59862**   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
59863**   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
59864**   *  OP_Destroy
59865**   *  OP_VUpdate
59866**   *  OP_VRename
59867**   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
59868**
59869** Then check that the value of Parse.mayAbort is true if an
59870** ABORT may be thrown, or false otherwise. Return true if it does
59871** match, or false otherwise. This function is intended to be used as
59872** part of an assert statement in the compiler. Similar to:
59873**
59874**   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
59875*/
59876SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
59877  int hasAbort = 0;
59878  Op *pOp;
59879  VdbeOpIter sIter;
59880  memset(&sIter, 0, sizeof(sIter));
59881  sIter.v = v;
59882
59883  while( (pOp = opIterNext(&sIter))!=0 ){
59884    int opcode = pOp->opcode;
59885    if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
59886#ifndef SQLITE_OMIT_FOREIGN_KEY
59887     || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
59888#endif
59889     || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
59890      && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
59891    ){
59892      hasAbort = 1;
59893      break;
59894    }
59895  }
59896  sqlite3DbFree(v->db, sIter.apSub);
59897
59898  /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
59899  ** If malloc failed, then the while() loop above may not have iterated
59900  ** through all opcodes and hasAbort may be set incorrectly. Return
59901  ** true for this case to prevent the assert() in the callers frame
59902  ** from failing.  */
59903  return ( v->db->mallocFailed || hasAbort==mayAbort );
59904}
59905#endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
59906
59907/*
59908** Loop through the program looking for P2 values that are negative
59909** on jump instructions.  Each such value is a label.  Resolve the
59910** label by setting the P2 value to its correct non-zero value.
59911**
59912** This routine is called once after all opcodes have been inserted.
59913**
59914** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
59915** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
59916** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
59917**
59918** The Op.opflags field is set on all opcodes.
59919*/
59920static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
59921  int i;
59922  int nMaxArgs = *pMaxFuncArgs;
59923  Op *pOp;
59924  int *aLabel = p->aLabel;
59925  p->readOnly = 1;
59926  for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
59927    u8 opcode = pOp->opcode;
59928
59929    pOp->opflags = sqlite3OpcodeProperty[opcode];
59930    if( opcode==OP_Function || opcode==OP_AggStep ){
59931      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
59932    }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
59933      p->readOnly = 0;
59934#ifndef SQLITE_OMIT_VIRTUALTABLE
59935    }else if( opcode==OP_VUpdate ){
59936      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
59937    }else if( opcode==OP_VFilter ){
59938      int n;
59939      assert( p->nOp - i >= 3 );
59940      assert( pOp[-1].opcode==OP_Integer );
59941      n = pOp[-1].p1;
59942      if( n>nMaxArgs ) nMaxArgs = n;
59943#endif
59944    }else if( opcode==OP_Next || opcode==OP_SorterNext ){
59945      pOp->p4.xAdvance = sqlite3BtreeNext;
59946      pOp->p4type = P4_ADVANCE;
59947    }else if( opcode==OP_Prev ){
59948      pOp->p4.xAdvance = sqlite3BtreePrevious;
59949      pOp->p4type = P4_ADVANCE;
59950    }
59951
59952    if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
59953      assert( -1-pOp->p2<p->nLabel );
59954      pOp->p2 = aLabel[-1-pOp->p2];
59955    }
59956  }
59957  sqlite3DbFree(p->db, p->aLabel);
59958  p->aLabel = 0;
59959
59960  *pMaxFuncArgs = nMaxArgs;
59961}
59962
59963/*
59964** Return the address of the next instruction to be inserted.
59965*/
59966SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
59967  assert( p->magic==VDBE_MAGIC_INIT );
59968  return p->nOp;
59969}
59970
59971/*
59972** This function returns a pointer to the array of opcodes associated with
59973** the Vdbe passed as the first argument. It is the callers responsibility
59974** to arrange for the returned array to be eventually freed using the
59975** vdbeFreeOpArray() function.
59976**
59977** Before returning, *pnOp is set to the number of entries in the returned
59978** array. Also, *pnMaxArg is set to the larger of its current value and
59979** the number of entries in the Vdbe.apArg[] array required to execute the
59980** returned program.
59981*/
59982SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
59983  VdbeOp *aOp = p->aOp;
59984  assert( aOp && !p->db->mallocFailed );
59985
59986  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
59987  assert( p->btreeMask==0 );
59988
59989  resolveP2Values(p, pnMaxArg);
59990  *pnOp = p->nOp;
59991  p->aOp = 0;
59992  return aOp;
59993}
59994
59995/*
59996** Add a whole list of operations to the operation stack.  Return the
59997** address of the first operation added.
59998*/
59999SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
60000  int addr;
60001  assert( p->magic==VDBE_MAGIC_INIT );
60002  if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
60003    return 0;
60004  }
60005  addr = p->nOp;
60006  if( ALWAYS(nOp>0) ){
60007    int i;
60008    VdbeOpList const *pIn = aOp;
60009    for(i=0; i<nOp; i++, pIn++){
60010      int p2 = pIn->p2;
60011      VdbeOp *pOut = &p->aOp[i+addr];
60012      pOut->opcode = pIn->opcode;
60013      pOut->p1 = pIn->p1;
60014      if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
60015        pOut->p2 = addr + ADDR(p2);
60016      }else{
60017        pOut->p2 = p2;
60018      }
60019      pOut->p3 = pIn->p3;
60020      pOut->p4type = P4_NOTUSED;
60021      pOut->p4.p = 0;
60022      pOut->p5 = 0;
60023#ifdef SQLITE_DEBUG
60024      pOut->zComment = 0;
60025      if( sqlite3VdbeAddopTrace ){
60026        sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
60027      }
60028#endif
60029    }
60030    p->nOp += nOp;
60031  }
60032  return addr;
60033}
60034
60035/*
60036** Change the value of the P1 operand for a specific instruction.
60037** This routine is useful when a large program is loaded from a
60038** static array using sqlite3VdbeAddOpList but we want to make a
60039** few minor changes to the program.
60040*/
60041SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
60042  assert( p!=0 );
60043  if( ((u32)p->nOp)>addr ){
60044    p->aOp[addr].p1 = val;
60045  }
60046}
60047
60048/*
60049** Change the value of the P2 operand for a specific instruction.
60050** This routine is useful for setting a jump destination.
60051*/
60052SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
60053  assert( p!=0 );
60054  if( ((u32)p->nOp)>addr ){
60055    p->aOp[addr].p2 = val;
60056  }
60057}
60058
60059/*
60060** Change the value of the P3 operand for a specific instruction.
60061*/
60062SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
60063  assert( p!=0 );
60064  if( ((u32)p->nOp)>addr ){
60065    p->aOp[addr].p3 = val;
60066  }
60067}
60068
60069/*
60070** Change the value of the P5 operand for the most recently
60071** added operation.
60072*/
60073SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
60074  assert( p!=0 );
60075  if( p->aOp ){
60076    assert( p->nOp>0 );
60077    p->aOp[p->nOp-1].p5 = val;
60078  }
60079}
60080
60081/*
60082** Change the P2 operand of instruction addr so that it points to
60083** the address of the next instruction to be coded.
60084*/
60085SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
60086  assert( addr>=0 || p->db->mallocFailed );
60087  if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
60088}
60089
60090
60091/*
60092** If the input FuncDef structure is ephemeral, then free it.  If
60093** the FuncDef is not ephermal, then do nothing.
60094*/
60095static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
60096  if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
60097    sqlite3DbFree(db, pDef);
60098  }
60099}
60100
60101static void vdbeFreeOpArray(sqlite3 *, Op *, int);
60102
60103/*
60104** Delete a P4 value if necessary.
60105*/
60106static void freeP4(sqlite3 *db, int p4type, void *p4){
60107  if( p4 ){
60108    assert( db );
60109    switch( p4type ){
60110      case P4_REAL:
60111      case P4_INT64:
60112      case P4_DYNAMIC:
60113      case P4_KEYINFO:
60114      case P4_INTARRAY:
60115      case P4_KEYINFO_HANDOFF: {
60116        sqlite3DbFree(db, p4);
60117        break;
60118      }
60119      case P4_MPRINTF: {
60120        if( db->pnBytesFreed==0 ) sqlite3_free(p4);
60121        break;
60122      }
60123      case P4_VDBEFUNC: {
60124        VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
60125        freeEphemeralFunction(db, pVdbeFunc->pFunc);
60126        if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
60127        sqlite3DbFree(db, pVdbeFunc);
60128        break;
60129      }
60130      case P4_FUNCDEF: {
60131        freeEphemeralFunction(db, (FuncDef*)p4);
60132        break;
60133      }
60134      case P4_MEM: {
60135        if( db->pnBytesFreed==0 ){
60136          sqlite3ValueFree((sqlite3_value*)p4);
60137        }else{
60138          Mem *p = (Mem*)p4;
60139          sqlite3DbFree(db, p->zMalloc);
60140          sqlite3DbFree(db, p);
60141        }
60142        break;
60143      }
60144      case P4_VTAB : {
60145        if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
60146        break;
60147      }
60148    }
60149  }
60150}
60151
60152/*
60153** Free the space allocated for aOp and any p4 values allocated for the
60154** opcodes contained within. If aOp is not NULL it is assumed to contain
60155** nOp entries.
60156*/
60157static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
60158  if( aOp ){
60159    Op *pOp;
60160    for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
60161      freeP4(db, pOp->p4type, pOp->p4.p);
60162#ifdef SQLITE_DEBUG
60163      sqlite3DbFree(db, pOp->zComment);
60164#endif
60165    }
60166  }
60167  sqlite3DbFree(db, aOp);
60168}
60169
60170/*
60171** Link the SubProgram object passed as the second argument into the linked
60172** list at Vdbe.pSubProgram. This list is used to delete all sub-program
60173** objects when the VM is no longer required.
60174*/
60175SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
60176  p->pNext = pVdbe->pProgram;
60177  pVdbe->pProgram = p;
60178}
60179
60180/*
60181** Change the opcode at addr into OP_Noop
60182*/
60183SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
60184  if( p->aOp ){
60185    VdbeOp *pOp = &p->aOp[addr];
60186    sqlite3 *db = p->db;
60187    freeP4(db, pOp->p4type, pOp->p4.p);
60188    memset(pOp, 0, sizeof(pOp[0]));
60189    pOp->opcode = OP_Noop;
60190  }
60191}
60192
60193/*
60194** Change the value of the P4 operand for a specific instruction.
60195** This routine is useful when a large program is loaded from a
60196** static array using sqlite3VdbeAddOpList but we want to make a
60197** few minor changes to the program.
60198**
60199** If n>=0 then the P4 operand is dynamic, meaning that a copy of
60200** the string is made into memory obtained from sqlite3_malloc().
60201** A value of n==0 means copy bytes of zP4 up to and including the
60202** first null byte.  If n>0 then copy n+1 bytes of zP4.
60203**
60204** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
60205** A copy is made of the KeyInfo structure into memory obtained from
60206** sqlite3_malloc, to be freed when the Vdbe is finalized.
60207** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
60208** stored in memory that the caller has obtained from sqlite3_malloc. The
60209** caller should not free the allocation, it will be freed when the Vdbe is
60210** finalized.
60211**
60212** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
60213** to a string or structure that is guaranteed to exist for the lifetime of
60214** the Vdbe. In these cases we can just copy the pointer.
60215**
60216** If addr<0 then change P4 on the most recently inserted instruction.
60217*/
60218SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
60219  Op *pOp;
60220  sqlite3 *db;
60221  assert( p!=0 );
60222  db = p->db;
60223  assert( p->magic==VDBE_MAGIC_INIT );
60224  if( p->aOp==0 || db->mallocFailed ){
60225    if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
60226      freeP4(db, n, (void*)*(char**)&zP4);
60227    }
60228    return;
60229  }
60230  assert( p->nOp>0 );
60231  assert( addr<p->nOp );
60232  if( addr<0 ){
60233    addr = p->nOp - 1;
60234  }
60235  pOp = &p->aOp[addr];
60236  freeP4(db, pOp->p4type, pOp->p4.p);
60237  pOp->p4.p = 0;
60238  if( n==P4_INT32 ){
60239    /* Note: this cast is safe, because the origin data point was an int
60240    ** that was cast to a (const char *). */
60241    pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
60242    pOp->p4type = P4_INT32;
60243  }else if( zP4==0 ){
60244    pOp->p4.p = 0;
60245    pOp->p4type = P4_NOTUSED;
60246  }else if( n==P4_KEYINFO ){
60247    KeyInfo *pKeyInfo;
60248    int nField, nByte;
60249
60250    nField = ((KeyInfo*)zP4)->nField;
60251    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
60252    pKeyInfo = sqlite3DbMallocRaw(0, nByte);
60253    pOp->p4.pKeyInfo = pKeyInfo;
60254    if( pKeyInfo ){
60255      u8 *aSortOrder;
60256      memcpy((char*)pKeyInfo, zP4, nByte - nField);
60257      aSortOrder = pKeyInfo->aSortOrder;
60258      if( aSortOrder ){
60259        pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
60260        memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
60261      }
60262      pOp->p4type = P4_KEYINFO;
60263    }else{
60264      p->db->mallocFailed = 1;
60265      pOp->p4type = P4_NOTUSED;
60266    }
60267  }else if( n==P4_KEYINFO_HANDOFF ){
60268    pOp->p4.p = (void*)zP4;
60269    pOp->p4type = P4_KEYINFO;
60270  }else if( n==P4_VTAB ){
60271    pOp->p4.p = (void*)zP4;
60272    pOp->p4type = P4_VTAB;
60273    sqlite3VtabLock((VTable *)zP4);
60274    assert( ((VTable *)zP4)->db==p->db );
60275  }else if( n<0 ){
60276    pOp->p4.p = (void*)zP4;
60277    pOp->p4type = (signed char)n;
60278  }else{
60279    if( n==0 ) n = sqlite3Strlen30(zP4);
60280    pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
60281    pOp->p4type = P4_DYNAMIC;
60282  }
60283}
60284
60285#ifndef NDEBUG
60286/*
60287** Change the comment on the the most recently coded instruction.  Or
60288** insert a No-op and add the comment to that new instruction.  This
60289** makes the code easier to read during debugging.  None of this happens
60290** in a production build.
60291*/
60292static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
60293  assert( p->nOp>0 || p->aOp==0 );
60294  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
60295  if( p->nOp ){
60296    assert( p->aOp );
60297    sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
60298    p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
60299  }
60300}
60301SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
60302  va_list ap;
60303  if( p ){
60304    va_start(ap, zFormat);
60305    vdbeVComment(p, zFormat, ap);
60306    va_end(ap);
60307  }
60308}
60309SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
60310  va_list ap;
60311  if( p ){
60312    sqlite3VdbeAddOp0(p, OP_Noop);
60313    va_start(ap, zFormat);
60314    vdbeVComment(p, zFormat, ap);
60315    va_end(ap);
60316  }
60317}
60318#endif  /* NDEBUG */
60319
60320/*
60321** Return the opcode for a given address.  If the address is -1, then
60322** return the most recently inserted opcode.
60323**
60324** If a memory allocation error has occurred prior to the calling of this
60325** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
60326** is readable but not writable, though it is cast to a writable value.
60327** The return of a dummy opcode allows the call to continue functioning
60328** after a OOM fault without having to check to see if the return from
60329** this routine is a valid pointer.  But because the dummy.opcode is 0,
60330** dummy will never be written to.  This is verified by code inspection and
60331** by running with Valgrind.
60332**
60333** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
60334** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
60335** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
60336** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
60337** having to double-check to make sure that the result is non-negative. But
60338** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
60339** check the value of p->nOp-1 before continuing.
60340*/
60341SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
60342  /* C89 specifies that the constant "dummy" will be initialized to all
60343  ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
60344  static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
60345  assert( p->magic==VDBE_MAGIC_INIT );
60346  if( addr<0 ){
60347#ifdef SQLITE_OMIT_TRACE
60348    if( p->nOp==0 ) return (VdbeOp*)&dummy;
60349#endif
60350    addr = p->nOp - 1;
60351  }
60352  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
60353  if( p->db->mallocFailed ){
60354    return (VdbeOp*)&dummy;
60355  }else{
60356    return &p->aOp[addr];
60357  }
60358}
60359
60360#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
60361     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
60362/*
60363** Compute a string that describes the P4 parameter for an opcode.
60364** Use zTemp for any required temporary buffer space.
60365*/
60366static char *displayP4(Op *pOp, char *zTemp, int nTemp){
60367  char *zP4 = zTemp;
60368  assert( nTemp>=20 );
60369  switch( pOp->p4type ){
60370    case P4_KEYINFO_STATIC:
60371    case P4_KEYINFO: {
60372      int i, j;
60373      KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
60374      sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
60375      i = sqlite3Strlen30(zTemp);
60376      for(j=0; j<pKeyInfo->nField; j++){
60377        CollSeq *pColl = pKeyInfo->aColl[j];
60378        if( pColl ){
60379          int n = sqlite3Strlen30(pColl->zName);
60380          if( i+n>nTemp-6 ){
60381            memcpy(&zTemp[i],",...",4);
60382            break;
60383          }
60384          zTemp[i++] = ',';
60385          if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
60386            zTemp[i++] = '-';
60387          }
60388          memcpy(&zTemp[i], pColl->zName,n+1);
60389          i += n;
60390        }else if( i+4<nTemp-6 ){
60391          memcpy(&zTemp[i],",nil",4);
60392          i += 4;
60393        }
60394      }
60395      zTemp[i++] = ')';
60396      zTemp[i] = 0;
60397      assert( i<nTemp );
60398      break;
60399    }
60400    case P4_COLLSEQ: {
60401      CollSeq *pColl = pOp->p4.pColl;
60402      sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
60403      break;
60404    }
60405    case P4_FUNCDEF: {
60406      FuncDef *pDef = pOp->p4.pFunc;
60407      sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
60408      break;
60409    }
60410    case P4_INT64: {
60411      sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
60412      break;
60413    }
60414    case P4_INT32: {
60415      sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
60416      break;
60417    }
60418    case P4_REAL: {
60419      sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
60420      break;
60421    }
60422    case P4_MEM: {
60423      Mem *pMem = pOp->p4.pMem;
60424      if( pMem->flags & MEM_Str ){
60425        zP4 = pMem->z;
60426      }else if( pMem->flags & MEM_Int ){
60427        sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
60428      }else if( pMem->flags & MEM_Real ){
60429        sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
60430      }else if( pMem->flags & MEM_Null ){
60431        sqlite3_snprintf(nTemp, zTemp, "NULL");
60432      }else{
60433        assert( pMem->flags & MEM_Blob );
60434        zP4 = "(blob)";
60435      }
60436      break;
60437    }
60438#ifndef SQLITE_OMIT_VIRTUALTABLE
60439    case P4_VTAB: {
60440      sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
60441      sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
60442      break;
60443    }
60444#endif
60445    case P4_INTARRAY: {
60446      sqlite3_snprintf(nTemp, zTemp, "intarray");
60447      break;
60448    }
60449    case P4_SUBPROGRAM: {
60450      sqlite3_snprintf(nTemp, zTemp, "program");
60451      break;
60452    }
60453    case P4_ADVANCE: {
60454      zTemp[0] = 0;
60455      break;
60456    }
60457    default: {
60458      zP4 = pOp->p4.z;
60459      if( zP4==0 ){
60460        zP4 = zTemp;
60461        zTemp[0] = 0;
60462      }
60463    }
60464  }
60465  assert( zP4!=0 );
60466  return zP4;
60467}
60468#endif
60469
60470/*
60471** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
60472**
60473** The prepared statements need to know in advance the complete set of
60474** attached databases that will be use.  A mask of these databases
60475** is maintained in p->btreeMask.  The p->lockMask value is the subset of
60476** p->btreeMask of databases that will require a lock.
60477*/
60478SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
60479  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
60480  assert( i<(int)sizeof(p->btreeMask)*8 );
60481  p->btreeMask |= ((yDbMask)1)<<i;
60482  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
60483    p->lockMask |= ((yDbMask)1)<<i;
60484  }
60485}
60486
60487#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
60488/*
60489** If SQLite is compiled to support shared-cache mode and to be threadsafe,
60490** this routine obtains the mutex associated with each BtShared structure
60491** that may be accessed by the VM passed as an argument. In doing so it also
60492** sets the BtShared.db member of each of the BtShared structures, ensuring
60493** that the correct busy-handler callback is invoked if required.
60494**
60495** If SQLite is not threadsafe but does support shared-cache mode, then
60496** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
60497** of all of BtShared structures accessible via the database handle
60498** associated with the VM.
60499**
60500** If SQLite is not threadsafe and does not support shared-cache mode, this
60501** function is a no-op.
60502**
60503** The p->btreeMask field is a bitmask of all btrees that the prepared
60504** statement p will ever use.  Let N be the number of bits in p->btreeMask
60505** corresponding to btrees that use shared cache.  Then the runtime of
60506** this routine is N*N.  But as N is rarely more than 1, this should not
60507** be a problem.
60508*/
60509SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
60510  int i;
60511  yDbMask mask;
60512  sqlite3 *db;
60513  Db *aDb;
60514  int nDb;
60515  if( p->lockMask==0 ) return;  /* The common case */
60516  db = p->db;
60517  aDb = db->aDb;
60518  nDb = db->nDb;
60519  for(i=0, mask=1; i<nDb; i++, mask += mask){
60520    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60521      sqlite3BtreeEnter(aDb[i].pBt);
60522    }
60523  }
60524}
60525#endif
60526
60527#if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
60528/*
60529** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
60530*/
60531SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
60532  int i;
60533  yDbMask mask;
60534  sqlite3 *db;
60535  Db *aDb;
60536  int nDb;
60537  if( p->lockMask==0 ) return;  /* The common case */
60538  db = p->db;
60539  aDb = db->aDb;
60540  nDb = db->nDb;
60541  for(i=0, mask=1; i<nDb; i++, mask += mask){
60542    if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60543      sqlite3BtreeLeave(aDb[i].pBt);
60544    }
60545  }
60546}
60547#endif
60548
60549#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
60550/*
60551** Print a single opcode.  This routine is used for debugging only.
60552*/
60553SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
60554  char *zP4;
60555  char zPtr[50];
60556  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
60557  if( pOut==0 ) pOut = stdout;
60558  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
60559  fprintf(pOut, zFormat1, pc,
60560      sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
60561#ifdef SQLITE_DEBUG
60562      pOp->zComment ? pOp->zComment : ""
60563#else
60564      ""
60565#endif
60566  );
60567  fflush(pOut);
60568}
60569#endif
60570
60571/*
60572** Release an array of N Mem elements
60573*/
60574static void releaseMemArray(Mem *p, int N){
60575  if( p && N ){
60576    Mem *pEnd;
60577    sqlite3 *db = p->db;
60578    u8 malloc_failed = db->mallocFailed;
60579    if( db->pnBytesFreed ){
60580      for(pEnd=&p[N]; p<pEnd; p++){
60581        sqlite3DbFree(db, p->zMalloc);
60582      }
60583      return;
60584    }
60585    for(pEnd=&p[N]; p<pEnd; p++){
60586      assert( (&p[1])==pEnd || p[0].db==p[1].db );
60587
60588      /* This block is really an inlined version of sqlite3VdbeMemRelease()
60589      ** that takes advantage of the fact that the memory cell value is
60590      ** being set to NULL after releasing any dynamic resources.
60591      **
60592      ** The justification for duplicating code is that according to
60593      ** callgrind, this causes a certain test case to hit the CPU 4.7
60594      ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
60595      ** sqlite3MemRelease() were called from here. With -O2, this jumps
60596      ** to 6.6 percent. The test case is inserting 1000 rows into a table
60597      ** with no indexes using a single prepared INSERT statement, bind()
60598      ** and reset(). Inserts are grouped into a transaction.
60599      */
60600      if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
60601        sqlite3VdbeMemRelease(p);
60602      }else if( p->zMalloc ){
60603        sqlite3DbFree(db, p->zMalloc);
60604        p->zMalloc = 0;
60605      }
60606
60607      p->flags = MEM_Invalid;
60608    }
60609    db->mallocFailed = malloc_failed;
60610  }
60611}
60612
60613/*
60614** Delete a VdbeFrame object and its contents. VdbeFrame objects are
60615** allocated by the OP_Program opcode in sqlite3VdbeExec().
60616*/
60617SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
60618  int i;
60619  Mem *aMem = VdbeFrameMem(p);
60620  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
60621  for(i=0; i<p->nChildCsr; i++){
60622    sqlite3VdbeFreeCursor(p->v, apCsr[i]);
60623  }
60624  releaseMemArray(aMem, p->nChildMem);
60625  sqlite3DbFree(p->v->db, p);
60626}
60627
60628#ifndef SQLITE_OMIT_EXPLAIN
60629/*
60630** Give a listing of the program in the virtual machine.
60631**
60632** The interface is the same as sqlite3VdbeExec().  But instead of
60633** running the code, it invokes the callback once for each instruction.
60634** This feature is used to implement "EXPLAIN".
60635**
60636** When p->explain==1, each instruction is listed.  When
60637** p->explain==2, only OP_Explain instructions are listed and these
60638** are shown in a different format.  p->explain==2 is used to implement
60639** EXPLAIN QUERY PLAN.
60640**
60641** When p->explain==1, first the main program is listed, then each of
60642** the trigger subprograms are listed one by one.
60643*/
60644SQLITE_PRIVATE int sqlite3VdbeList(
60645  Vdbe *p                   /* The VDBE */
60646){
60647  int nRow;                            /* Stop when row count reaches this */
60648  int nSub = 0;                        /* Number of sub-vdbes seen so far */
60649  SubProgram **apSub = 0;              /* Array of sub-vdbes */
60650  Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
60651  sqlite3 *db = p->db;                 /* The database connection */
60652  int i;                               /* Loop counter */
60653  int rc = SQLITE_OK;                  /* Return code */
60654  Mem *pMem = &p->aMem[1];             /* First Mem of result set */
60655
60656  assert( p->explain );
60657  assert( p->magic==VDBE_MAGIC_RUN );
60658  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
60659
60660  /* Even though this opcode does not use dynamic strings for
60661  ** the result, result columns may become dynamic if the user calls
60662  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
60663  */
60664  releaseMemArray(pMem, 8);
60665  p->pResultSet = 0;
60666
60667  if( p->rc==SQLITE_NOMEM ){
60668    /* This happens if a malloc() inside a call to sqlite3_column_text() or
60669    ** sqlite3_column_text16() failed.  */
60670    db->mallocFailed = 1;
60671    return SQLITE_ERROR;
60672  }
60673
60674  /* When the number of output rows reaches nRow, that means the
60675  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
60676  ** nRow is the sum of the number of rows in the main program, plus
60677  ** the sum of the number of rows in all trigger subprograms encountered
60678  ** so far.  The nRow value will increase as new trigger subprograms are
60679  ** encountered, but p->pc will eventually catch up to nRow.
60680  */
60681  nRow = p->nOp;
60682  if( p->explain==1 ){
60683    /* The first 8 memory cells are used for the result set.  So we will
60684    ** commandeer the 9th cell to use as storage for an array of pointers
60685    ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
60686    ** cells.  */
60687    assert( p->nMem>9 );
60688    pSub = &p->aMem[9];
60689    if( pSub->flags&MEM_Blob ){
60690      /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
60691      ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
60692      nSub = pSub->n/sizeof(Vdbe*);
60693      apSub = (SubProgram **)pSub->z;
60694    }
60695    for(i=0; i<nSub; i++){
60696      nRow += apSub[i]->nOp;
60697    }
60698  }
60699
60700  do{
60701    i = p->pc++;
60702  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
60703  if( i>=nRow ){
60704    p->rc = SQLITE_OK;
60705    rc = SQLITE_DONE;
60706  }else if( db->u1.isInterrupted ){
60707    p->rc = SQLITE_INTERRUPT;
60708    rc = SQLITE_ERROR;
60709    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
60710  }else{
60711    char *z;
60712    Op *pOp;
60713    if( i<p->nOp ){
60714      /* The output line number is small enough that we are still in the
60715      ** main program. */
60716      pOp = &p->aOp[i];
60717    }else{
60718      /* We are currently listing subprograms.  Figure out which one and
60719      ** pick up the appropriate opcode. */
60720      int j;
60721      i -= p->nOp;
60722      for(j=0; i>=apSub[j]->nOp; j++){
60723        i -= apSub[j]->nOp;
60724      }
60725      pOp = &apSub[j]->aOp[i];
60726    }
60727    if( p->explain==1 ){
60728      pMem->flags = MEM_Int;
60729      pMem->type = SQLITE_INTEGER;
60730      pMem->u.i = i;                                /* Program counter */
60731      pMem++;
60732
60733      pMem->flags = MEM_Static|MEM_Str|MEM_Term;
60734      pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
60735      assert( pMem->z!=0 );
60736      pMem->n = sqlite3Strlen30(pMem->z);
60737      pMem->type = SQLITE_TEXT;
60738      pMem->enc = SQLITE_UTF8;
60739      pMem++;
60740
60741      /* When an OP_Program opcode is encounter (the only opcode that has
60742      ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
60743      ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
60744      ** has not already been seen.
60745      */
60746      if( pOp->p4type==P4_SUBPROGRAM ){
60747        int nByte = (nSub+1)*sizeof(SubProgram*);
60748        int j;
60749        for(j=0; j<nSub; j++){
60750          if( apSub[j]==pOp->p4.pProgram ) break;
60751        }
60752        if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
60753          apSub = (SubProgram **)pSub->z;
60754          apSub[nSub++] = pOp->p4.pProgram;
60755          pSub->flags |= MEM_Blob;
60756          pSub->n = nSub*sizeof(SubProgram*);
60757        }
60758      }
60759    }
60760
60761    pMem->flags = MEM_Int;
60762    pMem->u.i = pOp->p1;                          /* P1 */
60763    pMem->type = SQLITE_INTEGER;
60764    pMem++;
60765
60766    pMem->flags = MEM_Int;
60767    pMem->u.i = pOp->p2;                          /* P2 */
60768    pMem->type = SQLITE_INTEGER;
60769    pMem++;
60770
60771    pMem->flags = MEM_Int;
60772    pMem->u.i = pOp->p3;                          /* P3 */
60773    pMem->type = SQLITE_INTEGER;
60774    pMem++;
60775
60776    if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
60777      assert( p->db->mallocFailed );
60778      return SQLITE_ERROR;
60779    }
60780    pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60781    z = displayP4(pOp, pMem->z, 32);
60782    if( z!=pMem->z ){
60783      sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
60784    }else{
60785      assert( pMem->z!=0 );
60786      pMem->n = sqlite3Strlen30(pMem->z);
60787      pMem->enc = SQLITE_UTF8;
60788    }
60789    pMem->type = SQLITE_TEXT;
60790    pMem++;
60791
60792    if( p->explain==1 ){
60793      if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
60794        assert( p->db->mallocFailed );
60795        return SQLITE_ERROR;
60796      }
60797      pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
60798      pMem->n = 2;
60799      sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
60800      pMem->type = SQLITE_TEXT;
60801      pMem->enc = SQLITE_UTF8;
60802      pMem++;
60803
60804#ifdef SQLITE_DEBUG
60805      if( pOp->zComment ){
60806        pMem->flags = MEM_Str|MEM_Term;
60807        pMem->z = pOp->zComment;
60808        pMem->n = sqlite3Strlen30(pMem->z);
60809        pMem->enc = SQLITE_UTF8;
60810        pMem->type = SQLITE_TEXT;
60811      }else
60812#endif
60813      {
60814        pMem->flags = MEM_Null;                       /* Comment */
60815        pMem->type = SQLITE_NULL;
60816      }
60817    }
60818
60819    p->nResColumn = 8 - 4*(p->explain-1);
60820    p->pResultSet = &p->aMem[1];
60821    p->rc = SQLITE_OK;
60822    rc = SQLITE_ROW;
60823  }
60824  return rc;
60825}
60826#endif /* SQLITE_OMIT_EXPLAIN */
60827
60828#ifdef SQLITE_DEBUG
60829/*
60830** Print the SQL that was used to generate a VDBE program.
60831*/
60832SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
60833  int nOp = p->nOp;
60834  VdbeOp *pOp;
60835  if( nOp<1 ) return;
60836  pOp = &p->aOp[0];
60837  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60838    const char *z = pOp->p4.z;
60839    while( sqlite3Isspace(*z) ) z++;
60840    printf("SQL: [%s]\n", z);
60841  }
60842}
60843#endif
60844
60845#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
60846/*
60847** Print an IOTRACE message showing SQL content.
60848*/
60849SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
60850  int nOp = p->nOp;
60851  VdbeOp *pOp;
60852  if( sqlite3IoTrace==0 ) return;
60853  if( nOp<1 ) return;
60854  pOp = &p->aOp[0];
60855  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
60856    int i, j;
60857    char z[1000];
60858    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
60859    for(i=0; sqlite3Isspace(z[i]); i++){}
60860    for(j=0; z[i]; i++){
60861      if( sqlite3Isspace(z[i]) ){
60862        if( z[i-1]!=' ' ){
60863          z[j++] = ' ';
60864        }
60865      }else{
60866        z[j++] = z[i];
60867      }
60868    }
60869    z[j] = 0;
60870    sqlite3IoTrace("SQL %s\n", z);
60871  }
60872}
60873#endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
60874
60875/*
60876** Allocate space from a fixed size buffer and return a pointer to
60877** that space.  If insufficient space is available, return NULL.
60878**
60879** The pBuf parameter is the initial value of a pointer which will
60880** receive the new memory.  pBuf is normally NULL.  If pBuf is not
60881** NULL, it means that memory space has already been allocated and that
60882** this routine should not allocate any new memory.  When pBuf is not
60883** NULL simply return pBuf.  Only allocate new memory space when pBuf
60884** is NULL.
60885**
60886** nByte is the number of bytes of space needed.
60887**
60888** *ppFrom points to available space and pEnd points to the end of the
60889** available space.  When space is allocated, *ppFrom is advanced past
60890** the end of the allocated space.
60891**
60892** *pnByte is a counter of the number of bytes of space that have failed
60893** to allocate.  If there is insufficient space in *ppFrom to satisfy the
60894** request, then increment *pnByte by the amount of the request.
60895*/
60896static void *allocSpace(
60897  void *pBuf,          /* Where return pointer will be stored */
60898  int nByte,           /* Number of bytes to allocate */
60899  u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
60900  u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
60901  int *pnByte          /* If allocation cannot be made, increment *pnByte */
60902){
60903  assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
60904  if( pBuf ) return pBuf;
60905  nByte = ROUND8(nByte);
60906  if( &(*ppFrom)[nByte] <= pEnd ){
60907    pBuf = (void*)*ppFrom;
60908    *ppFrom += nByte;
60909  }else{
60910    *pnByte += nByte;
60911  }
60912  return pBuf;
60913}
60914
60915/*
60916** Rewind the VDBE back to the beginning in preparation for
60917** running it.
60918*/
60919SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
60920#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
60921  int i;
60922#endif
60923  assert( p!=0 );
60924  assert( p->magic==VDBE_MAGIC_INIT );
60925
60926  /* There should be at least one opcode.
60927  */
60928  assert( p->nOp>0 );
60929
60930  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
60931  p->magic = VDBE_MAGIC_RUN;
60932
60933#ifdef SQLITE_DEBUG
60934  for(i=1; i<p->nMem; i++){
60935    assert( p->aMem[i].db==p->db );
60936  }
60937#endif
60938  p->pc = -1;
60939  p->rc = SQLITE_OK;
60940  p->errorAction = OE_Abort;
60941  p->magic = VDBE_MAGIC_RUN;
60942  p->nChange = 0;
60943  p->cacheCtr = 1;
60944  p->minWriteFileFormat = 255;
60945  p->iStatement = 0;
60946  p->nFkConstraint = 0;
60947#ifdef VDBE_PROFILE
60948  for(i=0; i<p->nOp; i++){
60949    p->aOp[i].cnt = 0;
60950    p->aOp[i].cycles = 0;
60951  }
60952#endif
60953}
60954
60955/*
60956** Prepare a virtual machine for execution for the first time after
60957** creating the virtual machine.  This involves things such
60958** as allocating stack space and initializing the program counter.
60959** After the VDBE has be prepped, it can be executed by one or more
60960** calls to sqlite3VdbeExec().
60961**
60962** This function may be called exact once on a each virtual machine.
60963** After this routine is called the VM has been "packaged" and is ready
60964** to run.  After this routine is called, futher calls to
60965** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
60966** the Vdbe from the Parse object that helped generate it so that the
60967** the Vdbe becomes an independent entity and the Parse object can be
60968** destroyed.
60969**
60970** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
60971** to its initial state after it has been run.
60972*/
60973SQLITE_PRIVATE void sqlite3VdbeMakeReady(
60974  Vdbe *p,                       /* The VDBE */
60975  Parse *pParse                  /* Parsing context */
60976){
60977  sqlite3 *db;                   /* The database connection */
60978  int nVar;                      /* Number of parameters */
60979  int nMem;                      /* Number of VM memory registers */
60980  int nCursor;                   /* Number of cursors required */
60981  int nArg;                      /* Number of arguments in subprograms */
60982  int nOnce;                     /* Number of OP_Once instructions */
60983  int n;                         /* Loop counter */
60984  u8 *zCsr;                      /* Memory available for allocation */
60985  u8 *zEnd;                      /* First byte past allocated memory */
60986  int nByte;                     /* How much extra memory is needed */
60987
60988  assert( p!=0 );
60989  assert( p->nOp>0 );
60990  assert( pParse!=0 );
60991  assert( p->magic==VDBE_MAGIC_INIT );
60992  db = p->db;
60993  assert( db->mallocFailed==0 );
60994  nVar = pParse->nVar;
60995  nMem = pParse->nMem;
60996  nCursor = pParse->nTab;
60997  nArg = pParse->nMaxArg;
60998  nOnce = pParse->nOnce;
60999  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
61000
61001  /* For each cursor required, also allocate a memory cell. Memory
61002  ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
61003  ** the vdbe program. Instead they are used to allocate space for
61004  ** VdbeCursor/BtCursor structures. The blob of memory associated with
61005  ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
61006  ** stores the blob of memory associated with cursor 1, etc.
61007  **
61008  ** See also: allocateCursor().
61009  */
61010  nMem += nCursor;
61011
61012  /* Allocate space for memory registers, SQL variables, VDBE cursors and
61013  ** an array to marshal SQL function arguments in.
61014  */
61015  zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
61016  zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
61017
61018  resolveP2Values(p, &nArg);
61019  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
61020  if( pParse->explain && nMem<10 ){
61021    nMem = 10;
61022  }
61023  memset(zCsr, 0, zEnd-zCsr);
61024  zCsr += (zCsr - (u8*)0)&7;
61025  assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
61026  p->expired = 0;
61027
61028  /* Memory for registers, parameters, cursor, etc, is allocated in two
61029  ** passes.  On the first pass, we try to reuse unused space at the
61030  ** end of the opcode array.  If we are unable to satisfy all memory
61031  ** requirements by reusing the opcode array tail, then the second
61032  ** pass will fill in the rest using a fresh allocation.
61033  **
61034  ** This two-pass approach that reuses as much memory as possible from
61035  ** the leftover space at the end of the opcode array can significantly
61036  ** reduce the amount of memory held by a prepared statement.
61037  */
61038  do {
61039    nByte = 0;
61040    p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
61041    p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
61042    p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
61043    p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
61044    p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
61045                          &zCsr, zEnd, &nByte);
61046    p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
61047    if( nByte ){
61048      p->pFree = sqlite3DbMallocZero(db, nByte);
61049    }
61050    zCsr = p->pFree;
61051    zEnd = &zCsr[nByte];
61052  }while( nByte && !db->mallocFailed );
61053
61054  p->nCursor = (u16)nCursor;
61055  p->nOnceFlag = nOnce;
61056  if( p->aVar ){
61057    p->nVar = (ynVar)nVar;
61058    for(n=0; n<nVar; n++){
61059      p->aVar[n].flags = MEM_Null;
61060      p->aVar[n].db = db;
61061    }
61062  }
61063  if( p->azVar ){
61064    p->nzVar = pParse->nzVar;
61065    memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
61066    memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
61067  }
61068  if( p->aMem ){
61069    p->aMem--;                      /* aMem[] goes from 1..nMem */
61070    p->nMem = nMem;                 /*       not from 0..nMem-1 */
61071    for(n=1; n<=nMem; n++){
61072      p->aMem[n].flags = MEM_Invalid;
61073      p->aMem[n].db = db;
61074    }
61075  }
61076  p->explain = pParse->explain;
61077  sqlite3VdbeRewind(p);
61078}
61079
61080/*
61081** Close a VDBE cursor and release all the resources that cursor
61082** happens to hold.
61083*/
61084SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
61085  if( pCx==0 ){
61086    return;
61087  }
61088  sqlite3VdbeSorterClose(p->db, pCx);
61089  if( pCx->pBt ){
61090    sqlite3BtreeClose(pCx->pBt);
61091    /* The pCx->pCursor will be close automatically, if it exists, by
61092    ** the call above. */
61093  }else if( pCx->pCursor ){
61094    sqlite3BtreeCloseCursor(pCx->pCursor);
61095  }
61096#ifndef SQLITE_OMIT_VIRTUALTABLE
61097  if( pCx->pVtabCursor ){
61098    sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
61099    const sqlite3_module *pModule = pCx->pModule;
61100    p->inVtabMethod = 1;
61101    pModule->xClose(pVtabCursor);
61102    p->inVtabMethod = 0;
61103  }
61104#endif
61105}
61106
61107/*
61108** Copy the values stored in the VdbeFrame structure to its Vdbe. This
61109** is used, for example, when a trigger sub-program is halted to restore
61110** control to the main program.
61111*/
61112SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
61113  Vdbe *v = pFrame->v;
61114  v->aOnceFlag = pFrame->aOnceFlag;
61115  v->nOnceFlag = pFrame->nOnceFlag;
61116  v->aOp = pFrame->aOp;
61117  v->nOp = pFrame->nOp;
61118  v->aMem = pFrame->aMem;
61119  v->nMem = pFrame->nMem;
61120  v->apCsr = pFrame->apCsr;
61121  v->nCursor = pFrame->nCursor;
61122  v->db->lastRowid = pFrame->lastRowid;
61123  v->nChange = pFrame->nChange;
61124  return pFrame->pc;
61125}
61126
61127/*
61128** Close all cursors.
61129**
61130** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
61131** cell array. This is necessary as the memory cell array may contain
61132** pointers to VdbeFrame objects, which may in turn contain pointers to
61133** open cursors.
61134*/
61135static void closeAllCursors(Vdbe *p){
61136  if( p->pFrame ){
61137    VdbeFrame *pFrame;
61138    for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
61139    sqlite3VdbeFrameRestore(pFrame);
61140  }
61141  p->pFrame = 0;
61142  p->nFrame = 0;
61143
61144  if( p->apCsr ){
61145    int i;
61146    for(i=0; i<p->nCursor; i++){
61147      VdbeCursor *pC = p->apCsr[i];
61148      if( pC ){
61149        sqlite3VdbeFreeCursor(p, pC);
61150        p->apCsr[i] = 0;
61151      }
61152    }
61153  }
61154  if( p->aMem ){
61155    releaseMemArray(&p->aMem[1], p->nMem);
61156  }
61157  while( p->pDelFrame ){
61158    VdbeFrame *pDel = p->pDelFrame;
61159    p->pDelFrame = pDel->pParent;
61160    sqlite3VdbeFrameDelete(pDel);
61161  }
61162}
61163
61164/*
61165** Clean up the VM after execution.
61166**
61167** This routine will automatically close any cursors, lists, and/or
61168** sorters that were left open.  It also deletes the values of
61169** variables in the aVar[] array.
61170*/
61171static void Cleanup(Vdbe *p){
61172  sqlite3 *db = p->db;
61173
61174#ifdef SQLITE_DEBUG
61175  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
61176  ** Vdbe.aMem[] arrays have already been cleaned up.  */
61177  int i;
61178  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
61179  if( p->aMem ){
61180    for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
61181  }
61182#endif
61183
61184  sqlite3DbFree(db, p->zErrMsg);
61185  p->zErrMsg = 0;
61186  p->pResultSet = 0;
61187}
61188
61189/*
61190** Set the number of result columns that will be returned by this SQL
61191** statement. This is now set at compile time, rather than during
61192** execution of the vdbe program so that sqlite3_column_count() can
61193** be called on an SQL statement before sqlite3_step().
61194*/
61195SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
61196  Mem *pColName;
61197  int n;
61198  sqlite3 *db = p->db;
61199
61200  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61201  sqlite3DbFree(db, p->aColName);
61202  n = nResColumn*COLNAME_N;
61203  p->nResColumn = (u16)nResColumn;
61204  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
61205  if( p->aColName==0 ) return;
61206  while( n-- > 0 ){
61207    pColName->flags = MEM_Null;
61208    pColName->db = p->db;
61209    pColName++;
61210  }
61211}
61212
61213/*
61214** Set the name of the idx'th column to be returned by the SQL statement.
61215** zName must be a pointer to a nul terminated string.
61216**
61217** This call must be made after a call to sqlite3VdbeSetNumCols().
61218**
61219** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
61220** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
61221** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
61222*/
61223SQLITE_PRIVATE int sqlite3VdbeSetColName(
61224  Vdbe *p,                         /* Vdbe being configured */
61225  int idx,                         /* Index of column zName applies to */
61226  int var,                         /* One of the COLNAME_* constants */
61227  const char *zName,               /* Pointer to buffer containing name */
61228  void (*xDel)(void*)              /* Memory management strategy for zName */
61229){
61230  int rc;
61231  Mem *pColName;
61232  assert( idx<p->nResColumn );
61233  assert( var<COLNAME_N );
61234  if( p->db->mallocFailed ){
61235    assert( !zName || xDel!=SQLITE_DYNAMIC );
61236    return SQLITE_NOMEM;
61237  }
61238  assert( p->aColName!=0 );
61239  pColName = &(p->aColName[idx+var*p->nResColumn]);
61240  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
61241  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
61242  return rc;
61243}
61244
61245/*
61246** A read or write transaction may or may not be active on database handle
61247** db. If a transaction is active, commit it. If there is a
61248** write-transaction spanning more than one database file, this routine
61249** takes care of the master journal trickery.
61250*/
61251static int vdbeCommit(sqlite3 *db, Vdbe *p){
61252  int i;
61253  int nTrans = 0;  /* Number of databases with an active write-transaction */
61254  int rc = SQLITE_OK;
61255  int needXcommit = 0;
61256
61257#ifdef SQLITE_OMIT_VIRTUALTABLE
61258  /* With this option, sqlite3VtabSync() is defined to be simply
61259  ** SQLITE_OK so p is not used.
61260  */
61261  UNUSED_PARAMETER(p);
61262#endif
61263
61264  /* Before doing anything else, call the xSync() callback for any
61265  ** virtual module tables written in this transaction. This has to
61266  ** be done before determining whether a master journal file is
61267  ** required, as an xSync() callback may add an attached database
61268  ** to the transaction.
61269  */
61270  rc = sqlite3VtabSync(db, &p->zErrMsg);
61271
61272  /* This loop determines (a) if the commit hook should be invoked and
61273  ** (b) how many database files have open write transactions, not
61274  ** including the temp database. (b) is important because if more than
61275  ** one database file has an open write transaction, a master journal
61276  ** file is required for an atomic commit.
61277  */
61278  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61279    Btree *pBt = db->aDb[i].pBt;
61280    if( sqlite3BtreeIsInTrans(pBt) ){
61281      needXcommit = 1;
61282      if( i!=1 ) nTrans++;
61283      rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
61284    }
61285  }
61286  if( rc!=SQLITE_OK ){
61287    return rc;
61288  }
61289
61290  /* If there are any write-transactions at all, invoke the commit hook */
61291  if( needXcommit && db->xCommitCallback ){
61292    rc = db->xCommitCallback(db->pCommitArg);
61293    if( rc ){
61294      return SQLITE_CONSTRAINT;
61295    }
61296  }
61297
61298  /* The simple case - no more than one database file (not counting the
61299  ** TEMP database) has a transaction active.   There is no need for the
61300  ** master-journal.
61301  **
61302  ** If the return value of sqlite3BtreeGetFilename() is a zero length
61303  ** string, it means the main database is :memory: or a temp file.  In
61304  ** that case we do not support atomic multi-file commits, so use the
61305  ** simple case then too.
61306  */
61307  if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
61308   || nTrans<=1
61309  ){
61310    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61311      Btree *pBt = db->aDb[i].pBt;
61312      if( pBt ){
61313        rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
61314      }
61315    }
61316
61317    /* Do the commit only if all databases successfully complete phase 1.
61318    ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
61319    ** IO error while deleting or truncating a journal file. It is unlikely,
61320    ** but could happen. In this case abandon processing and return the error.
61321    */
61322    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61323      Btree *pBt = db->aDb[i].pBt;
61324      if( pBt ){
61325        rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
61326      }
61327    }
61328    if( rc==SQLITE_OK ){
61329      sqlite3VtabCommit(db);
61330    }
61331  }
61332
61333  /* The complex case - There is a multi-file write-transaction active.
61334  ** This requires a master journal file to ensure the transaction is
61335  ** committed atomicly.
61336  */
61337#ifndef SQLITE_OMIT_DISKIO
61338  else{
61339    sqlite3_vfs *pVfs = db->pVfs;
61340    int needSync = 0;
61341    char *zMaster = 0;   /* File-name for the master journal */
61342    char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
61343    sqlite3_file *pMaster = 0;
61344    i64 offset = 0;
61345    int res;
61346    int retryCount = 0;
61347    int nMainFile;
61348
61349    /* Select a master journal file name */
61350    nMainFile = sqlite3Strlen30(zMainFile);
61351    zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
61352    if( zMaster==0 ) return SQLITE_NOMEM;
61353    do {
61354      u32 iRandom;
61355      if( retryCount ){
61356        if( retryCount>100 ){
61357          sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
61358          sqlite3OsDelete(pVfs, zMaster, 0);
61359          break;
61360        }else if( retryCount==1 ){
61361          sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
61362        }
61363      }
61364      retryCount++;
61365      sqlite3_randomness(sizeof(iRandom), &iRandom);
61366      sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
61367                               (iRandom>>8)&0xffffff, iRandom&0xff);
61368      /* The antipenultimate character of the master journal name must
61369      ** be "9" to avoid name collisions when using 8+3 filenames. */
61370      assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
61371      sqlite3FileSuffix3(zMainFile, zMaster);
61372      rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
61373    }while( rc==SQLITE_OK && res );
61374    if( rc==SQLITE_OK ){
61375      /* Open the master journal. */
61376      rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
61377          SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
61378          SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
61379      );
61380    }
61381    if( rc!=SQLITE_OK ){
61382      sqlite3DbFree(db, zMaster);
61383      return rc;
61384    }
61385
61386    /* Write the name of each database file in the transaction into the new
61387    ** master journal file. If an error occurs at this point close
61388    ** and delete the master journal file. All the individual journal files
61389    ** still have 'null' as the master journal pointer, so they will roll
61390    ** back independently if a failure occurs.
61391    */
61392    for(i=0; i<db->nDb; i++){
61393      Btree *pBt = db->aDb[i].pBt;
61394      if( sqlite3BtreeIsInTrans(pBt) ){
61395        char const *zFile = sqlite3BtreeGetJournalname(pBt);
61396        if( zFile==0 ){
61397          continue;  /* Ignore TEMP and :memory: databases */
61398        }
61399        assert( zFile[0]!=0 );
61400        if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
61401          needSync = 1;
61402        }
61403        rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
61404        offset += sqlite3Strlen30(zFile)+1;
61405        if( rc!=SQLITE_OK ){
61406          sqlite3OsCloseFree(pMaster);
61407          sqlite3OsDelete(pVfs, zMaster, 0);
61408          sqlite3DbFree(db, zMaster);
61409          return rc;
61410        }
61411      }
61412    }
61413
61414    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
61415    ** flag is set this is not required.
61416    */
61417    if( needSync
61418     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
61419     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
61420    ){
61421      sqlite3OsCloseFree(pMaster);
61422      sqlite3OsDelete(pVfs, zMaster, 0);
61423      sqlite3DbFree(db, zMaster);
61424      return rc;
61425    }
61426
61427    /* Sync all the db files involved in the transaction. The same call
61428    ** sets the master journal pointer in each individual journal. If
61429    ** an error occurs here, do not delete the master journal file.
61430    **
61431    ** If the error occurs during the first call to
61432    ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
61433    ** master journal file will be orphaned. But we cannot delete it,
61434    ** in case the master journal file name was written into the journal
61435    ** file before the failure occurred.
61436    */
61437    for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61438      Btree *pBt = db->aDb[i].pBt;
61439      if( pBt ){
61440        rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
61441      }
61442    }
61443    sqlite3OsCloseFree(pMaster);
61444    assert( rc!=SQLITE_BUSY );
61445    if( rc!=SQLITE_OK ){
61446      sqlite3DbFree(db, zMaster);
61447      return rc;
61448    }
61449
61450    /* Delete the master journal file. This commits the transaction. After
61451    ** doing this the directory is synced again before any individual
61452    ** transaction files are deleted.
61453    */
61454    rc = sqlite3OsDelete(pVfs, zMaster, 1);
61455    sqlite3DbFree(db, zMaster);
61456    zMaster = 0;
61457    if( rc ){
61458      return rc;
61459    }
61460
61461    /* All files and directories have already been synced, so the following
61462    ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
61463    ** deleting or truncating journals. If something goes wrong while
61464    ** this is happening we don't really care. The integrity of the
61465    ** transaction is already guaranteed, but some stray 'cold' journals
61466    ** may be lying around. Returning an error code won't help matters.
61467    */
61468    disable_simulated_io_errors();
61469    sqlite3BeginBenignMalloc();
61470    for(i=0; i<db->nDb; i++){
61471      Btree *pBt = db->aDb[i].pBt;
61472      if( pBt ){
61473        sqlite3BtreeCommitPhaseTwo(pBt, 1);
61474      }
61475    }
61476    sqlite3EndBenignMalloc();
61477    enable_simulated_io_errors();
61478
61479    sqlite3VtabCommit(db);
61480  }
61481#endif
61482
61483  return rc;
61484}
61485
61486/*
61487** This routine checks that the sqlite3.activeVdbeCnt count variable
61488** matches the number of vdbe's in the list sqlite3.pVdbe that are
61489** currently active. An assertion fails if the two counts do not match.
61490** This is an internal self-check only - it is not an essential processing
61491** step.
61492**
61493** This is a no-op if NDEBUG is defined.
61494*/
61495#ifndef NDEBUG
61496static void checkActiveVdbeCnt(sqlite3 *db){
61497  Vdbe *p;
61498  int cnt = 0;
61499  int nWrite = 0;
61500  p = db->pVdbe;
61501  while( p ){
61502    if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
61503      cnt++;
61504      if( p->readOnly==0 ) nWrite++;
61505    }
61506    p = p->pNext;
61507  }
61508  assert( cnt==db->activeVdbeCnt );
61509  assert( nWrite==db->writeVdbeCnt );
61510}
61511#else
61512#define checkActiveVdbeCnt(x)
61513#endif
61514
61515/*
61516** If the Vdbe passed as the first argument opened a statement-transaction,
61517** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
61518** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
61519** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
61520** statement transaction is commtted.
61521**
61522** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
61523** Otherwise SQLITE_OK.
61524*/
61525SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
61526  sqlite3 *const db = p->db;
61527  int rc = SQLITE_OK;
61528
61529  /* If p->iStatement is greater than zero, then this Vdbe opened a
61530  ** statement transaction that should be closed here. The only exception
61531  ** is that an IO error may have occured, causing an emergency rollback.
61532  ** In this case (db->nStatement==0), and there is nothing to do.
61533  */
61534  if( db->nStatement && p->iStatement ){
61535    int i;
61536    const int iSavepoint = p->iStatement-1;
61537
61538    assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
61539    assert( db->nStatement>0 );
61540    assert( p->iStatement==(db->nStatement+db->nSavepoint) );
61541
61542    for(i=0; i<db->nDb; i++){
61543      int rc2 = SQLITE_OK;
61544      Btree *pBt = db->aDb[i].pBt;
61545      if( pBt ){
61546        if( eOp==SAVEPOINT_ROLLBACK ){
61547          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
61548        }
61549        if( rc2==SQLITE_OK ){
61550          rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
61551        }
61552        if( rc==SQLITE_OK ){
61553          rc = rc2;
61554        }
61555      }
61556    }
61557    db->nStatement--;
61558    p->iStatement = 0;
61559
61560    if( rc==SQLITE_OK ){
61561      if( eOp==SAVEPOINT_ROLLBACK ){
61562        rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
61563      }
61564      if( rc==SQLITE_OK ){
61565        rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
61566      }
61567    }
61568
61569    /* If the statement transaction is being rolled back, also restore the
61570    ** database handles deferred constraint counter to the value it had when
61571    ** the statement transaction was opened.  */
61572    if( eOp==SAVEPOINT_ROLLBACK ){
61573      db->nDeferredCons = p->nStmtDefCons;
61574    }
61575  }
61576  return rc;
61577}
61578
61579/*
61580** This function is called when a transaction opened by the database
61581** handle associated with the VM passed as an argument is about to be
61582** committed. If there are outstanding deferred foreign key constraint
61583** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
61584**
61585** If there are outstanding FK violations and this function returns
61586** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
61587** an error message to it. Then return SQLITE_ERROR.
61588*/
61589#ifndef SQLITE_OMIT_FOREIGN_KEY
61590SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
61591  sqlite3 *db = p->db;
61592  if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
61593    p->rc = SQLITE_CONSTRAINT;
61594    p->errorAction = OE_Abort;
61595    sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
61596    return SQLITE_ERROR;
61597  }
61598  return SQLITE_OK;
61599}
61600#endif
61601
61602/*
61603** This routine is called the when a VDBE tries to halt.  If the VDBE
61604** has made changes and is in autocommit mode, then commit those
61605** changes.  If a rollback is needed, then do the rollback.
61606**
61607** This routine is the only way to move the state of a VM from
61608** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
61609** call this on a VM that is in the SQLITE_MAGIC_HALT state.
61610**
61611** Return an error code.  If the commit could not complete because of
61612** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
61613** means the close did not happen and needs to be repeated.
61614*/
61615SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
61616  int rc;                         /* Used to store transient return codes */
61617  sqlite3 *db = p->db;
61618
61619  /* This function contains the logic that determines if a statement or
61620  ** transaction will be committed or rolled back as a result of the
61621  ** execution of this virtual machine.
61622  **
61623  ** If any of the following errors occur:
61624  **
61625  **     SQLITE_NOMEM
61626  **     SQLITE_IOERR
61627  **     SQLITE_FULL
61628  **     SQLITE_INTERRUPT
61629  **
61630  ** Then the internal cache might have been left in an inconsistent
61631  ** state.  We need to rollback the statement transaction, if there is
61632  ** one, or the complete transaction if there is no statement transaction.
61633  */
61634
61635  if( p->db->mallocFailed ){
61636    p->rc = SQLITE_NOMEM;
61637  }
61638  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
61639  closeAllCursors(p);
61640  if( p->magic!=VDBE_MAGIC_RUN ){
61641    return SQLITE_OK;
61642  }
61643  checkActiveVdbeCnt(db);
61644
61645  /* No commit or rollback needed if the program never started */
61646  if( p->pc>=0 ){
61647    int mrc;   /* Primary error code from p->rc */
61648    int eStatementOp = 0;
61649    int isSpecialError;            /* Set to true if a 'special' error */
61650
61651    /* Lock all btrees used by the statement */
61652    sqlite3VdbeEnter(p);
61653
61654    /* Check for one of the special errors */
61655    mrc = p->rc & 0xff;
61656    assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
61657    isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
61658                     || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
61659    if( isSpecialError ){
61660      /* If the query was read-only and the error code is SQLITE_INTERRUPT,
61661      ** no rollback is necessary. Otherwise, at least a savepoint
61662      ** transaction must be rolled back to restore the database to a
61663      ** consistent state.
61664      **
61665      ** Even if the statement is read-only, it is important to perform
61666      ** a statement or transaction rollback operation. If the error
61667      ** occured while writing to the journal, sub-journal or database
61668      ** file as part of an effort to free up cache space (see function
61669      ** pagerStress() in pager.c), the rollback is required to restore
61670      ** the pager to a consistent state.
61671      */
61672      if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
61673        if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
61674          eStatementOp = SAVEPOINT_ROLLBACK;
61675        }else{
61676          /* We are forced to roll back the active transaction. Before doing
61677          ** so, abort any other statements this handle currently has active.
61678          */
61679          sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
61680          sqlite3CloseSavepoints(db);
61681          db->autoCommit = 1;
61682        }
61683      }
61684    }
61685
61686    /* Check for immediate foreign key violations. */
61687    if( p->rc==SQLITE_OK ){
61688      sqlite3VdbeCheckFk(p, 0);
61689    }
61690
61691    /* If the auto-commit flag is set and this is the only active writer
61692    ** VM, then we do either a commit or rollback of the current transaction.
61693    **
61694    ** Note: This block also runs if one of the special errors handled
61695    ** above has occurred.
61696    */
61697    if( !sqlite3VtabInSync(db)
61698     && db->autoCommit
61699     && db->writeVdbeCnt==(p->readOnly==0)
61700    ){
61701      if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
61702        rc = sqlite3VdbeCheckFk(p, 1);
61703        if( rc!=SQLITE_OK ){
61704          if( NEVER(p->readOnly) ){
61705            sqlite3VdbeLeave(p);
61706            return SQLITE_ERROR;
61707          }
61708          rc = SQLITE_CONSTRAINT;
61709        }else{
61710          /* The auto-commit flag is true, the vdbe program was successful
61711          ** or hit an 'OR FAIL' constraint and there are no deferred foreign
61712          ** key constraints to hold up the transaction. This means a commit
61713          ** is required. */
61714          rc = vdbeCommit(db, p);
61715        }
61716        if( rc==SQLITE_BUSY && p->readOnly ){
61717          sqlite3VdbeLeave(p);
61718          return SQLITE_BUSY;
61719        }else if( rc!=SQLITE_OK ){
61720          p->rc = rc;
61721          sqlite3RollbackAll(db, SQLITE_OK);
61722        }else{
61723          db->nDeferredCons = 0;
61724          sqlite3CommitInternalChanges(db);
61725        }
61726      }else{
61727        sqlite3RollbackAll(db, SQLITE_OK);
61728      }
61729      db->nStatement = 0;
61730    }else if( eStatementOp==0 ){
61731      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
61732        eStatementOp = SAVEPOINT_RELEASE;
61733      }else if( p->errorAction==OE_Abort ){
61734        eStatementOp = SAVEPOINT_ROLLBACK;
61735      }else{
61736        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
61737        sqlite3CloseSavepoints(db);
61738        db->autoCommit = 1;
61739      }
61740    }
61741
61742    /* If eStatementOp is non-zero, then a statement transaction needs to
61743    ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
61744    ** do so. If this operation returns an error, and the current statement
61745    ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
61746    ** current statement error code.
61747    */
61748    if( eStatementOp ){
61749      rc = sqlite3VdbeCloseStatement(p, eStatementOp);
61750      if( rc ){
61751        if( p->rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT ){
61752          p->rc = rc;
61753          sqlite3DbFree(db, p->zErrMsg);
61754          p->zErrMsg = 0;
61755        }
61756        sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
61757        sqlite3CloseSavepoints(db);
61758        db->autoCommit = 1;
61759      }
61760    }
61761
61762    /* If this was an INSERT, UPDATE or DELETE and no statement transaction
61763    ** has been rolled back, update the database connection change-counter.
61764    */
61765    if( p->changeCntOn ){
61766      if( eStatementOp!=SAVEPOINT_ROLLBACK ){
61767        sqlite3VdbeSetChanges(db, p->nChange);
61768      }else{
61769        sqlite3VdbeSetChanges(db, 0);
61770      }
61771      p->nChange = 0;
61772    }
61773
61774    /* Release the locks */
61775    sqlite3VdbeLeave(p);
61776  }
61777
61778  /* We have successfully halted and closed the VM.  Record this fact. */
61779  if( p->pc>=0 ){
61780    db->activeVdbeCnt--;
61781    if( !p->readOnly ){
61782      db->writeVdbeCnt--;
61783    }
61784    assert( db->activeVdbeCnt>=db->writeVdbeCnt );
61785  }
61786  p->magic = VDBE_MAGIC_HALT;
61787  checkActiveVdbeCnt(db);
61788  if( p->db->mallocFailed ){
61789    p->rc = SQLITE_NOMEM;
61790  }
61791
61792  /* If the auto-commit flag is set to true, then any locks that were held
61793  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
61794  ** to invoke any required unlock-notify callbacks.
61795  */
61796  if( db->autoCommit ){
61797    sqlite3ConnectionUnlocked(db);
61798  }
61799
61800  assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
61801  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
61802}
61803
61804
61805/*
61806** Each VDBE holds the result of the most recent sqlite3_step() call
61807** in p->rc.  This routine sets that result back to SQLITE_OK.
61808*/
61809SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
61810  p->rc = SQLITE_OK;
61811}
61812
61813/*
61814** Copy the error code and error message belonging to the VDBE passed
61815** as the first argument to its database handle (so that they will be
61816** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
61817**
61818** This function does not clear the VDBE error code or message, just
61819** copies them to the database handle.
61820*/
61821SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
61822  sqlite3 *db = p->db;
61823  int rc = p->rc;
61824  if( p->zErrMsg ){
61825    u8 mallocFailed = db->mallocFailed;
61826    sqlite3BeginBenignMalloc();
61827    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
61828    sqlite3EndBenignMalloc();
61829    db->mallocFailed = mallocFailed;
61830    db->errCode = rc;
61831  }else{
61832    sqlite3Error(db, rc, 0);
61833  }
61834  return rc;
61835}
61836
61837/*
61838** Clean up a VDBE after execution but do not delete the VDBE just yet.
61839** Write any error messages into *pzErrMsg.  Return the result code.
61840**
61841** After this routine is run, the VDBE should be ready to be executed
61842** again.
61843**
61844** To look at it another way, this routine resets the state of the
61845** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
61846** VDBE_MAGIC_INIT.
61847*/
61848SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
61849  sqlite3 *db;
61850  db = p->db;
61851
61852  /* If the VM did not run to completion or if it encountered an
61853  ** error, then it might not have been halted properly.  So halt
61854  ** it now.
61855  */
61856  sqlite3VdbeHalt(p);
61857
61858  /* If the VDBE has be run even partially, then transfer the error code
61859  ** and error message from the VDBE into the main database structure.  But
61860  ** if the VDBE has just been set to run but has not actually executed any
61861  ** instructions yet, leave the main database error information unchanged.
61862  */
61863  if( p->pc>=0 ){
61864    sqlite3VdbeTransferError(p);
61865    sqlite3DbFree(db, p->zErrMsg);
61866    p->zErrMsg = 0;
61867    if( p->runOnlyOnce ) p->expired = 1;
61868  }else if( p->rc && p->expired ){
61869    /* The expired flag was set on the VDBE before the first call
61870    ** to sqlite3_step(). For consistency (since sqlite3_step() was
61871    ** called), set the database error in this case as well.
61872    */
61873    sqlite3Error(db, p->rc, 0);
61874    sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
61875    sqlite3DbFree(db, p->zErrMsg);
61876    p->zErrMsg = 0;
61877  }
61878
61879  /* Reclaim all memory used by the VDBE
61880  */
61881  Cleanup(p);
61882
61883  /* Save profiling information from this VDBE run.
61884  */
61885#ifdef VDBE_PROFILE
61886  {
61887    FILE *out = fopen("vdbe_profile.out", "a");
61888    if( out ){
61889      int i;
61890      fprintf(out, "---- ");
61891      for(i=0; i<p->nOp; i++){
61892        fprintf(out, "%02x", p->aOp[i].opcode);
61893      }
61894      fprintf(out, "\n");
61895      for(i=0; i<p->nOp; i++){
61896        fprintf(out, "%6d %10lld %8lld ",
61897           p->aOp[i].cnt,
61898           p->aOp[i].cycles,
61899           p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
61900        );
61901        sqlite3VdbePrintOp(out, i, &p->aOp[i]);
61902      }
61903      fclose(out);
61904    }
61905  }
61906#endif
61907  p->magic = VDBE_MAGIC_INIT;
61908  return p->rc & db->errMask;
61909}
61910
61911/*
61912** Clean up and delete a VDBE after execution.  Return an integer which is
61913** the result code.  Write any error message text into *pzErrMsg.
61914*/
61915SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
61916  int rc = SQLITE_OK;
61917  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
61918    rc = sqlite3VdbeReset(p);
61919    assert( (rc & p->db->errMask)==rc );
61920  }
61921  sqlite3VdbeDelete(p);
61922  return rc;
61923}
61924
61925/*
61926** Call the destructor for each auxdata entry in pVdbeFunc for which
61927** the corresponding bit in mask is clear.  Auxdata entries beyond 31
61928** are always destroyed.  To destroy all auxdata entries, call this
61929** routine with mask==0.
61930*/
61931SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
61932  int i;
61933  for(i=0; i<pVdbeFunc->nAux; i++){
61934    struct AuxData *pAux = &pVdbeFunc->apAux[i];
61935    if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
61936      if( pAux->xDelete ){
61937        pAux->xDelete(pAux->pAux);
61938      }
61939      pAux->pAux = 0;
61940    }
61941  }
61942}
61943
61944/*
61945** Free all memory associated with the Vdbe passed as the second argument.
61946** The difference between this function and sqlite3VdbeDelete() is that
61947** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
61948** the database connection.
61949*/
61950SQLITE_PRIVATE void sqlite3VdbeDeleteObject(sqlite3 *db, Vdbe *p){
61951  SubProgram *pSub, *pNext;
61952  int i;
61953  assert( p->db==0 || p->db==db );
61954  releaseMemArray(p->aVar, p->nVar);
61955  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61956  for(pSub=p->pProgram; pSub; pSub=pNext){
61957    pNext = pSub->pNext;
61958    vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
61959    sqlite3DbFree(db, pSub);
61960  }
61961  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
61962  vdbeFreeOpArray(db, p->aOp, p->nOp);
61963  sqlite3DbFree(db, p->aLabel);
61964  sqlite3DbFree(db, p->aColName);
61965  sqlite3DbFree(db, p->zSql);
61966  sqlite3DbFree(db, p->pFree);
61967#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
61968  sqlite3DbFree(db, p->zExplain);
61969  sqlite3DbFree(db, p->pExplain);
61970#endif
61971  sqlite3DbFree(db, p);
61972}
61973
61974/*
61975** Delete an entire VDBE.
61976*/
61977SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
61978  sqlite3 *db;
61979
61980  if( NEVER(p==0) ) return;
61981  db = p->db;
61982  if( p->pPrev ){
61983    p->pPrev->pNext = p->pNext;
61984  }else{
61985    assert( db->pVdbe==p );
61986    db->pVdbe = p->pNext;
61987  }
61988  if( p->pNext ){
61989    p->pNext->pPrev = p->pPrev;
61990  }
61991  p->magic = VDBE_MAGIC_DEAD;
61992  p->db = 0;
61993  sqlite3VdbeDeleteObject(db, p);
61994}
61995
61996/*
61997** Make sure the cursor p is ready to read or write the row to which it
61998** was last positioned.  Return an error code if an OOM fault or I/O error
61999** prevents us from positioning the cursor to its correct position.
62000**
62001** If a MoveTo operation is pending on the given cursor, then do that
62002** MoveTo now.  If no move is pending, check to see if the row has been
62003** deleted out from under the cursor and if it has, mark the row as
62004** a NULL row.
62005**
62006** If the cursor is already pointing to the correct row and that row has
62007** not been deleted out from under the cursor, then this routine is a no-op.
62008*/
62009SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
62010  if( p->deferredMoveto ){
62011    int res, rc;
62012#ifdef SQLITE_TEST
62013    extern int sqlite3_search_count;
62014#endif
62015    assert( p->isTable );
62016    rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
62017    if( rc ) return rc;
62018    p->lastRowid = p->movetoTarget;
62019    if( res!=0 ) return SQLITE_CORRUPT_BKPT;
62020    p->rowidIsValid = 1;
62021#ifdef SQLITE_TEST
62022    sqlite3_search_count++;
62023#endif
62024    p->deferredMoveto = 0;
62025    p->cacheStatus = CACHE_STALE;
62026  }else if( ALWAYS(p->pCursor) ){
62027    int hasMoved;
62028    int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
62029    if( rc ) return rc;
62030    if( hasMoved ){
62031      p->cacheStatus = CACHE_STALE;
62032      p->nullRow = 1;
62033    }
62034  }
62035  return SQLITE_OK;
62036}
62037
62038/*
62039** The following functions:
62040**
62041** sqlite3VdbeSerialType()
62042** sqlite3VdbeSerialTypeLen()
62043** sqlite3VdbeSerialLen()
62044** sqlite3VdbeSerialPut()
62045** sqlite3VdbeSerialGet()
62046**
62047** encapsulate the code that serializes values for storage in SQLite
62048** data and index records. Each serialized value consists of a
62049** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
62050** integer, stored as a varint.
62051**
62052** In an SQLite index record, the serial type is stored directly before
62053** the blob of data that it corresponds to. In a table record, all serial
62054** types are stored at the start of the record, and the blobs of data at
62055** the end. Hence these functions allow the caller to handle the
62056** serial-type and data blob seperately.
62057**
62058** The following table describes the various storage classes for data:
62059**
62060**   serial type        bytes of data      type
62061**   --------------     ---------------    ---------------
62062**      0                     0            NULL
62063**      1                     1            signed integer
62064**      2                     2            signed integer
62065**      3                     3            signed integer
62066**      4                     4            signed integer
62067**      5                     6            signed integer
62068**      6                     8            signed integer
62069**      7                     8            IEEE float
62070**      8                     0            Integer constant 0
62071**      9                     0            Integer constant 1
62072**     10,11                               reserved for expansion
62073**    N>=12 and even       (N-12)/2        BLOB
62074**    N>=13 and odd        (N-13)/2        text
62075**
62076** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
62077** of SQLite will not understand those serial types.
62078*/
62079
62080/*
62081** Return the serial-type for the value stored in pMem.
62082*/
62083SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
62084  int flags = pMem->flags;
62085  int n;
62086
62087  if( flags&MEM_Null ){
62088    return 0;
62089  }
62090  if( flags&MEM_Int ){
62091    /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
62092#   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
62093    i64 i = pMem->u.i;
62094    u64 u;
62095    if( file_format>=4 && (i&1)==i ){
62096      return 8+(u32)i;
62097    }
62098    if( i<0 ){
62099      if( i<(-MAX_6BYTE) ) return 6;
62100      /* Previous test prevents:  u = -(-9223372036854775808) */
62101      u = -i;
62102    }else{
62103      u = i;
62104    }
62105    if( u<=127 ) return 1;
62106    if( u<=32767 ) return 2;
62107    if( u<=8388607 ) return 3;
62108    if( u<=2147483647 ) return 4;
62109    if( u<=MAX_6BYTE ) return 5;
62110    return 6;
62111  }
62112  if( flags&MEM_Real ){
62113    return 7;
62114  }
62115  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
62116  n = pMem->n;
62117  if( flags & MEM_Zero ){
62118    n += pMem->u.nZero;
62119  }
62120  assert( n>=0 );
62121  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
62122}
62123
62124/*
62125** Return the length of the data corresponding to the supplied serial-type.
62126*/
62127SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
62128  if( serial_type>=12 ){
62129    return (serial_type-12)/2;
62130  }else{
62131    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
62132    return aSize[serial_type];
62133  }
62134}
62135
62136/*
62137** If we are on an architecture with mixed-endian floating
62138** points (ex: ARM7) then swap the lower 4 bytes with the
62139** upper 4 bytes.  Return the result.
62140**
62141** For most architectures, this is a no-op.
62142**
62143** (later):  It is reported to me that the mixed-endian problem
62144** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
62145** that early versions of GCC stored the two words of a 64-bit
62146** float in the wrong order.  And that error has been propagated
62147** ever since.  The blame is not necessarily with GCC, though.
62148** GCC might have just copying the problem from a prior compiler.
62149** I am also told that newer versions of GCC that follow a different
62150** ABI get the byte order right.
62151**
62152** Developers using SQLite on an ARM7 should compile and run their
62153** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
62154** enabled, some asserts below will ensure that the byte order of
62155** floating point values is correct.
62156**
62157** (2007-08-30)  Frank van Vugt has studied this problem closely
62158** and has send his findings to the SQLite developers.  Frank
62159** writes that some Linux kernels offer floating point hardware
62160** emulation that uses only 32-bit mantissas instead of a full
62161** 48-bits as required by the IEEE standard.  (This is the
62162** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
62163** byte swapping becomes very complicated.  To avoid problems,
62164** the necessary byte swapping is carried out using a 64-bit integer
62165** rather than a 64-bit float.  Frank assures us that the code here
62166** works for him.  We, the developers, have no way to independently
62167** verify this, but Frank seems to know what he is talking about
62168** so we trust him.
62169*/
62170#ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
62171static u64 floatSwap(u64 in){
62172  union {
62173    u64 r;
62174    u32 i[2];
62175  } u;
62176  u32 t;
62177
62178  u.r = in;
62179  t = u.i[0];
62180  u.i[0] = u.i[1];
62181  u.i[1] = t;
62182  return u.r;
62183}
62184# define swapMixedEndianFloat(X)  X = floatSwap(X)
62185#else
62186# define swapMixedEndianFloat(X)
62187#endif
62188
62189/*
62190** Write the serialized data blob for the value stored in pMem into
62191** buf. It is assumed that the caller has allocated sufficient space.
62192** Return the number of bytes written.
62193**
62194** nBuf is the amount of space left in buf[].  nBuf must always be
62195** large enough to hold the entire field.  Except, if the field is
62196** a blob with a zero-filled tail, then buf[] might be just the right
62197** size to hold everything except for the zero-filled tail.  If buf[]
62198** is only big enough to hold the non-zero prefix, then only write that
62199** prefix into buf[].  But if buf[] is large enough to hold both the
62200** prefix and the tail then write the prefix and set the tail to all
62201** zeros.
62202**
62203** Return the number of bytes actually written into buf[].  The number
62204** of bytes in the zero-filled tail is included in the return value only
62205** if those bytes were zeroed in buf[].
62206*/
62207SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
62208  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
62209  u32 len;
62210
62211  /* Integer and Real */
62212  if( serial_type<=7 && serial_type>0 ){
62213    u64 v;
62214    u32 i;
62215    if( serial_type==7 ){
62216      assert( sizeof(v)==sizeof(pMem->r) );
62217      memcpy(&v, &pMem->r, sizeof(v));
62218      swapMixedEndianFloat(v);
62219    }else{
62220      v = pMem->u.i;
62221    }
62222    len = i = sqlite3VdbeSerialTypeLen(serial_type);
62223    assert( len<=(u32)nBuf );
62224    while( i-- ){
62225      buf[i] = (u8)(v&0xFF);
62226      v >>= 8;
62227    }
62228    return len;
62229  }
62230
62231  /* String or blob */
62232  if( serial_type>=12 ){
62233    assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
62234             == (int)sqlite3VdbeSerialTypeLen(serial_type) );
62235    assert( pMem->n<=nBuf );
62236    len = pMem->n;
62237    memcpy(buf, pMem->z, len);
62238    if( pMem->flags & MEM_Zero ){
62239      len += pMem->u.nZero;
62240      assert( nBuf>=0 );
62241      if( len > (u32)nBuf ){
62242        len = (u32)nBuf;
62243      }
62244      memset(&buf[pMem->n], 0, len-pMem->n);
62245    }
62246    return len;
62247  }
62248
62249  /* NULL or constants 0 or 1 */
62250  return 0;
62251}
62252
62253/*
62254** Deserialize the data blob pointed to by buf as serial type serial_type
62255** and store the result in pMem.  Return the number of bytes read.
62256*/
62257SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
62258  const unsigned char *buf,     /* Buffer to deserialize from */
62259  u32 serial_type,              /* Serial type to deserialize */
62260  Mem *pMem                     /* Memory cell to write value into */
62261){
62262  switch( serial_type ){
62263    case 10:   /* Reserved for future use */
62264    case 11:   /* Reserved for future use */
62265    case 0: {  /* NULL */
62266      pMem->flags = MEM_Null;
62267      break;
62268    }
62269    case 1: { /* 1-byte signed integer */
62270      pMem->u.i = (signed char)buf[0];
62271      pMem->flags = MEM_Int;
62272      return 1;
62273    }
62274    case 2: { /* 2-byte signed integer */
62275      pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
62276      pMem->flags = MEM_Int;
62277      return 2;
62278    }
62279    case 3: { /* 3-byte signed integer */
62280      pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
62281      pMem->flags = MEM_Int;
62282      return 3;
62283    }
62284    case 4: { /* 4-byte signed integer */
62285      pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62286      pMem->flags = MEM_Int;
62287      return 4;
62288    }
62289    case 5: { /* 6-byte signed integer */
62290      u64 x = (((signed char)buf[0])<<8) | buf[1];
62291      u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
62292      x = (x<<32) | y;
62293      pMem->u.i = *(i64*)&x;
62294      pMem->flags = MEM_Int;
62295      return 6;
62296    }
62297    case 6:   /* 8-byte signed integer */
62298    case 7: { /* IEEE floating point */
62299      u64 x;
62300      u32 y;
62301#if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
62302      /* Verify that integers and floating point values use the same
62303      ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
62304      ** defined that 64-bit floating point values really are mixed
62305      ** endian.
62306      */
62307      static const u64 t1 = ((u64)0x3ff00000)<<32;
62308      static const double r1 = 1.0;
62309      u64 t2 = t1;
62310      swapMixedEndianFloat(t2);
62311      assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
62312#endif
62313
62314      x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62315      y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
62316      x = (x<<32) | y;
62317      if( serial_type==6 ){
62318        pMem->u.i = *(i64*)&x;
62319        pMem->flags = MEM_Int;
62320      }else{
62321        assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
62322        swapMixedEndianFloat(x);
62323        memcpy(&pMem->r, &x, sizeof(x));
62324        pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
62325      }
62326      return 8;
62327    }
62328    case 8:    /* Integer 0 */
62329    case 9: {  /* Integer 1 */
62330      pMem->u.i = serial_type-8;
62331      pMem->flags = MEM_Int;
62332      return 0;
62333    }
62334    default: {
62335      u32 len = (serial_type-12)/2;
62336      pMem->z = (char *)buf;
62337      pMem->n = len;
62338      pMem->xDel = 0;
62339      if( serial_type&0x01 ){
62340        pMem->flags = MEM_Str | MEM_Ephem;
62341      }else{
62342        pMem->flags = MEM_Blob | MEM_Ephem;
62343      }
62344      return len;
62345    }
62346  }
62347  return 0;
62348}
62349
62350/*
62351** This routine is used to allocate sufficient space for an UnpackedRecord
62352** structure large enough to be used with sqlite3VdbeRecordUnpack() if
62353** the first argument is a pointer to KeyInfo structure pKeyInfo.
62354**
62355** The space is either allocated using sqlite3DbMallocRaw() or from within
62356** the unaligned buffer passed via the second and third arguments (presumably
62357** stack space). If the former, then *ppFree is set to a pointer that should
62358** be eventually freed by the caller using sqlite3DbFree(). Or, if the
62359** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
62360** before returning.
62361**
62362** If an OOM error occurs, NULL is returned.
62363*/
62364SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
62365  KeyInfo *pKeyInfo,              /* Description of the record */
62366  char *pSpace,                   /* Unaligned space available */
62367  int szSpace,                    /* Size of pSpace[] in bytes */
62368  char **ppFree                   /* OUT: Caller should free this pointer */
62369){
62370  UnpackedRecord *p;              /* Unpacked record to return */
62371  int nOff;                       /* Increment pSpace by nOff to align it */
62372  int nByte;                      /* Number of bytes required for *p */
62373
62374  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
62375  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
62376  ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
62377  */
62378  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
62379  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
62380  if( nByte>szSpace+nOff ){
62381    p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
62382    *ppFree = (char *)p;
62383    if( !p ) return 0;
62384  }else{
62385    p = (UnpackedRecord*)&pSpace[nOff];
62386    *ppFree = 0;
62387  }
62388
62389  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
62390  p->pKeyInfo = pKeyInfo;
62391  p->nField = pKeyInfo->nField + 1;
62392  return p;
62393}
62394
62395/*
62396** Given the nKey-byte encoding of a record in pKey[], populate the
62397** UnpackedRecord structure indicated by the fourth argument with the
62398** contents of the decoded record.
62399*/
62400SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
62401  KeyInfo *pKeyInfo,     /* Information about the record format */
62402  int nKey,              /* Size of the binary record */
62403  const void *pKey,      /* The binary record */
62404  UnpackedRecord *p      /* Populate this structure before returning. */
62405){
62406  const unsigned char *aKey = (const unsigned char *)pKey;
62407  int d;
62408  u32 idx;                        /* Offset in aKey[] to read from */
62409  u16 u;                          /* Unsigned loop counter */
62410  u32 szHdr;
62411  Mem *pMem = p->aMem;
62412
62413  p->flags = 0;
62414  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62415  idx = getVarint32(aKey, szHdr);
62416  d = szHdr;
62417  u = 0;
62418  while( idx<szHdr && u<p->nField && d<=nKey ){
62419    u32 serial_type;
62420
62421    idx += getVarint32(&aKey[idx], serial_type);
62422    pMem->enc = pKeyInfo->enc;
62423    pMem->db = pKeyInfo->db;
62424    /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
62425    pMem->zMalloc = 0;
62426    d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
62427    pMem++;
62428    u++;
62429  }
62430  assert( u<=pKeyInfo->nField + 1 );
62431  p->nField = u;
62432}
62433
62434/*
62435** This function compares the two table rows or index records
62436** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
62437** or positive integer if key1 is less than, equal to or
62438** greater than key2.  The {nKey1, pKey1} key must be a blob
62439** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
62440** key must be a parsed key such as obtained from
62441** sqlite3VdbeParseRecord.
62442**
62443** Key1 and Key2 do not have to contain the same number of fields.
62444** The key with fewer fields is usually compares less than the
62445** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
62446** and the common prefixes are equal, then key1 is less than key2.
62447** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
62448** equal, then the keys are considered to be equal and
62449** the parts beyond the common prefix are ignored.
62450*/
62451SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
62452  int nKey1, const void *pKey1, /* Left key */
62453  UnpackedRecord *pPKey2        /* Right key */
62454){
62455  int d1;            /* Offset into aKey[] of next data element */
62456  u32 idx1;          /* Offset into aKey[] of next header element */
62457  u32 szHdr1;        /* Number of bytes in header */
62458  int i = 0;
62459  int nField;
62460  int rc = 0;
62461  const unsigned char *aKey1 = (const unsigned char *)pKey1;
62462  KeyInfo *pKeyInfo;
62463  Mem mem1;
62464
62465  pKeyInfo = pPKey2->pKeyInfo;
62466  mem1.enc = pKeyInfo->enc;
62467  mem1.db = pKeyInfo->db;
62468  /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
62469  VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
62470
62471  /* Compilers may complain that mem1.u.i is potentially uninitialized.
62472  ** We could initialize it, as shown here, to silence those complaints.
62473  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
62474  ** the unnecessary initialization has a measurable negative performance
62475  ** impact, since this routine is a very high runner.  And so, we choose
62476  ** to ignore the compiler warnings and leave this variable uninitialized.
62477  */
62478  /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
62479
62480  idx1 = getVarint32(aKey1, szHdr1);
62481  d1 = szHdr1;
62482  nField = pKeyInfo->nField;
62483  while( idx1<szHdr1 && i<pPKey2->nField ){
62484    u32 serial_type1;
62485
62486    /* Read the serial types for the next element in each key. */
62487    idx1 += getVarint32( aKey1+idx1, serial_type1 );
62488    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
62489
62490    /* Extract the values to be compared.
62491    */
62492    d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
62493
62494    /* Do the comparison
62495    */
62496    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
62497                           i<nField ? pKeyInfo->aColl[i] : 0);
62498    if( rc!=0 ){
62499      assert( mem1.zMalloc==0 );  /* See comment below */
62500
62501      /* Invert the result if we are using DESC sort order. */
62502      if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
62503        rc = -rc;
62504      }
62505
62506      /* If the PREFIX_SEARCH flag is set and all fields except the final
62507      ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
62508      ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
62509      ** This is used by the OP_IsUnique opcode.
62510      */
62511      if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
62512        assert( idx1==szHdr1 && rc );
62513        assert( mem1.flags & MEM_Int );
62514        pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
62515        pPKey2->rowid = mem1.u.i;
62516      }
62517
62518      return rc;
62519    }
62520    i++;
62521  }
62522
62523  /* No memory allocation is ever used on mem1.  Prove this using
62524  ** the following assert().  If the assert() fails, it indicates a
62525  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
62526  */
62527  assert( mem1.zMalloc==0 );
62528
62529  /* rc==0 here means that one of the keys ran out of fields and
62530  ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
62531  ** flag is set, then break the tie by treating key2 as larger.
62532  ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
62533  ** are considered to be equal.  Otherwise, the longer key is the
62534  ** larger.  As it happens, the pPKey2 will always be the longer
62535  ** if there is a difference.
62536  */
62537  assert( rc==0 );
62538  if( pPKey2->flags & UNPACKED_INCRKEY ){
62539    rc = -1;
62540  }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
62541    /* Leave rc==0 */
62542  }else if( idx1<szHdr1 ){
62543    rc = 1;
62544  }
62545  return rc;
62546}
62547
62548
62549/*
62550** pCur points at an index entry created using the OP_MakeRecord opcode.
62551** Read the rowid (the last field in the record) and store it in *rowid.
62552** Return SQLITE_OK if everything works, or an error code otherwise.
62553**
62554** pCur might be pointing to text obtained from a corrupt database file.
62555** So the content cannot be trusted.  Do appropriate checks on the content.
62556*/
62557SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
62558  i64 nCellKey = 0;
62559  int rc;
62560  u32 szHdr;        /* Size of the header */
62561  u32 typeRowid;    /* Serial type of the rowid */
62562  u32 lenRowid;     /* Size of the rowid */
62563  Mem m, v;
62564
62565  UNUSED_PARAMETER(db);
62566
62567  /* Get the size of the index entry.  Only indices entries of less
62568  ** than 2GiB are support - anything large must be database corruption.
62569  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
62570  ** this code can safely assume that nCellKey is 32-bits
62571  */
62572  assert( sqlite3BtreeCursorIsValid(pCur) );
62573  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
62574  assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
62575  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
62576
62577  /* Read in the complete content of the index entry */
62578  memset(&m, 0, sizeof(m));
62579  rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
62580  if( rc ){
62581    return rc;
62582  }
62583
62584  /* The index entry must begin with a header size */
62585  (void)getVarint32((u8*)m.z, szHdr);
62586  testcase( szHdr==3 );
62587  testcase( szHdr==m.n );
62588  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
62589    goto idx_rowid_corruption;
62590  }
62591
62592  /* The last field of the index should be an integer - the ROWID.
62593  ** Verify that the last entry really is an integer. */
62594  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
62595  testcase( typeRowid==1 );
62596  testcase( typeRowid==2 );
62597  testcase( typeRowid==3 );
62598  testcase( typeRowid==4 );
62599  testcase( typeRowid==5 );
62600  testcase( typeRowid==6 );
62601  testcase( typeRowid==8 );
62602  testcase( typeRowid==9 );
62603  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
62604    goto idx_rowid_corruption;
62605  }
62606  lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
62607  testcase( (u32)m.n==szHdr+lenRowid );
62608  if( unlikely((u32)m.n<szHdr+lenRowid) ){
62609    goto idx_rowid_corruption;
62610  }
62611
62612  /* Fetch the integer off the end of the index record */
62613  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
62614  *rowid = v.u.i;
62615  sqlite3VdbeMemRelease(&m);
62616  return SQLITE_OK;
62617
62618  /* Jump here if database corruption is detected after m has been
62619  ** allocated.  Free the m object and return SQLITE_CORRUPT. */
62620idx_rowid_corruption:
62621  testcase( m.zMalloc!=0 );
62622  sqlite3VdbeMemRelease(&m);
62623  return SQLITE_CORRUPT_BKPT;
62624}
62625
62626/*
62627** Compare the key of the index entry that cursor pC is pointing to against
62628** the key string in pUnpacked.  Write into *pRes a number
62629** that is negative, zero, or positive if pC is less than, equal to,
62630** or greater than pUnpacked.  Return SQLITE_OK on success.
62631**
62632** pUnpacked is either created without a rowid or is truncated so that it
62633** omits the rowid at the end.  The rowid at the end of the index entry
62634** is ignored as well.  Hence, this routine only compares the prefixes
62635** of the keys prior to the final rowid, not the entire key.
62636*/
62637SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
62638  VdbeCursor *pC,             /* The cursor to compare against */
62639  UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
62640  int *res                    /* Write the comparison result here */
62641){
62642  i64 nCellKey = 0;
62643  int rc;
62644  BtCursor *pCur = pC->pCursor;
62645  Mem m;
62646
62647  assert( sqlite3BtreeCursorIsValid(pCur) );
62648  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
62649  assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
62650  /* nCellKey will always be between 0 and 0xffffffff because of the say
62651  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
62652  if( nCellKey<=0 || nCellKey>0x7fffffff ){
62653    *res = 0;
62654    return SQLITE_CORRUPT_BKPT;
62655  }
62656  memset(&m, 0, sizeof(m));
62657  rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
62658  if( rc ){
62659    return rc;
62660  }
62661  assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
62662  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
62663  sqlite3VdbeMemRelease(&m);
62664  return SQLITE_OK;
62665}
62666
62667/*
62668** This routine sets the value to be returned by subsequent calls to
62669** sqlite3_changes() on the database handle 'db'.
62670*/
62671SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
62672  assert( sqlite3_mutex_held(db->mutex) );
62673  db->nChange = nChange;
62674  db->nTotalChange += nChange;
62675}
62676
62677/*
62678** Set a flag in the vdbe to update the change counter when it is finalised
62679** or reset.
62680*/
62681SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
62682  v->changeCntOn = 1;
62683}
62684
62685/*
62686** Mark every prepared statement associated with a database connection
62687** as expired.
62688**
62689** An expired statement means that recompilation of the statement is
62690** recommend.  Statements expire when things happen that make their
62691** programs obsolete.  Removing user-defined functions or collating
62692** sequences, or changing an authorization function are the types of
62693** things that make prepared statements obsolete.
62694*/
62695SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
62696  Vdbe *p;
62697  for(p = db->pVdbe; p; p=p->pNext){
62698    p->expired = 1;
62699  }
62700}
62701
62702/*
62703** Return the database associated with the Vdbe.
62704*/
62705SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
62706  return v->db;
62707}
62708
62709/*
62710** Return a pointer to an sqlite3_value structure containing the value bound
62711** parameter iVar of VM v. Except, if the value is an SQL NULL, return
62712** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
62713** constants) to the value before returning it.
62714**
62715** The returned value must be freed by the caller using sqlite3ValueFree().
62716*/
62717SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
62718  assert( iVar>0 );
62719  if( v ){
62720    Mem *pMem = &v->aVar[iVar-1];
62721    if( 0==(pMem->flags & MEM_Null) ){
62722      sqlite3_value *pRet = sqlite3ValueNew(v->db);
62723      if( pRet ){
62724        sqlite3VdbeMemCopy((Mem *)pRet, pMem);
62725        sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
62726        sqlite3VdbeMemStoreType((Mem *)pRet);
62727      }
62728      return pRet;
62729    }
62730  }
62731  return 0;
62732}
62733
62734/*
62735** Configure SQL variable iVar so that binding a new value to it signals
62736** to sqlite3_reoptimize() that re-preparing the statement may result
62737** in a better query plan.
62738*/
62739SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
62740  assert( iVar>0 );
62741  if( iVar>32 ){
62742    v->expmask = 0xffffffff;
62743  }else{
62744    v->expmask |= ((u32)1 << (iVar-1));
62745  }
62746}
62747
62748/************** End of vdbeaux.c *********************************************/
62749/************** Begin file vdbeapi.c *****************************************/
62750/*
62751** 2004 May 26
62752**
62753** The author disclaims copyright to this source code.  In place of
62754** a legal notice, here is a blessing:
62755**
62756**    May you do good and not evil.
62757**    May you find forgiveness for yourself and forgive others.
62758**    May you share freely, never taking more than you give.
62759**
62760*************************************************************************
62761**
62762** This file contains code use to implement APIs that are part of the
62763** VDBE.
62764*/
62765
62766#ifndef SQLITE_OMIT_DEPRECATED
62767/*
62768** Return TRUE (non-zero) of the statement supplied as an argument needs
62769** to be recompiled.  A statement needs to be recompiled whenever the
62770** execution environment changes in a way that would alter the program
62771** that sqlite3_prepare() generates.  For example, if new functions or
62772** collating sequences are registered or if an authorizer function is
62773** added or changed.
62774*/
62775SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
62776  Vdbe *p = (Vdbe*)pStmt;
62777  return p==0 || p->expired;
62778}
62779#endif
62780
62781/*
62782** Check on a Vdbe to make sure it has not been finalized.  Log
62783** an error and return true if it has been finalized (or is otherwise
62784** invalid).  Return false if it is ok.
62785*/
62786static int vdbeSafety(Vdbe *p){
62787  if( p->db==0 ){
62788    sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
62789    return 1;
62790  }else{
62791    return 0;
62792  }
62793}
62794static int vdbeSafetyNotNull(Vdbe *p){
62795  if( p==0 ){
62796    sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
62797    return 1;
62798  }else{
62799    return vdbeSafety(p);
62800  }
62801}
62802
62803/*
62804** The following routine destroys a virtual machine that is created by
62805** the sqlite3_compile() routine. The integer returned is an SQLITE_
62806** success/failure code that describes the result of executing the virtual
62807** machine.
62808**
62809** This routine sets the error code and string returned by
62810** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
62811*/
62812SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
62813  int rc;
62814  if( pStmt==0 ){
62815    /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
62816    ** pointer is a harmless no-op. */
62817    rc = SQLITE_OK;
62818  }else{
62819    Vdbe *v = (Vdbe*)pStmt;
62820    sqlite3 *db = v->db;
62821#if SQLITE_THREADSAFE
62822    sqlite3_mutex *mutex;
62823#endif
62824    if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
62825#if SQLITE_THREADSAFE
62826    mutex = v->db->mutex;
62827#endif
62828    sqlite3_mutex_enter(mutex);
62829    rc = sqlite3VdbeFinalize(v);
62830    rc = sqlite3ApiExit(db, rc);
62831    sqlite3_mutex_leave(mutex);
62832  }
62833  return rc;
62834}
62835
62836/*
62837** Terminate the current execution of an SQL statement and reset it
62838** back to its starting state so that it can be reused. A success code from
62839** the prior execution is returned.
62840**
62841** This routine sets the error code and string returned by
62842** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
62843*/
62844SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
62845  int rc;
62846  if( pStmt==0 ){
62847    rc = SQLITE_OK;
62848  }else{
62849    Vdbe *v = (Vdbe*)pStmt;
62850    sqlite3_mutex_enter(v->db->mutex);
62851    rc = sqlite3VdbeReset(v);
62852    sqlite3VdbeRewind(v);
62853    assert( (rc & (v->db->errMask))==rc );
62854    rc = sqlite3ApiExit(v->db, rc);
62855    sqlite3_mutex_leave(v->db->mutex);
62856  }
62857  return rc;
62858}
62859
62860/*
62861** Set all the parameters in the compiled SQL statement to NULL.
62862*/
62863SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
62864  int i;
62865  int rc = SQLITE_OK;
62866  Vdbe *p = (Vdbe*)pStmt;
62867#if SQLITE_THREADSAFE
62868  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
62869#endif
62870  sqlite3_mutex_enter(mutex);
62871  for(i=0; i<p->nVar; i++){
62872    sqlite3VdbeMemRelease(&p->aVar[i]);
62873    p->aVar[i].flags = MEM_Null;
62874  }
62875  if( p->isPrepareV2 && p->expmask ){
62876    p->expired = 1;
62877  }
62878  sqlite3_mutex_leave(mutex);
62879  return rc;
62880}
62881
62882
62883/**************************** sqlite3_value_  *******************************
62884** The following routines extract information from a Mem or sqlite3_value
62885** structure.
62886*/
62887SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
62888  Mem *p = (Mem*)pVal;
62889  if( p->flags & (MEM_Blob|MEM_Str) ){
62890    sqlite3VdbeMemExpandBlob(p);
62891    p->flags &= ~MEM_Str;
62892    p->flags |= MEM_Blob;
62893    return p->n ? p->z : 0;
62894  }else{
62895    return sqlite3_value_text(pVal);
62896  }
62897}
62898SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
62899  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
62900}
62901SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
62902  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
62903}
62904SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
62905  return sqlite3VdbeRealValue((Mem*)pVal);
62906}
62907SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
62908  return (int)sqlite3VdbeIntValue((Mem*)pVal);
62909}
62910SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
62911  return sqlite3VdbeIntValue((Mem*)pVal);
62912}
62913SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
62914  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
62915}
62916#ifndef SQLITE_OMIT_UTF16
62917SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
62918  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
62919}
62920SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
62921  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
62922}
62923SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
62924  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
62925}
62926#endif /* SQLITE_OMIT_UTF16 */
62927SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
62928  return pVal->type;
62929}
62930
62931/**************************** sqlite3_result_  *******************************
62932** The following routines are used by user-defined functions to specify
62933** the function result.
62934**
62935** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
62936** result as a string or blob but if the string or blob is too large, it
62937** then sets the error code to SQLITE_TOOBIG
62938*/
62939static void setResultStrOrError(
62940  sqlite3_context *pCtx,  /* Function context */
62941  const char *z,          /* String pointer */
62942  int n,                  /* Bytes in string, or negative */
62943  u8 enc,                 /* Encoding of z.  0 for BLOBs */
62944  void (*xDel)(void*)     /* Destructor function */
62945){
62946  if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
62947    sqlite3_result_error_toobig(pCtx);
62948  }
62949}
62950SQLITE_API void sqlite3_result_blob(
62951  sqlite3_context *pCtx,
62952  const void *z,
62953  int n,
62954  void (*xDel)(void *)
62955){
62956  assert( n>=0 );
62957  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62958  setResultStrOrError(pCtx, z, n, 0, xDel);
62959}
62960SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
62961  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62962  sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
62963}
62964SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
62965  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62966  pCtx->isError = SQLITE_ERROR;
62967  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
62968}
62969#ifndef SQLITE_OMIT_UTF16
62970SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
62971  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62972  pCtx->isError = SQLITE_ERROR;
62973  sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
62974}
62975#endif
62976SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
62977  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62978  sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
62979}
62980SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
62981  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62982  sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
62983}
62984SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
62985  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62986  sqlite3VdbeMemSetNull(&pCtx->s);
62987}
62988SQLITE_API void sqlite3_result_text(
62989  sqlite3_context *pCtx,
62990  const char *z,
62991  int n,
62992  void (*xDel)(void *)
62993){
62994  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
62995  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
62996}
62997#ifndef SQLITE_OMIT_UTF16
62998SQLITE_API void sqlite3_result_text16(
62999  sqlite3_context *pCtx,
63000  const void *z,
63001  int n,
63002  void (*xDel)(void *)
63003){
63004  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63005  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
63006}
63007SQLITE_API void sqlite3_result_text16be(
63008  sqlite3_context *pCtx,
63009  const void *z,
63010  int n,
63011  void (*xDel)(void *)
63012){
63013  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63014  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
63015}
63016SQLITE_API void sqlite3_result_text16le(
63017  sqlite3_context *pCtx,
63018  const void *z,
63019  int n,
63020  void (*xDel)(void *)
63021){
63022  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63023  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
63024}
63025#endif /* SQLITE_OMIT_UTF16 */
63026SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
63027  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63028  sqlite3VdbeMemCopy(&pCtx->s, pValue);
63029}
63030SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
63031  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63032  sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
63033}
63034SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
63035  pCtx->isError = errCode;
63036  if( pCtx->s.flags & MEM_Null ){
63037    sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
63038                         SQLITE_UTF8, SQLITE_STATIC);
63039  }
63040}
63041
63042/* Force an SQLITE_TOOBIG error. */
63043SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
63044  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63045  pCtx->isError = SQLITE_TOOBIG;
63046  sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
63047                       SQLITE_UTF8, SQLITE_STATIC);
63048}
63049
63050/* An SQLITE_NOMEM error. */
63051SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
63052  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63053  sqlite3VdbeMemSetNull(&pCtx->s);
63054  pCtx->isError = SQLITE_NOMEM;
63055  pCtx->s.db->mallocFailed = 1;
63056}
63057
63058/*
63059** This function is called after a transaction has been committed. It
63060** invokes callbacks registered with sqlite3_wal_hook() as required.
63061*/
63062static int doWalCallbacks(sqlite3 *db){
63063  int rc = SQLITE_OK;
63064#ifndef SQLITE_OMIT_WAL
63065  int i;
63066  for(i=0; i<db->nDb; i++){
63067    Btree *pBt = db->aDb[i].pBt;
63068    if( pBt ){
63069      int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
63070      if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
63071        rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
63072      }
63073    }
63074  }
63075#endif
63076  return rc;
63077}
63078
63079/*
63080** Execute the statement pStmt, either until a row of data is ready, the
63081** statement is completely executed or an error occurs.
63082**
63083** This routine implements the bulk of the logic behind the sqlite_step()
63084** API.  The only thing omitted is the automatic recompile if a
63085** schema change has occurred.  That detail is handled by the
63086** outer sqlite3_step() wrapper procedure.
63087*/
63088static int sqlite3Step(Vdbe *p){
63089  sqlite3 *db;
63090  int rc;
63091
63092  assert(p);
63093  if( p->magic!=VDBE_MAGIC_RUN ){
63094    /* We used to require that sqlite3_reset() be called before retrying
63095    ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
63096    ** with version 3.7.0, we changed this so that sqlite3_reset() would
63097    ** be called automatically instead of throwing the SQLITE_MISUSE error.
63098    ** This "automatic-reset" change is not technically an incompatibility,
63099    ** since any application that receives an SQLITE_MISUSE is broken by
63100    ** definition.
63101    **
63102    ** Nevertheless, some published applications that were originally written
63103    ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
63104    ** returns, and those were broken by the automatic-reset change.  As a
63105    ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
63106    ** legacy behavior of returning SQLITE_MISUSE for cases where the
63107    ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
63108    ** or SQLITE_BUSY error.
63109    */
63110#ifdef SQLITE_OMIT_AUTORESET
63111    if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
63112      sqlite3_reset((sqlite3_stmt*)p);
63113    }else{
63114      return SQLITE_MISUSE_BKPT;
63115    }
63116#else
63117    sqlite3_reset((sqlite3_stmt*)p);
63118#endif
63119  }
63120
63121  /* Check that malloc() has not failed. If it has, return early. */
63122  db = p->db;
63123  if( db->mallocFailed ){
63124    p->rc = SQLITE_NOMEM;
63125    return SQLITE_NOMEM;
63126  }
63127
63128  if( p->pc<=0 && p->expired ){
63129    p->rc = SQLITE_SCHEMA;
63130    rc = SQLITE_ERROR;
63131    goto end_of_step;
63132  }
63133  if( p->pc<0 ){
63134    /* If there are no other statements currently running, then
63135    ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
63136    ** from interrupting a statement that has not yet started.
63137    */
63138    if( db->activeVdbeCnt==0 ){
63139      db->u1.isInterrupted = 0;
63140    }
63141
63142    assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
63143
63144#ifndef SQLITE_OMIT_TRACE
63145    if( db->xProfile && !db->init.busy ){
63146      sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
63147    }
63148#endif
63149
63150    db->activeVdbeCnt++;
63151    if( p->readOnly==0 ) db->writeVdbeCnt++;
63152    p->pc = 0;
63153  }
63154#ifndef SQLITE_OMIT_EXPLAIN
63155  if( p->explain ){
63156    rc = sqlite3VdbeList(p);
63157  }else
63158#endif /* SQLITE_OMIT_EXPLAIN */
63159  {
63160    db->vdbeExecCnt++;
63161    rc = sqlite3VdbeExec(p);
63162    db->vdbeExecCnt--;
63163  }
63164
63165#ifndef SQLITE_OMIT_TRACE
63166  /* Invoke the profile callback if there is one
63167  */
63168  if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
63169    sqlite3_int64 iNow;
63170    sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
63171    db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
63172  }
63173#endif
63174
63175  if( rc==SQLITE_DONE ){
63176    assert( p->rc==SQLITE_OK );
63177    p->rc = doWalCallbacks(db);
63178    if( p->rc!=SQLITE_OK ){
63179      rc = SQLITE_ERROR;
63180    }
63181  }
63182
63183  db->errCode = rc;
63184  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
63185    p->rc = SQLITE_NOMEM;
63186  }
63187end_of_step:
63188  /* At this point local variable rc holds the value that should be
63189  ** returned if this statement was compiled using the legacy
63190  ** sqlite3_prepare() interface. According to the docs, this can only
63191  ** be one of the values in the first assert() below. Variable p->rc
63192  ** contains the value that would be returned if sqlite3_finalize()
63193  ** were called on statement p.
63194  */
63195  assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR
63196       || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
63197  );
63198  assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
63199  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
63200    /* If this statement was prepared using sqlite3_prepare_v2(), and an
63201    ** error has occured, then return the error code in p->rc to the
63202    ** caller. Set the error code in the database handle to the same value.
63203    */
63204    rc = sqlite3VdbeTransferError(p);
63205  }
63206  return (rc&db->errMask);
63207}
63208
63209/*
63210** The maximum number of times that a statement will try to reparse
63211** itself before giving up and returning SQLITE_SCHEMA.
63212*/
63213#ifndef SQLITE_MAX_SCHEMA_RETRY
63214# define SQLITE_MAX_SCHEMA_RETRY 5
63215#endif
63216
63217/*
63218** This is the top-level implementation of sqlite3_step().  Call
63219** sqlite3Step() to do most of the work.  If a schema error occurs,
63220** call sqlite3Reprepare() and try again.
63221*/
63222SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
63223  int rc = SQLITE_OK;      /* Result from sqlite3Step() */
63224  int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
63225  Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
63226  int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
63227  sqlite3 *db;             /* The database connection */
63228
63229  if( vdbeSafetyNotNull(v) ){
63230    return SQLITE_MISUSE_BKPT;
63231  }
63232  db = v->db;
63233  sqlite3_mutex_enter(db->mutex);
63234  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
63235         && cnt++ < SQLITE_MAX_SCHEMA_RETRY
63236         && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
63237    sqlite3_reset(pStmt);
63238    assert( v->expired==0 );
63239  }
63240  if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
63241    /* This case occurs after failing to recompile an sql statement.
63242    ** The error message from the SQL compiler has already been loaded
63243    ** into the database handle. This block copies the error message
63244    ** from the database handle into the statement and sets the statement
63245    ** program counter to 0 to ensure that when the statement is
63246    ** finalized or reset the parser error message is available via
63247    ** sqlite3_errmsg() and sqlite3_errcode().
63248    */
63249    const char *zErr = (const char *)sqlite3_value_text(db->pErr);
63250    sqlite3DbFree(db, v->zErrMsg);
63251    if( !db->mallocFailed ){
63252      v->zErrMsg = sqlite3DbStrDup(db, zErr);
63253      v->rc = rc2;
63254    } else {
63255      v->zErrMsg = 0;
63256      v->rc = rc = SQLITE_NOMEM;
63257    }
63258  }
63259  rc = sqlite3ApiExit(db, rc);
63260  sqlite3_mutex_leave(db->mutex);
63261  return rc;
63262}
63263
63264/*
63265** Extract the user data from a sqlite3_context structure and return a
63266** pointer to it.
63267*/
63268SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
63269  assert( p && p->pFunc );
63270  return p->pFunc->pUserData;
63271}
63272
63273/*
63274** Extract the user data from a sqlite3_context structure and return a
63275** pointer to it.
63276**
63277** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
63278** returns a copy of the pointer to the database connection (the 1st
63279** parameter) of the sqlite3_create_function() and
63280** sqlite3_create_function16() routines that originally registered the
63281** application defined function.
63282*/
63283SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
63284  assert( p && p->pFunc );
63285  return p->s.db;
63286}
63287
63288/*
63289** The following is the implementation of an SQL function that always
63290** fails with an error message stating that the function is used in the
63291** wrong context.  The sqlite3_overload_function() API might construct
63292** SQL function that use this routine so that the functions will exist
63293** for name resolution but are actually overloaded by the xFindFunction
63294** method of virtual tables.
63295*/
63296SQLITE_PRIVATE void sqlite3InvalidFunction(
63297  sqlite3_context *context,  /* The function calling context */
63298  int NotUsed,               /* Number of arguments to the function */
63299  sqlite3_value **NotUsed2   /* Value of each argument */
63300){
63301  const char *zName = context->pFunc->zName;
63302  char *zErr;
63303  UNUSED_PARAMETER2(NotUsed, NotUsed2);
63304  zErr = sqlite3_mprintf(
63305      "unable to use function %s in the requested context", zName);
63306  sqlite3_result_error(context, zErr, -1);
63307  sqlite3_free(zErr);
63308}
63309
63310/*
63311** Allocate or return the aggregate context for a user function.  A new
63312** context is allocated on the first call.  Subsequent calls return the
63313** same context that was returned on prior calls.
63314*/
63315SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
63316  Mem *pMem;
63317  assert( p && p->pFunc && p->pFunc->xStep );
63318  assert( sqlite3_mutex_held(p->s.db->mutex) );
63319  pMem = p->pMem;
63320  testcase( nByte<0 );
63321  if( (pMem->flags & MEM_Agg)==0 ){
63322    if( nByte<=0 ){
63323      sqlite3VdbeMemReleaseExternal(pMem);
63324      pMem->flags = MEM_Null;
63325      pMem->z = 0;
63326    }else{
63327      sqlite3VdbeMemGrow(pMem, nByte, 0);
63328      pMem->flags = MEM_Agg;
63329      pMem->u.pDef = p->pFunc;
63330      if( pMem->z ){
63331        memset(pMem->z, 0, nByte);
63332      }
63333    }
63334  }
63335  return (void*)pMem->z;
63336}
63337
63338/*
63339** Return the auxilary data pointer, if any, for the iArg'th argument to
63340** the user-function defined by pCtx.
63341*/
63342SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
63343  VdbeFunc *pVdbeFunc;
63344
63345  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63346  pVdbeFunc = pCtx->pVdbeFunc;
63347  if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
63348    return 0;
63349  }
63350  return pVdbeFunc->apAux[iArg].pAux;
63351}
63352
63353/*
63354** Set the auxilary data pointer and delete function, for the iArg'th
63355** argument to the user-function defined by pCtx. Any previous value is
63356** deleted by calling the delete function specified when it was set.
63357*/
63358SQLITE_API void sqlite3_set_auxdata(
63359  sqlite3_context *pCtx,
63360  int iArg,
63361  void *pAux,
63362  void (*xDelete)(void*)
63363){
63364  struct AuxData *pAuxData;
63365  VdbeFunc *pVdbeFunc;
63366  if( iArg<0 ) goto failed;
63367
63368  assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63369  pVdbeFunc = pCtx->pVdbeFunc;
63370  if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
63371    int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
63372    int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
63373    pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
63374    if( !pVdbeFunc ){
63375      goto failed;
63376    }
63377    pCtx->pVdbeFunc = pVdbeFunc;
63378    memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
63379    pVdbeFunc->nAux = iArg+1;
63380    pVdbeFunc->pFunc = pCtx->pFunc;
63381  }
63382
63383  pAuxData = &pVdbeFunc->apAux[iArg];
63384  if( pAuxData->pAux && pAuxData->xDelete ){
63385    pAuxData->xDelete(pAuxData->pAux);
63386  }
63387  pAuxData->pAux = pAux;
63388  pAuxData->xDelete = xDelete;
63389  return;
63390
63391failed:
63392  if( xDelete ){
63393    xDelete(pAux);
63394  }
63395}
63396
63397#ifndef SQLITE_OMIT_DEPRECATED
63398/*
63399** Return the number of times the Step function of a aggregate has been
63400** called.
63401**
63402** This function is deprecated.  Do not use it for new code.  It is
63403** provide only to avoid breaking legacy code.  New aggregate function
63404** implementations should keep their own counts within their aggregate
63405** context.
63406*/
63407SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
63408  assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
63409  return p->pMem->n;
63410}
63411#endif
63412
63413/*
63414** Return the number of columns in the result set for the statement pStmt.
63415*/
63416SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
63417  Vdbe *pVm = (Vdbe *)pStmt;
63418  return pVm ? pVm->nResColumn : 0;
63419}
63420
63421/*
63422** Return the number of values available from the current row of the
63423** currently executing statement pStmt.
63424*/
63425SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
63426  Vdbe *pVm = (Vdbe *)pStmt;
63427  if( pVm==0 || pVm->pResultSet==0 ) return 0;
63428  return pVm->nResColumn;
63429}
63430
63431
63432/*
63433** Check to see if column iCol of the given statement is valid.  If
63434** it is, return a pointer to the Mem for the value of that column.
63435** If iCol is not valid, return a pointer to a Mem which has a value
63436** of NULL.
63437*/
63438static Mem *columnMem(sqlite3_stmt *pStmt, int i){
63439  Vdbe *pVm;
63440  Mem *pOut;
63441
63442  pVm = (Vdbe *)pStmt;
63443  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
63444    sqlite3_mutex_enter(pVm->db->mutex);
63445    pOut = &pVm->pResultSet[i];
63446  }else{
63447    /* If the value passed as the second argument is out of range, return
63448    ** a pointer to the following static Mem object which contains the
63449    ** value SQL NULL. Even though the Mem structure contains an element
63450    ** of type i64, on certain architectures (x86) with certain compiler
63451    ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
63452    ** instead of an 8-byte one. This all works fine, except that when
63453    ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
63454    ** that a Mem structure is located on an 8-byte boundary. To prevent
63455    ** these assert()s from failing, when building with SQLITE_DEBUG defined
63456    ** using gcc, we force nullMem to be 8-byte aligned using the magical
63457    ** __attribute__((aligned(8))) macro.  */
63458    static const Mem nullMem
63459#if defined(SQLITE_DEBUG) && defined(__GNUC__)
63460      __attribute__((aligned(8)))
63461#endif
63462      = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
63463#ifdef SQLITE_DEBUG
63464         0, 0,  /* pScopyFrom, pFiller */
63465#endif
63466         0, 0 };
63467
63468    if( pVm && ALWAYS(pVm->db) ){
63469      sqlite3_mutex_enter(pVm->db->mutex);
63470      sqlite3Error(pVm->db, SQLITE_RANGE, 0);
63471    }
63472    pOut = (Mem*)&nullMem;
63473  }
63474  return pOut;
63475}
63476
63477/*
63478** This function is called after invoking an sqlite3_value_XXX function on a
63479** column value (i.e. a value returned by evaluating an SQL expression in the
63480** select list of a SELECT statement) that may cause a malloc() failure. If
63481** malloc() has failed, the threads mallocFailed flag is cleared and the result
63482** code of statement pStmt set to SQLITE_NOMEM.
63483**
63484** Specifically, this is called from within:
63485**
63486**     sqlite3_column_int()
63487**     sqlite3_column_int64()
63488**     sqlite3_column_text()
63489**     sqlite3_column_text16()
63490**     sqlite3_column_real()
63491**     sqlite3_column_bytes()
63492**     sqlite3_column_bytes16()
63493**     sqiite3_column_blob()
63494*/
63495static void columnMallocFailure(sqlite3_stmt *pStmt)
63496{
63497  /* If malloc() failed during an encoding conversion within an
63498  ** sqlite3_column_XXX API, then set the return code of the statement to
63499  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
63500  ** and _finalize() will return NOMEM.
63501  */
63502  Vdbe *p = (Vdbe *)pStmt;
63503  if( p ){
63504    p->rc = sqlite3ApiExit(p->db, p->rc);
63505    sqlite3_mutex_leave(p->db->mutex);
63506  }
63507}
63508
63509/**************************** sqlite3_column_  *******************************
63510** The following routines are used to access elements of the current row
63511** in the result set.
63512*/
63513SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
63514  const void *val;
63515  val = sqlite3_value_blob( columnMem(pStmt,i) );
63516  /* Even though there is no encoding conversion, value_blob() might
63517  ** need to call malloc() to expand the result of a zeroblob()
63518  ** expression.
63519  */
63520  columnMallocFailure(pStmt);
63521  return val;
63522}
63523SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
63524  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
63525  columnMallocFailure(pStmt);
63526  return val;
63527}
63528SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
63529  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
63530  columnMallocFailure(pStmt);
63531  return val;
63532}
63533SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
63534  double val = sqlite3_value_double( columnMem(pStmt,i) );
63535  columnMallocFailure(pStmt);
63536  return val;
63537}
63538SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
63539  int val = sqlite3_value_int( columnMem(pStmt,i) );
63540  columnMallocFailure(pStmt);
63541  return val;
63542}
63543SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
63544  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
63545  columnMallocFailure(pStmt);
63546  return val;
63547}
63548SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
63549  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
63550  columnMallocFailure(pStmt);
63551  return val;
63552}
63553SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
63554  Mem *pOut = columnMem(pStmt, i);
63555  if( pOut->flags&MEM_Static ){
63556    pOut->flags &= ~MEM_Static;
63557    pOut->flags |= MEM_Ephem;
63558  }
63559  columnMallocFailure(pStmt);
63560  return (sqlite3_value *)pOut;
63561}
63562#ifndef SQLITE_OMIT_UTF16
63563SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
63564  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
63565  columnMallocFailure(pStmt);
63566  return val;
63567}
63568#endif /* SQLITE_OMIT_UTF16 */
63569SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
63570  int iType = sqlite3_value_type( columnMem(pStmt,i) );
63571  columnMallocFailure(pStmt);
63572  return iType;
63573}
63574
63575/* The following function is experimental and subject to change or
63576** removal */
63577/*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
63578**  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
63579**}
63580*/
63581
63582/*
63583** Convert the N-th element of pStmt->pColName[] into a string using
63584** xFunc() then return that string.  If N is out of range, return 0.
63585**
63586** There are up to 5 names for each column.  useType determines which
63587** name is returned.  Here are the names:
63588**
63589**    0      The column name as it should be displayed for output
63590**    1      The datatype name for the column
63591**    2      The name of the database that the column derives from
63592**    3      The name of the table that the column derives from
63593**    4      The name of the table column that the result column derives from
63594**
63595** If the result is not a simple column reference (if it is an expression
63596** or a constant) then useTypes 2, 3, and 4 return NULL.
63597*/
63598static const void *columnName(
63599  sqlite3_stmt *pStmt,
63600  int N,
63601  const void *(*xFunc)(Mem*),
63602  int useType
63603){
63604  const void *ret = 0;
63605  Vdbe *p = (Vdbe *)pStmt;
63606  int n;
63607  sqlite3 *db = p->db;
63608
63609  assert( db!=0 );
63610  n = sqlite3_column_count(pStmt);
63611  if( N<n && N>=0 ){
63612    N += useType*n;
63613    sqlite3_mutex_enter(db->mutex);
63614    assert( db->mallocFailed==0 );
63615    ret = xFunc(&p->aColName[N]);
63616     /* A malloc may have failed inside of the xFunc() call. If this
63617    ** is the case, clear the mallocFailed flag and return NULL.
63618    */
63619    if( db->mallocFailed ){
63620      db->mallocFailed = 0;
63621      ret = 0;
63622    }
63623    sqlite3_mutex_leave(db->mutex);
63624  }
63625  return ret;
63626}
63627
63628/*
63629** Return the name of the Nth column of the result set returned by SQL
63630** statement pStmt.
63631*/
63632SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
63633  return columnName(
63634      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
63635}
63636#ifndef SQLITE_OMIT_UTF16
63637SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
63638  return columnName(
63639      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
63640}
63641#endif
63642
63643/*
63644** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
63645** not define OMIT_DECLTYPE.
63646*/
63647#if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
63648# error "Must not define both SQLITE_OMIT_DECLTYPE \
63649         and SQLITE_ENABLE_COLUMN_METADATA"
63650#endif
63651
63652#ifndef SQLITE_OMIT_DECLTYPE
63653/*
63654** Return the column declaration type (if applicable) of the 'i'th column
63655** of the result set of SQL statement pStmt.
63656*/
63657SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
63658  return columnName(
63659      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
63660}
63661#ifndef SQLITE_OMIT_UTF16
63662SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
63663  return columnName(
63664      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
63665}
63666#endif /* SQLITE_OMIT_UTF16 */
63667#endif /* SQLITE_OMIT_DECLTYPE */
63668
63669#ifdef SQLITE_ENABLE_COLUMN_METADATA
63670/*
63671** Return the name of the database from which a result column derives.
63672** NULL is returned if the result column is an expression or constant or
63673** anything else which is not an unabiguous reference to a database column.
63674*/
63675SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
63676  return columnName(
63677      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
63678}
63679#ifndef SQLITE_OMIT_UTF16
63680SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
63681  return columnName(
63682      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
63683}
63684#endif /* SQLITE_OMIT_UTF16 */
63685
63686/*
63687** Return the name of the table from which a result column derives.
63688** NULL is returned if the result column is an expression or constant or
63689** anything else which is not an unabiguous reference to a database column.
63690*/
63691SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
63692  return columnName(
63693      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
63694}
63695#ifndef SQLITE_OMIT_UTF16
63696SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
63697  return columnName(
63698      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
63699}
63700#endif /* SQLITE_OMIT_UTF16 */
63701
63702/*
63703** Return the name of the table column from which a result column derives.
63704** NULL is returned if the result column is an expression or constant or
63705** anything else which is not an unabiguous reference to a database column.
63706*/
63707SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
63708  return columnName(
63709      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
63710}
63711#ifndef SQLITE_OMIT_UTF16
63712SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
63713  return columnName(
63714      pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
63715}
63716#endif /* SQLITE_OMIT_UTF16 */
63717#endif /* SQLITE_ENABLE_COLUMN_METADATA */
63718
63719
63720/******************************* sqlite3_bind_  ***************************
63721**
63722** Routines used to attach values to wildcards in a compiled SQL statement.
63723*/
63724/*
63725** Unbind the value bound to variable i in virtual machine p. This is the
63726** the same as binding a NULL value to the column. If the "i" parameter is
63727** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
63728**
63729** A successful evaluation of this routine acquires the mutex on p.
63730** the mutex is released if any kind of error occurs.
63731**
63732** The error code stored in database p->db is overwritten with the return
63733** value in any case.
63734*/
63735static int vdbeUnbind(Vdbe *p, int i){
63736  Mem *pVar;
63737  if( vdbeSafetyNotNull(p) ){
63738    return SQLITE_MISUSE_BKPT;
63739  }
63740  sqlite3_mutex_enter(p->db->mutex);
63741  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
63742    sqlite3Error(p->db, SQLITE_MISUSE, 0);
63743    sqlite3_mutex_leave(p->db->mutex);
63744    sqlite3_log(SQLITE_MISUSE,
63745        "bind on a busy prepared statement: [%s]", p->zSql);
63746    return SQLITE_MISUSE_BKPT;
63747  }
63748  if( i<1 || i>p->nVar ){
63749    sqlite3Error(p->db, SQLITE_RANGE, 0);
63750    sqlite3_mutex_leave(p->db->mutex);
63751    return SQLITE_RANGE;
63752  }
63753  i--;
63754  pVar = &p->aVar[i];
63755  sqlite3VdbeMemRelease(pVar);
63756  pVar->flags = MEM_Null;
63757  sqlite3Error(p->db, SQLITE_OK, 0);
63758
63759  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
63760  ** binding a new value to this variable invalidates the current query plan.
63761  **
63762  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
63763  ** parameter in the WHERE clause might influence the choice of query plan
63764  ** for a statement, then the statement will be automatically recompiled,
63765  ** as if there had been a schema change, on the first sqlite3_step() call
63766  ** following any change to the bindings of that parameter.
63767  */
63768  if( p->isPrepareV2 &&
63769     ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
63770  ){
63771    p->expired = 1;
63772  }
63773  return SQLITE_OK;
63774}
63775
63776/*
63777** Bind a text or BLOB value.
63778*/
63779static int bindText(
63780  sqlite3_stmt *pStmt,   /* The statement to bind against */
63781  int i,                 /* Index of the parameter to bind */
63782  const void *zData,     /* Pointer to the data to be bound */
63783  int nData,             /* Number of bytes of data to be bound */
63784  void (*xDel)(void*),   /* Destructor for the data */
63785  u8 encoding            /* Encoding for the data */
63786){
63787  Vdbe *p = (Vdbe *)pStmt;
63788  Mem *pVar;
63789  int rc;
63790
63791  rc = vdbeUnbind(p, i);
63792  if( rc==SQLITE_OK ){
63793    if( zData!=0 ){
63794      pVar = &p->aVar[i-1];
63795      rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
63796      if( rc==SQLITE_OK && encoding!=0 ){
63797        rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
63798      }
63799      sqlite3Error(p->db, rc, 0);
63800      rc = sqlite3ApiExit(p->db, rc);
63801    }
63802    sqlite3_mutex_leave(p->db->mutex);
63803  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
63804    xDel((void*)zData);
63805  }
63806  return rc;
63807}
63808
63809
63810/*
63811** Bind a blob value to an SQL statement variable.
63812*/
63813SQLITE_API int sqlite3_bind_blob(
63814  sqlite3_stmt *pStmt,
63815  int i,
63816  const void *zData,
63817  int nData,
63818  void (*xDel)(void*)
63819){
63820  return bindText(pStmt, i, zData, nData, xDel, 0);
63821}
63822SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
63823  int rc;
63824  Vdbe *p = (Vdbe *)pStmt;
63825  rc = vdbeUnbind(p, i);
63826  if( rc==SQLITE_OK ){
63827    sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
63828    sqlite3_mutex_leave(p->db->mutex);
63829  }
63830  return rc;
63831}
63832SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
63833  return sqlite3_bind_int64(p, i, (i64)iValue);
63834}
63835SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
63836  int rc;
63837  Vdbe *p = (Vdbe *)pStmt;
63838  rc = vdbeUnbind(p, i);
63839  if( rc==SQLITE_OK ){
63840    sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
63841    sqlite3_mutex_leave(p->db->mutex);
63842  }
63843  return rc;
63844}
63845SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
63846  int rc;
63847  Vdbe *p = (Vdbe*)pStmt;
63848  rc = vdbeUnbind(p, i);
63849  if( rc==SQLITE_OK ){
63850    sqlite3_mutex_leave(p->db->mutex);
63851  }
63852  return rc;
63853}
63854SQLITE_API int sqlite3_bind_text(
63855  sqlite3_stmt *pStmt,
63856  int i,
63857  const char *zData,
63858  int nData,
63859  void (*xDel)(void*)
63860){
63861  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
63862}
63863#ifndef SQLITE_OMIT_UTF16
63864SQLITE_API int sqlite3_bind_text16(
63865  sqlite3_stmt *pStmt,
63866  int i,
63867  const void *zData,
63868  int nData,
63869  void (*xDel)(void*)
63870){
63871  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
63872}
63873#endif /* SQLITE_OMIT_UTF16 */
63874SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
63875  int rc;
63876  switch( pValue->type ){
63877    case SQLITE_INTEGER: {
63878      rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
63879      break;
63880    }
63881    case SQLITE_FLOAT: {
63882      rc = sqlite3_bind_double(pStmt, i, pValue->r);
63883      break;
63884    }
63885    case SQLITE_BLOB: {
63886      if( pValue->flags & MEM_Zero ){
63887        rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
63888      }else{
63889        rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
63890      }
63891      break;
63892    }
63893    case SQLITE_TEXT: {
63894      rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
63895                              pValue->enc);
63896      break;
63897    }
63898    default: {
63899      rc = sqlite3_bind_null(pStmt, i);
63900      break;
63901    }
63902  }
63903  return rc;
63904}
63905SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
63906  int rc;
63907  Vdbe *p = (Vdbe *)pStmt;
63908  rc = vdbeUnbind(p, i);
63909  if( rc==SQLITE_OK ){
63910    sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
63911    sqlite3_mutex_leave(p->db->mutex);
63912  }
63913  return rc;
63914}
63915
63916/*
63917** Return the number of wildcards that can be potentially bound to.
63918** This routine is added to support DBD::SQLite.
63919*/
63920SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
63921  Vdbe *p = (Vdbe*)pStmt;
63922  return p ? p->nVar : 0;
63923}
63924
63925/*
63926** Return the name of a wildcard parameter.  Return NULL if the index
63927** is out of range or if the wildcard is unnamed.
63928**
63929** The result is always UTF-8.
63930*/
63931SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
63932  Vdbe *p = (Vdbe*)pStmt;
63933  if( p==0 || i<1 || i>p->nzVar ){
63934    return 0;
63935  }
63936  return p->azVar[i-1];
63937}
63938
63939/*
63940** Given a wildcard parameter name, return the index of the variable
63941** with that name.  If there is no variable with the given name,
63942** return 0.
63943*/
63944SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
63945  int i;
63946  if( p==0 ){
63947    return 0;
63948  }
63949  if( zName ){
63950    for(i=0; i<p->nzVar; i++){
63951      const char *z = p->azVar[i];
63952      if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
63953        return i+1;
63954      }
63955    }
63956  }
63957  return 0;
63958}
63959SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
63960  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
63961}
63962
63963/*
63964** Transfer all bindings from the first statement over to the second.
63965*/
63966SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
63967  Vdbe *pFrom = (Vdbe*)pFromStmt;
63968  Vdbe *pTo = (Vdbe*)pToStmt;
63969  int i;
63970  assert( pTo->db==pFrom->db );
63971  assert( pTo->nVar==pFrom->nVar );
63972  sqlite3_mutex_enter(pTo->db->mutex);
63973  for(i=0; i<pFrom->nVar; i++){
63974    sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
63975  }
63976  sqlite3_mutex_leave(pTo->db->mutex);
63977  return SQLITE_OK;
63978}
63979
63980#ifndef SQLITE_OMIT_DEPRECATED
63981/*
63982** Deprecated external interface.  Internal/core SQLite code
63983** should call sqlite3TransferBindings.
63984**
63985** Is is misuse to call this routine with statements from different
63986** database connections.  But as this is a deprecated interface, we
63987** will not bother to check for that condition.
63988**
63989** If the two statements contain a different number of bindings, then
63990** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
63991** SQLITE_OK is returned.
63992*/
63993SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
63994  Vdbe *pFrom = (Vdbe*)pFromStmt;
63995  Vdbe *pTo = (Vdbe*)pToStmt;
63996  if( pFrom->nVar!=pTo->nVar ){
63997    return SQLITE_ERROR;
63998  }
63999  if( pTo->isPrepareV2 && pTo->expmask ){
64000    pTo->expired = 1;
64001  }
64002  if( pFrom->isPrepareV2 && pFrom->expmask ){
64003    pFrom->expired = 1;
64004  }
64005  return sqlite3TransferBindings(pFromStmt, pToStmt);
64006}
64007#endif
64008
64009/*
64010** Return the sqlite3* database handle to which the prepared statement given
64011** in the argument belongs.  This is the same database handle that was
64012** the first argument to the sqlite3_prepare() that was used to create
64013** the statement in the first place.
64014*/
64015SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
64016  return pStmt ? ((Vdbe*)pStmt)->db : 0;
64017}
64018
64019/*
64020** Return true if the prepared statement is guaranteed to not modify the
64021** database.
64022*/
64023SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
64024  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
64025}
64026
64027/*
64028** Return true if the prepared statement is in need of being reset.
64029*/
64030SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
64031  Vdbe *v = (Vdbe*)pStmt;
64032  return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
64033}
64034
64035/*
64036** Return a pointer to the next prepared statement after pStmt associated
64037** with database connection pDb.  If pStmt is NULL, return the first
64038** prepared statement for the database connection.  Return NULL if there
64039** are no more.
64040*/
64041SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
64042  sqlite3_stmt *pNext;
64043  sqlite3_mutex_enter(pDb->mutex);
64044  if( pStmt==0 ){
64045    pNext = (sqlite3_stmt*)pDb->pVdbe;
64046  }else{
64047    pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
64048  }
64049  sqlite3_mutex_leave(pDb->mutex);
64050  return pNext;
64051}
64052
64053/*
64054** Return the value of a status counter for a prepared statement
64055*/
64056SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
64057  Vdbe *pVdbe = (Vdbe*)pStmt;
64058  int v = pVdbe->aCounter[op-1];
64059  if( resetFlag ) pVdbe->aCounter[op-1] = 0;
64060  return v;
64061}
64062
64063/************** End of vdbeapi.c *********************************************/
64064/************** Begin file vdbetrace.c ***************************************/
64065/*
64066** 2009 November 25
64067**
64068** The author disclaims copyright to this source code.  In place of
64069** a legal notice, here is a blessing:
64070**
64071**    May you do good and not evil.
64072**    May you find forgiveness for yourself and forgive others.
64073**    May you share freely, never taking more than you give.
64074**
64075*************************************************************************
64076**
64077** This file contains code used to insert the values of host parameters
64078** (aka "wildcards") into the SQL text output by sqlite3_trace().
64079**
64080** The Vdbe parse-tree explainer is also found here.
64081*/
64082
64083#ifndef SQLITE_OMIT_TRACE
64084
64085/*
64086** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
64087** bytes in this text up to but excluding the first character in
64088** a host parameter.  If the text contains no host parameters, return
64089** the total number of bytes in the text.
64090*/
64091static int findNextHostParameter(const char *zSql, int *pnToken){
64092  int tokenType;
64093  int nTotal = 0;
64094  int n;
64095
64096  *pnToken = 0;
64097  while( zSql[0] ){
64098    n = sqlite3GetToken((u8*)zSql, &tokenType);
64099    assert( n>0 && tokenType!=TK_ILLEGAL );
64100    if( tokenType==TK_VARIABLE ){
64101      *pnToken = n;
64102      break;
64103    }
64104    nTotal += n;
64105    zSql += n;
64106  }
64107  return nTotal;
64108}
64109
64110/*
64111** This function returns a pointer to a nul-terminated string in memory
64112** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
64113** string contains a copy of zRawSql but with host parameters expanded to
64114** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
64115** then the returned string holds a copy of zRawSql with "-- " prepended
64116** to each line of text.
64117**
64118** The calling function is responsible for making sure the memory returned
64119** is eventually freed.
64120**
64121** ALGORITHM:  Scan the input string looking for host parameters in any of
64122** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
64123** string literals, quoted identifier names, and comments.  For text forms,
64124** the host parameter index is found by scanning the perpared
64125** statement for the corresponding OP_Variable opcode.  Once the host
64126** parameter index is known, locate the value in p->aVar[].  Then render
64127** the value as a literal in place of the host parameter name.
64128*/
64129SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
64130  Vdbe *p,                 /* The prepared statement being evaluated */
64131  const char *zRawSql      /* Raw text of the SQL statement */
64132){
64133  sqlite3 *db;             /* The database connection */
64134  int idx = 0;             /* Index of a host parameter */
64135  int nextIndex = 1;       /* Index of next ? host parameter */
64136  int n;                   /* Length of a token prefix */
64137  int nToken;              /* Length of the parameter token */
64138  int i;                   /* Loop counter */
64139  Mem *pVar;               /* Value of a host parameter */
64140  StrAccum out;            /* Accumulate the output here */
64141  char zBase[100];         /* Initial working space */
64142
64143  db = p->db;
64144  sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
64145                      db->aLimit[SQLITE_LIMIT_LENGTH]);
64146  out.db = db;
64147  if( db->vdbeExecCnt>1 ){
64148    while( *zRawSql ){
64149      const char *zStart = zRawSql;
64150      while( *(zRawSql++)!='\n' && *zRawSql );
64151      sqlite3StrAccumAppend(&out, "-- ", 3);
64152      sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
64153    }
64154  }else{
64155    while( zRawSql[0] ){
64156      n = findNextHostParameter(zRawSql, &nToken);
64157      assert( n>0 );
64158      sqlite3StrAccumAppend(&out, zRawSql, n);
64159      zRawSql += n;
64160      assert( zRawSql[0] || nToken==0 );
64161      if( nToken==0 ) break;
64162      if( zRawSql[0]=='?' ){
64163        if( nToken>1 ){
64164          assert( sqlite3Isdigit(zRawSql[1]) );
64165          sqlite3GetInt32(&zRawSql[1], &idx);
64166        }else{
64167          idx = nextIndex;
64168        }
64169      }else{
64170        assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
64171        testcase( zRawSql[0]==':' );
64172        testcase( zRawSql[0]=='$' );
64173        testcase( zRawSql[0]=='@' );
64174        idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
64175        assert( idx>0 );
64176      }
64177      zRawSql += nToken;
64178      nextIndex = idx + 1;
64179      assert( idx>0 && idx<=p->nVar );
64180      pVar = &p->aVar[idx-1];
64181      if( pVar->flags & MEM_Null ){
64182        sqlite3StrAccumAppend(&out, "NULL", 4);
64183      }else if( pVar->flags & MEM_Int ){
64184        sqlite3XPrintf(&out, "%lld", pVar->u.i);
64185      }else if( pVar->flags & MEM_Real ){
64186        sqlite3XPrintf(&out, "%!.15g", pVar->r);
64187      }else if( pVar->flags & MEM_Str ){
64188#ifndef SQLITE_OMIT_UTF16
64189        u8 enc = ENC(db);
64190        if( enc!=SQLITE_UTF8 ){
64191          Mem utf8;
64192          memset(&utf8, 0, sizeof(utf8));
64193          utf8.db = db;
64194          sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
64195          sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
64196          sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
64197          sqlite3VdbeMemRelease(&utf8);
64198        }else
64199#endif
64200        {
64201          sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
64202        }
64203      }else if( pVar->flags & MEM_Zero ){
64204        sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
64205      }else{
64206        assert( pVar->flags & MEM_Blob );
64207        sqlite3StrAccumAppend(&out, "x'", 2);
64208        for(i=0; i<pVar->n; i++){
64209          sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64210        }
64211        sqlite3StrAccumAppend(&out, "'", 1);
64212      }
64213    }
64214  }
64215  return sqlite3StrAccumFinish(&out);
64216}
64217
64218#endif /* #ifndef SQLITE_OMIT_TRACE */
64219
64220/*****************************************************************************
64221** The following code implements the data-structure explaining logic
64222** for the Vdbe.
64223*/
64224
64225#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
64226
64227/*
64228** Allocate a new Explain object
64229*/
64230SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
64231  if( pVdbe ){
64232    sqlite3BeginBenignMalloc();
64233    Explain *p = sqlite3_malloc( sizeof(Explain) );
64234    if( p ){
64235      memset(p, 0, sizeof(*p));
64236      p->pVdbe = pVdbe;
64237      sqlite3_free(pVdbe->pExplain);
64238      pVdbe->pExplain = p;
64239      sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
64240                          SQLITE_MAX_LENGTH);
64241      p->str.useMalloc = 2;
64242    }else{
64243      sqlite3EndBenignMalloc();
64244    }
64245  }
64246}
64247
64248/*
64249** Return true if the Explain ends with a new-line.
64250*/
64251static int endsWithNL(Explain *p){
64252  return p && p->str.zText && p->str.nChar
64253           && p->str.zText[p->str.nChar-1]=='\n';
64254}
64255
64256/*
64257** Append text to the indentation
64258*/
64259SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
64260  Explain *p;
64261  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64262    va_list ap;
64263    if( p->nIndent && endsWithNL(p) ){
64264      int n = p->nIndent;
64265      if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
64266      sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
64267    }
64268    va_start(ap, zFormat);
64269    sqlite3VXPrintf(&p->str, 1, zFormat, ap);
64270    va_end(ap);
64271  }
64272}
64273
64274/*
64275** Append a '\n' if there is not already one.
64276*/
64277SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
64278  Explain *p;
64279  if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
64280    sqlite3StrAccumAppend(&p->str, "\n", 1);
64281  }
64282}
64283
64284/*
64285** Push a new indentation level.  Subsequent lines will be indented
64286** so that they begin at the current cursor position.
64287*/
64288SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
64289  Explain *p;
64290  if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64291    if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
64292      const char *z = p->str.zText;
64293      int i = p->str.nChar-1;
64294      int x;
64295      while( i>=0 && z[i]!='\n' ){ i--; }
64296      x = (p->str.nChar - 1) - i;
64297      if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
64298        x = p->aIndent[p->nIndent-1];
64299      }
64300      p->aIndent[p->nIndent] = x;
64301    }
64302    p->nIndent++;
64303  }
64304}
64305
64306/*
64307** Pop the indentation stack by one level.
64308*/
64309SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
64310  if( p && p->pExplain ) p->pExplain->nIndent--;
64311}
64312
64313/*
64314** Free the indentation structure
64315*/
64316SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
64317  if( pVdbe && pVdbe->pExplain ){
64318    sqlite3_free(pVdbe->zExplain);
64319    sqlite3ExplainNL(pVdbe);
64320    pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
64321    sqlite3_free(pVdbe->pExplain);
64322    pVdbe->pExplain = 0;
64323    sqlite3EndBenignMalloc();
64324  }
64325}
64326
64327/*
64328** Return the explanation of a virtual machine.
64329*/
64330SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
64331  return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
64332}
64333#endif /* defined(SQLITE_DEBUG) */
64334
64335/************** End of vdbetrace.c *******************************************/
64336/************** Begin file vdbe.c ********************************************/
64337/*
64338** 2001 September 15
64339**
64340** The author disclaims copyright to this source code.  In place of
64341** a legal notice, here is a blessing:
64342**
64343**    May you do good and not evil.
64344**    May you find forgiveness for yourself and forgive others.
64345**    May you share freely, never taking more than you give.
64346**
64347*************************************************************************
64348** The code in this file implements execution method of the
64349** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
64350** handles housekeeping details such as creating and deleting
64351** VDBE instances.  This file is solely interested in executing
64352** the VDBE program.
64353**
64354** In the external interface, an "sqlite3_stmt*" is an opaque pointer
64355** to a VDBE.
64356**
64357** The SQL parser generates a program which is then executed by
64358** the VDBE to do the work of the SQL statement.  VDBE programs are
64359** similar in form to assembly language.  The program consists of
64360** a linear sequence of operations.  Each operation has an opcode
64361** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4
64362** is a null-terminated string.  Operand P5 is an unsigned character.
64363** Few opcodes use all 5 operands.
64364**
64365** Computation results are stored on a set of registers numbered beginning
64366** with 1 and going up to Vdbe.nMem.  Each register can store
64367** either an integer, a null-terminated string, a floating point
64368** number, or the SQL "NULL" value.  An implicit conversion from one
64369** type to the other occurs as necessary.
64370**
64371** Most of the code in this file is taken up by the sqlite3VdbeExec()
64372** function which does the work of interpreting a VDBE program.
64373** But other routines are also provided to help in building up
64374** a program instruction by instruction.
64375**
64376** Various scripts scan this source file in order to generate HTML
64377** documentation, headers files, or other derived files.  The formatting
64378** of the code in this file is, therefore, important.  See other comments
64379** in this file for details.  If in doubt, do not deviate from existing
64380** commenting and indentation practices when changing or adding code.
64381*/
64382
64383/*
64384** Invoke this macro on memory cells just prior to changing the
64385** value of the cell.  This macro verifies that shallow copies are
64386** not misused.
64387*/
64388#ifdef SQLITE_DEBUG
64389# define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
64390#else
64391# define memAboutToChange(P,M)
64392#endif
64393
64394/*
64395** The following global variable is incremented every time a cursor
64396** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
64397** procedures use this information to make sure that indices are
64398** working correctly.  This variable has no function other than to
64399** help verify the correct operation of the library.
64400*/
64401#ifdef SQLITE_TEST
64402SQLITE_API int sqlite3_search_count = 0;
64403#endif
64404
64405/*
64406** When this global variable is positive, it gets decremented once before
64407** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
64408** field of the sqlite3 structure is set in order to simulate an interrupt.
64409**
64410** This facility is used for testing purposes only.  It does not function
64411** in an ordinary build.
64412*/
64413#ifdef SQLITE_TEST
64414SQLITE_API int sqlite3_interrupt_count = 0;
64415#endif
64416
64417/*
64418** The next global variable is incremented each type the OP_Sort opcode
64419** is executed.  The test procedures use this information to make sure that
64420** sorting is occurring or not occurring at appropriate times.   This variable
64421** has no function other than to help verify the correct operation of the
64422** library.
64423*/
64424#ifdef SQLITE_TEST
64425SQLITE_API int sqlite3_sort_count = 0;
64426#endif
64427
64428/*
64429** The next global variable records the size of the largest MEM_Blob
64430** or MEM_Str that has been used by a VDBE opcode.  The test procedures
64431** use this information to make sure that the zero-blob functionality
64432** is working correctly.   This variable has no function other than to
64433** help verify the correct operation of the library.
64434*/
64435#ifdef SQLITE_TEST
64436SQLITE_API int sqlite3_max_blobsize = 0;
64437static void updateMaxBlobsize(Mem *p){
64438  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
64439    sqlite3_max_blobsize = p->n;
64440  }
64441}
64442#endif
64443
64444/*
64445** The next global variable is incremented each type the OP_Found opcode
64446** is executed. This is used to test whether or not the foreign key
64447** operation implemented using OP_FkIsZero is working. This variable
64448** has no function other than to help verify the correct operation of the
64449** library.
64450*/
64451#ifdef SQLITE_TEST
64452SQLITE_API int sqlite3_found_count = 0;
64453#endif
64454
64455/*
64456** Test a register to see if it exceeds the current maximum blob size.
64457** If it does, record the new maximum blob size.
64458*/
64459#if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
64460# define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
64461#else
64462# define UPDATE_MAX_BLOBSIZE(P)
64463#endif
64464
64465/*
64466** Convert the given register into a string if it isn't one
64467** already. Return non-zero if a malloc() fails.
64468*/
64469#define Stringify(P, enc) \
64470   if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
64471     { goto no_mem; }
64472
64473/*
64474** An ephemeral string value (signified by the MEM_Ephem flag) contains
64475** a pointer to a dynamically allocated string where some other entity
64476** is responsible for deallocating that string.  Because the register
64477** does not control the string, it might be deleted without the register
64478** knowing it.
64479**
64480** This routine converts an ephemeral string into a dynamically allocated
64481** string that the register itself controls.  In other words, it
64482** converts an MEM_Ephem string into an MEM_Dyn string.
64483*/
64484#define Deephemeralize(P) \
64485   if( ((P)->flags&MEM_Ephem)!=0 \
64486       && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
64487
64488/* Return true if the cursor was opened using the OP_OpenSorter opcode. */
64489#ifdef SQLITE_OMIT_MERGE_SORT
64490# define isSorter(x) 0
64491#else
64492# define isSorter(x) ((x)->pSorter!=0)
64493#endif
64494
64495/*
64496** Argument pMem points at a register that will be passed to a
64497** user-defined function or returned to the user as the result of a query.
64498** This routine sets the pMem->type variable used by the sqlite3_value_*()
64499** routines.
64500*/
64501SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
64502  int flags = pMem->flags;
64503  if( flags & MEM_Null ){
64504    pMem->type = SQLITE_NULL;
64505  }
64506  else if( flags & MEM_Int ){
64507    pMem->type = SQLITE_INTEGER;
64508  }
64509  else if( flags & MEM_Real ){
64510    pMem->type = SQLITE_FLOAT;
64511  }
64512  else if( flags & MEM_Str ){
64513    pMem->type = SQLITE_TEXT;
64514  }else{
64515    pMem->type = SQLITE_BLOB;
64516  }
64517}
64518
64519/*
64520** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
64521** if we run out of memory.
64522*/
64523static VdbeCursor *allocateCursor(
64524  Vdbe *p,              /* The virtual machine */
64525  int iCur,             /* Index of the new VdbeCursor */
64526  int nField,           /* Number of fields in the table or index */
64527  int iDb,              /* Database the cursor belongs to, or -1 */
64528  int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
64529){
64530  /* Find the memory cell that will be used to store the blob of memory
64531  ** required for this VdbeCursor structure. It is convenient to use a
64532  ** vdbe memory cell to manage the memory allocation required for a
64533  ** VdbeCursor structure for the following reasons:
64534  **
64535  **   * Sometimes cursor numbers are used for a couple of different
64536  **     purposes in a vdbe program. The different uses might require
64537  **     different sized allocations. Memory cells provide growable
64538  **     allocations.
64539  **
64540  **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
64541  **     be freed lazily via the sqlite3_release_memory() API. This
64542  **     minimizes the number of malloc calls made by the system.
64543  **
64544  ** Memory cells for cursors are allocated at the top of the address
64545  ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
64546  ** cursor 1 is managed by memory cell (p->nMem-1), etc.
64547  */
64548  Mem *pMem = &p->aMem[p->nMem-iCur];
64549
64550  int nByte;
64551  VdbeCursor *pCx = 0;
64552  nByte =
64553      ROUND8(sizeof(VdbeCursor)) +
64554      (isBtreeCursor?sqlite3BtreeCursorSize():0) +
64555      2*nField*sizeof(u32);
64556
64557  assert( iCur<p->nCursor );
64558  if( p->apCsr[iCur] ){
64559    sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
64560    p->apCsr[iCur] = 0;
64561  }
64562  if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
64563    p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
64564    memset(pCx, 0, sizeof(VdbeCursor));
64565    pCx->iDb = iDb;
64566    pCx->nField = nField;
64567    if( nField ){
64568      pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
64569    }
64570    if( isBtreeCursor ){
64571      pCx->pCursor = (BtCursor*)
64572          &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
64573      sqlite3BtreeCursorZero(pCx->pCursor);
64574    }
64575  }
64576  return pCx;
64577}
64578
64579/*
64580** Try to convert a value into a numeric representation if we can
64581** do so without loss of information.  In other words, if the string
64582** looks like a number, convert it into a number.  If it does not
64583** look like a number, leave it alone.
64584*/
64585static void applyNumericAffinity(Mem *pRec){
64586  if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
64587    double rValue;
64588    i64 iValue;
64589    u8 enc = pRec->enc;
64590    if( (pRec->flags&MEM_Str)==0 ) return;
64591    if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
64592    if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
64593      pRec->u.i = iValue;
64594      pRec->flags |= MEM_Int;
64595    }else{
64596      pRec->r = rValue;
64597      pRec->flags |= MEM_Real;
64598    }
64599  }
64600}
64601
64602/*
64603** Processing is determine by the affinity parameter:
64604**
64605** SQLITE_AFF_INTEGER:
64606** SQLITE_AFF_REAL:
64607** SQLITE_AFF_NUMERIC:
64608**    Try to convert pRec to an integer representation or a
64609**    floating-point representation if an integer representation
64610**    is not possible.  Note that the integer representation is
64611**    always preferred, even if the affinity is REAL, because
64612**    an integer representation is more space efficient on disk.
64613**
64614** SQLITE_AFF_TEXT:
64615**    Convert pRec to a text representation.
64616**
64617** SQLITE_AFF_NONE:
64618**    No-op.  pRec is unchanged.
64619*/
64620static void applyAffinity(
64621  Mem *pRec,          /* The value to apply affinity to */
64622  char affinity,      /* The affinity to be applied */
64623  u8 enc              /* Use this text encoding */
64624){
64625  if( affinity==SQLITE_AFF_TEXT ){
64626    /* Only attempt the conversion to TEXT if there is an integer or real
64627    ** representation (blob and NULL do not get converted) but no string
64628    ** representation.
64629    */
64630    if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
64631      sqlite3VdbeMemStringify(pRec, enc);
64632    }
64633    pRec->flags &= ~(MEM_Real|MEM_Int);
64634  }else if( affinity!=SQLITE_AFF_NONE ){
64635    assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
64636             || affinity==SQLITE_AFF_NUMERIC );
64637    applyNumericAffinity(pRec);
64638    if( pRec->flags & MEM_Real ){
64639      sqlite3VdbeIntegerAffinity(pRec);
64640    }
64641  }
64642}
64643
64644/*
64645** Try to convert the type of a function argument or a result column
64646** into a numeric representation.  Use either INTEGER or REAL whichever
64647** is appropriate.  But only do the conversion if it is possible without
64648** loss of information and return the revised type of the argument.
64649*/
64650SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
64651  Mem *pMem = (Mem*)pVal;
64652  if( pMem->type==SQLITE_TEXT ){
64653    applyNumericAffinity(pMem);
64654    sqlite3VdbeMemStoreType(pMem);
64655  }
64656  return pMem->type;
64657}
64658
64659/*
64660** Exported version of applyAffinity(). This one works on sqlite3_value*,
64661** not the internal Mem* type.
64662*/
64663SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
64664  sqlite3_value *pVal,
64665  u8 affinity,
64666  u8 enc
64667){
64668  applyAffinity((Mem *)pVal, affinity, enc);
64669}
64670
64671#ifdef SQLITE_DEBUG
64672/*
64673** Write a nice string representation of the contents of cell pMem
64674** into buffer zBuf, length nBuf.
64675*/
64676SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
64677  char *zCsr = zBuf;
64678  int f = pMem->flags;
64679
64680  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
64681
64682  if( f&MEM_Blob ){
64683    int i;
64684    char c;
64685    if( f & MEM_Dyn ){
64686      c = 'z';
64687      assert( (f & (MEM_Static|MEM_Ephem))==0 );
64688    }else if( f & MEM_Static ){
64689      c = 't';
64690      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
64691    }else if( f & MEM_Ephem ){
64692      c = 'e';
64693      assert( (f & (MEM_Static|MEM_Dyn))==0 );
64694    }else{
64695      c = 's';
64696    }
64697
64698    sqlite3_snprintf(100, zCsr, "%c", c);
64699    zCsr += sqlite3Strlen30(zCsr);
64700    sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
64701    zCsr += sqlite3Strlen30(zCsr);
64702    for(i=0; i<16 && i<pMem->n; i++){
64703      sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
64704      zCsr += sqlite3Strlen30(zCsr);
64705    }
64706    for(i=0; i<16 && i<pMem->n; i++){
64707      char z = pMem->z[i];
64708      if( z<32 || z>126 ) *zCsr++ = '.';
64709      else *zCsr++ = z;
64710    }
64711
64712    sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
64713    zCsr += sqlite3Strlen30(zCsr);
64714    if( f & MEM_Zero ){
64715      sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
64716      zCsr += sqlite3Strlen30(zCsr);
64717    }
64718    *zCsr = '\0';
64719  }else if( f & MEM_Str ){
64720    int j, k;
64721    zBuf[0] = ' ';
64722    if( f & MEM_Dyn ){
64723      zBuf[1] = 'z';
64724      assert( (f & (MEM_Static|MEM_Ephem))==0 );
64725    }else if( f & MEM_Static ){
64726      zBuf[1] = 't';
64727      assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
64728    }else if( f & MEM_Ephem ){
64729      zBuf[1] = 'e';
64730      assert( (f & (MEM_Static|MEM_Dyn))==0 );
64731    }else{
64732      zBuf[1] = 's';
64733    }
64734    k = 2;
64735    sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
64736    k += sqlite3Strlen30(&zBuf[k]);
64737    zBuf[k++] = '[';
64738    for(j=0; j<15 && j<pMem->n; j++){
64739      u8 c = pMem->z[j];
64740      if( c>=0x20 && c<0x7f ){
64741        zBuf[k++] = c;
64742      }else{
64743        zBuf[k++] = '.';
64744      }
64745    }
64746    zBuf[k++] = ']';
64747    sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
64748    k += sqlite3Strlen30(&zBuf[k]);
64749    zBuf[k++] = 0;
64750  }
64751}
64752#endif
64753
64754#ifdef SQLITE_DEBUG
64755/*
64756** Print the value of a register for tracing purposes:
64757*/
64758static void memTracePrint(FILE *out, Mem *p){
64759  if( p->flags & MEM_Null ){
64760    fprintf(out, " NULL");
64761  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
64762    fprintf(out, " si:%lld", p->u.i);
64763  }else if( p->flags & MEM_Int ){
64764    fprintf(out, " i:%lld", p->u.i);
64765#ifndef SQLITE_OMIT_FLOATING_POINT
64766  }else if( p->flags & MEM_Real ){
64767    fprintf(out, " r:%g", p->r);
64768#endif
64769  }else if( p->flags & MEM_RowSet ){
64770    fprintf(out, " (rowset)");
64771  }else{
64772    char zBuf[200];
64773    sqlite3VdbeMemPrettyPrint(p, zBuf);
64774    fprintf(out, " ");
64775    fprintf(out, "%s", zBuf);
64776  }
64777}
64778static void registerTrace(FILE *out, int iReg, Mem *p){
64779  fprintf(out, "REG[%d] = ", iReg);
64780  memTracePrint(out, p);
64781  fprintf(out, "\n");
64782}
64783#endif
64784
64785#ifdef SQLITE_DEBUG
64786#  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
64787#else
64788#  define REGISTER_TRACE(R,M)
64789#endif
64790
64791
64792#ifdef VDBE_PROFILE
64793
64794/*
64795** hwtime.h contains inline assembler code for implementing
64796** high-performance timing routines.
64797*/
64798/************** Include hwtime.h in the middle of vdbe.c *********************/
64799/************** Begin file hwtime.h ******************************************/
64800/*
64801** 2008 May 27
64802**
64803** The author disclaims copyright to this source code.  In place of
64804** a legal notice, here is a blessing:
64805**
64806**    May you do good and not evil.
64807**    May you find forgiveness for yourself and forgive others.
64808**    May you share freely, never taking more than you give.
64809**
64810******************************************************************************
64811**
64812** This file contains inline asm code for retrieving "high-performance"
64813** counters for x86 class CPUs.
64814*/
64815#ifndef _HWTIME_H_
64816#define _HWTIME_H_
64817
64818/*
64819** The following routine only works on pentium-class (or newer) processors.
64820** It uses the RDTSC opcode to read the cycle count value out of the
64821** processor and returns that value.  This can be used for high-res
64822** profiling.
64823*/
64824#if (defined(__GNUC__) || defined(_MSC_VER)) && \
64825      (defined(i386) || defined(__i386__) || defined(_M_IX86))
64826
64827  #if defined(__GNUC__)
64828
64829  __inline__ sqlite_uint64 sqlite3Hwtime(void){
64830     unsigned int lo, hi;
64831     __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
64832     return (sqlite_uint64)hi << 32 | lo;
64833  }
64834
64835  #elif defined(_MSC_VER)
64836
64837  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
64838     __asm {
64839        rdtsc
64840        ret       ; return value at EDX:EAX
64841     }
64842  }
64843
64844  #endif
64845
64846#elif (defined(__GNUC__) && defined(__x86_64__))
64847
64848  __inline__ sqlite_uint64 sqlite3Hwtime(void){
64849      unsigned long val;
64850      __asm__ __volatile__ ("rdtsc" : "=A" (val));
64851      return val;
64852  }
64853
64854#elif (defined(__GNUC__) && defined(__ppc__))
64855
64856  __inline__ sqlite_uint64 sqlite3Hwtime(void){
64857      unsigned long long retval;
64858      unsigned long junk;
64859      __asm__ __volatile__ ("\n\
64860          1:      mftbu   %1\n\
64861                  mftb    %L0\n\
64862                  mftbu   %0\n\
64863                  cmpw    %0,%1\n\
64864                  bne     1b"
64865                  : "=r" (retval), "=r" (junk));
64866      return retval;
64867  }
64868
64869#else
64870
64871  #error Need implementation of sqlite3Hwtime() for your platform.
64872
64873  /*
64874  ** To compile without implementing sqlite3Hwtime() for your platform,
64875  ** you can remove the above #error and use the following
64876  ** stub function.  You will lose timing support for many
64877  ** of the debugging and testing utilities, but it should at
64878  ** least compile and run.
64879  */
64880SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
64881
64882#endif
64883
64884#endif /* !defined(_HWTIME_H_) */
64885
64886/************** End of hwtime.h **********************************************/
64887/************** Continuing where we left off in vdbe.c ***********************/
64888
64889#endif
64890
64891/*
64892** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
64893** sqlite3_interrupt() routine has been called.  If it has been, then
64894** processing of the VDBE program is interrupted.
64895**
64896** This macro added to every instruction that does a jump in order to
64897** implement a loop.  This test used to be on every single instruction,
64898** but that meant we more testing than we needed.  By only testing the
64899** flag on jump instructions, we get a (small) speed improvement.
64900*/
64901#define CHECK_FOR_INTERRUPT \
64902   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
64903
64904
64905#ifndef NDEBUG
64906/*
64907** This function is only called from within an assert() expression. It
64908** checks that the sqlite3.nTransaction variable is correctly set to
64909** the number of non-transaction savepoints currently in the
64910** linked list starting at sqlite3.pSavepoint.
64911**
64912** Usage:
64913**
64914**     assert( checkSavepointCount(db) );
64915*/
64916static int checkSavepointCount(sqlite3 *db){
64917  int n = 0;
64918  Savepoint *p;
64919  for(p=db->pSavepoint; p; p=p->pNext) n++;
64920  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
64921  return 1;
64922}
64923#endif
64924
64925/*
64926** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
64927** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
64928** in memory obtained from sqlite3DbMalloc).
64929*/
64930static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
64931  sqlite3 *db = p->db;
64932  sqlite3DbFree(db, p->zErrMsg);
64933  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
64934  sqlite3_free(pVtab->zErrMsg);
64935  pVtab->zErrMsg = 0;
64936}
64937
64938
64939/*
64940** Execute as much of a VDBE program as we can then return.
64941**
64942** sqlite3VdbeMakeReady() must be called before this routine in order to
64943** close the program with a final OP_Halt and to set up the callbacks
64944** and the error message pointer.
64945**
64946** Whenever a row or result data is available, this routine will either
64947** invoke the result callback (if there is one) or return with
64948** SQLITE_ROW.
64949**
64950** If an attempt is made to open a locked database, then this routine
64951** will either invoke the busy callback (if there is one) or it will
64952** return SQLITE_BUSY.
64953**
64954** If an error occurs, an error message is written to memory obtained
64955** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
64956** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
64957**
64958** If the callback ever returns non-zero, then the program exits
64959** immediately.  There will be no error message but the p->rc field is
64960** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
64961**
64962** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
64963** routine to return SQLITE_ERROR.
64964**
64965** Other fatal errors return SQLITE_ERROR.
64966**
64967** After this routine has finished, sqlite3VdbeFinalize() should be
64968** used to clean up the mess that was left behind.
64969*/
64970SQLITE_PRIVATE int sqlite3VdbeExec(
64971  Vdbe *p                    /* The VDBE */
64972){
64973  int pc=0;                  /* The program counter */
64974  Op *aOp = p->aOp;          /* Copy of p->aOp */
64975  Op *pOp;                   /* Current operation */
64976  int rc = SQLITE_OK;        /* Value to return */
64977  sqlite3 *db = p->db;       /* The database */
64978  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
64979  u8 encoding = ENC(db);     /* The database encoding */
64980#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
64981  int checkProgress;         /* True if progress callbacks are enabled */
64982  int nProgressOps = 0;      /* Opcodes executed since progress callback. */
64983#endif
64984  Mem *aMem = p->aMem;       /* Copy of p->aMem */
64985  Mem *pIn1 = 0;             /* 1st input operand */
64986  Mem *pIn2 = 0;             /* 2nd input operand */
64987  Mem *pIn3 = 0;             /* 3rd input operand */
64988  Mem *pOut = 0;             /* Output operand */
64989  int iCompare = 0;          /* Result of last OP_Compare operation */
64990  int *aPermute = 0;         /* Permutation of columns for OP_Compare */
64991  i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
64992#ifdef VDBE_PROFILE
64993  u64 start;                 /* CPU clock count at start of opcode */
64994  int origPc;                /* Program counter at start of opcode */
64995#endif
64996  /********************************************************************
64997  ** Automatically generated code
64998  **
64999  ** The following union is automatically generated by the
65000  ** vdbe-compress.tcl script.  The purpose of this union is to
65001  ** reduce the amount of stack space required by this function.
65002  ** See comments in the vdbe-compress.tcl script for details.
65003  */
65004  union vdbeExecUnion {
65005    struct OP_Yield_stack_vars {
65006      int pcDest;
65007    } aa;
65008    struct OP_Null_stack_vars {
65009      int cnt;
65010    } ab;
65011    struct OP_Variable_stack_vars {
65012      Mem *pVar;       /* Value being transferred */
65013    } ac;
65014    struct OP_Move_stack_vars {
65015      char *zMalloc;   /* Holding variable for allocated memory */
65016      int n;           /* Number of registers left to copy */
65017      int p1;          /* Register to copy from */
65018      int p2;          /* Register to copy to */
65019    } ad;
65020    struct OP_ResultRow_stack_vars {
65021      Mem *pMem;
65022      int i;
65023    } ae;
65024    struct OP_Concat_stack_vars {
65025      i64 nByte;
65026    } af;
65027    struct OP_Remainder_stack_vars {
65028      int flags;      /* Combined MEM_* flags from both inputs */
65029      i64 iA;         /* Integer value of left operand */
65030      i64 iB;         /* Integer value of right operand */
65031      double rA;      /* Real value of left operand */
65032      double rB;      /* Real value of right operand */
65033    } ag;
65034    struct OP_Function_stack_vars {
65035      int i;
65036      Mem *pArg;
65037      sqlite3_context ctx;
65038      sqlite3_value **apVal;
65039      int n;
65040    } ah;
65041    struct OP_ShiftRight_stack_vars {
65042      i64 iA;
65043      u64 uA;
65044      i64 iB;
65045      u8 op;
65046    } ai;
65047    struct OP_Ge_stack_vars {
65048      int res;            /* Result of the comparison of pIn1 against pIn3 */
65049      char affinity;      /* Affinity to use for comparison */
65050      u16 flags1;         /* Copy of initial value of pIn1->flags */
65051      u16 flags3;         /* Copy of initial value of pIn3->flags */
65052    } aj;
65053    struct OP_Compare_stack_vars {
65054      int n;
65055      int i;
65056      int p1;
65057      int p2;
65058      const KeyInfo *pKeyInfo;
65059      int idx;
65060      CollSeq *pColl;    /* Collating sequence to use on this term */
65061      int bRev;          /* True for DESCENDING sort order */
65062    } ak;
65063    struct OP_Or_stack_vars {
65064      int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65065      int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65066    } al;
65067    struct OP_IfNot_stack_vars {
65068      int c;
65069    } am;
65070    struct OP_Column_stack_vars {
65071      u32 payloadSize;   /* Number of bytes in the record */
65072      i64 payloadSize64; /* Number of bytes in the record */
65073      int p1;            /* P1 value of the opcode */
65074      int p2;            /* column number to retrieve */
65075      VdbeCursor *pC;    /* The VDBE cursor */
65076      char *zRec;        /* Pointer to complete record-data */
65077      BtCursor *pCrsr;   /* The BTree cursor */
65078      u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65079      u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65080      int nField;        /* number of fields in the record */
65081      int len;           /* The length of the serialized data for the column */
65082      int i;             /* Loop counter */
65083      char *zData;       /* Part of the record being decoded */
65084      Mem *pDest;        /* Where to write the extracted value */
65085      Mem sMem;          /* For storing the record being decoded */
65086      u8 *zIdx;          /* Index into header */
65087      u8 *zEndHdr;       /* Pointer to first byte after the header */
65088      u32 offset;        /* Offset into the data */
65089      u32 szField;       /* Number of bytes in the content of a field */
65090      int szHdr;         /* Size of the header size field at start of record */
65091      int avail;         /* Number of bytes of available data */
65092      u32 t;             /* A type code from the record header */
65093      Mem *pReg;         /* PseudoTable input register */
65094    } an;
65095    struct OP_Affinity_stack_vars {
65096      const char *zAffinity;   /* The affinity to be applied */
65097      char cAff;               /* A single character of affinity */
65098    } ao;
65099    struct OP_MakeRecord_stack_vars {
65100      u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65101      Mem *pRec;             /* The new record */
65102      u64 nData;             /* Number of bytes of data space */
65103      int nHdr;              /* Number of bytes of header space */
65104      i64 nByte;             /* Data space required for this record */
65105      int nZero;             /* Number of zero bytes at the end of the record */
65106      int nVarint;           /* Number of bytes in a varint */
65107      u32 serial_type;       /* Type field */
65108      Mem *pData0;           /* First field to be combined into the record */
65109      Mem *pLast;            /* Last field of the record */
65110      int nField;            /* Number of fields in the record */
65111      char *zAffinity;       /* The affinity string for the record */
65112      int file_format;       /* File format to use for encoding */
65113      int i;                 /* Space used in zNewRecord[] */
65114      int len;               /* Length of a field */
65115    } ap;
65116    struct OP_Count_stack_vars {
65117      i64 nEntry;
65118      BtCursor *pCrsr;
65119    } aq;
65120    struct OP_Savepoint_stack_vars {
65121      int p1;                         /* Value of P1 operand */
65122      char *zName;                    /* Name of savepoint */
65123      int nName;
65124      Savepoint *pNew;
65125      Savepoint *pSavepoint;
65126      Savepoint *pTmp;
65127      int iSavepoint;
65128      int ii;
65129    } ar;
65130    struct OP_AutoCommit_stack_vars {
65131      int desiredAutoCommit;
65132      int iRollback;
65133      int turnOnAC;
65134    } as;
65135    struct OP_Transaction_stack_vars {
65136      Btree *pBt;
65137    } at;
65138    struct OP_ReadCookie_stack_vars {
65139      int iMeta;
65140      int iDb;
65141      int iCookie;
65142    } au;
65143    struct OP_SetCookie_stack_vars {
65144      Db *pDb;
65145    } av;
65146    struct OP_VerifyCookie_stack_vars {
65147      int iMeta;
65148      int iGen;
65149      Btree *pBt;
65150    } aw;
65151    struct OP_OpenWrite_stack_vars {
65152      int nField;
65153      KeyInfo *pKeyInfo;
65154      int p2;
65155      int iDb;
65156      int wrFlag;
65157      Btree *pX;
65158      VdbeCursor *pCur;
65159      Db *pDb;
65160    } ax;
65161    struct OP_OpenEphemeral_stack_vars {
65162      VdbeCursor *pCx;
65163    } ay;
65164    struct OP_SorterOpen_stack_vars {
65165      VdbeCursor *pCx;
65166    } az;
65167    struct OP_OpenPseudo_stack_vars {
65168      VdbeCursor *pCx;
65169    } ba;
65170    struct OP_SeekGt_stack_vars {
65171      int res;
65172      int oc;
65173      VdbeCursor *pC;
65174      UnpackedRecord r;
65175      int nField;
65176      i64 iKey;      /* The rowid we are to seek to */
65177    } bb;
65178    struct OP_Seek_stack_vars {
65179      VdbeCursor *pC;
65180    } bc;
65181    struct OP_Found_stack_vars {
65182      int alreadyExists;
65183      VdbeCursor *pC;
65184      int res;
65185      char *pFree;
65186      UnpackedRecord *pIdxKey;
65187      UnpackedRecord r;
65188      char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65189    } bd;
65190    struct OP_IsUnique_stack_vars {
65191      u16 ii;
65192      VdbeCursor *pCx;
65193      BtCursor *pCrsr;
65194      u16 nField;
65195      Mem *aMx;
65196      UnpackedRecord r;                  /* B-Tree index search key */
65197      i64 R;                             /* Rowid stored in register P3 */
65198    } be;
65199    struct OP_NotExists_stack_vars {
65200      VdbeCursor *pC;
65201      BtCursor *pCrsr;
65202      int res;
65203      u64 iKey;
65204    } bf;
65205    struct OP_NewRowid_stack_vars {
65206      i64 v;                 /* The new rowid */
65207      VdbeCursor *pC;        /* Cursor of table to get the new rowid */
65208      int res;               /* Result of an sqlite3BtreeLast() */
65209      int cnt;               /* Counter to limit the number of searches */
65210      Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
65211      VdbeFrame *pFrame;     /* Root frame of VDBE */
65212    } bg;
65213    struct OP_InsertInt_stack_vars {
65214      Mem *pData;       /* MEM cell holding data for the record to be inserted */
65215      Mem *pKey;        /* MEM cell holding key  for the record */
65216      i64 iKey;         /* The integer ROWID or key for the record to be inserted */
65217      VdbeCursor *pC;   /* Cursor to table into which insert is written */
65218      int nZero;        /* Number of zero-bytes to append */
65219      int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
65220      const char *zDb;  /* database name - used by the update hook */
65221      const char *zTbl; /* Table name - used by the opdate hook */
65222      int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
65223    } bh;
65224    struct OP_Delete_stack_vars {
65225      i64 iKey;
65226      VdbeCursor *pC;
65227    } bi;
65228    struct OP_SorterCompare_stack_vars {
65229      VdbeCursor *pC;
65230      int res;
65231    } bj;
65232    struct OP_SorterData_stack_vars {
65233      VdbeCursor *pC;
65234    } bk;
65235    struct OP_RowData_stack_vars {
65236      VdbeCursor *pC;
65237      BtCursor *pCrsr;
65238      u32 n;
65239      i64 n64;
65240    } bl;
65241    struct OP_Rowid_stack_vars {
65242      VdbeCursor *pC;
65243      i64 v;
65244      sqlite3_vtab *pVtab;
65245      const sqlite3_module *pModule;
65246    } bm;
65247    struct OP_NullRow_stack_vars {
65248      VdbeCursor *pC;
65249    } bn;
65250    struct OP_Last_stack_vars {
65251      VdbeCursor *pC;
65252      BtCursor *pCrsr;
65253      int res;
65254    } bo;
65255    struct OP_Rewind_stack_vars {
65256      VdbeCursor *pC;
65257      BtCursor *pCrsr;
65258      int res;
65259    } bp;
65260    struct OP_Next_stack_vars {
65261      VdbeCursor *pC;
65262      int res;
65263    } bq;
65264    struct OP_IdxInsert_stack_vars {
65265      VdbeCursor *pC;
65266      BtCursor *pCrsr;
65267      int nKey;
65268      const char *zKey;
65269    } br;
65270    struct OP_IdxDelete_stack_vars {
65271      VdbeCursor *pC;
65272      BtCursor *pCrsr;
65273      int res;
65274      UnpackedRecord r;
65275    } bs;
65276    struct OP_IdxRowid_stack_vars {
65277      BtCursor *pCrsr;
65278      VdbeCursor *pC;
65279      i64 rowid;
65280    } bt;
65281    struct OP_IdxGE_stack_vars {
65282      VdbeCursor *pC;
65283      int res;
65284      UnpackedRecord r;
65285    } bu;
65286    struct OP_Destroy_stack_vars {
65287      int iMoved;
65288      int iCnt;
65289      Vdbe *pVdbe;
65290      int iDb;
65291    } bv;
65292    struct OP_Clear_stack_vars {
65293      int nChange;
65294    } bw;
65295    struct OP_CreateTable_stack_vars {
65296      int pgno;
65297      int flags;
65298      Db *pDb;
65299    } bx;
65300    struct OP_ParseSchema_stack_vars {
65301      int iDb;
65302      const char *zMaster;
65303      char *zSql;
65304      InitData initData;
65305    } by;
65306    struct OP_IntegrityCk_stack_vars {
65307      int nRoot;      /* Number of tables to check.  (Number of root pages.) */
65308      int *aRoot;     /* Array of rootpage numbers for tables to be checked */
65309      int j;          /* Loop counter */
65310      int nErr;       /* Number of errors reported */
65311      char *z;        /* Text of the error report */
65312      Mem *pnErr;     /* Register keeping track of errors remaining */
65313    } bz;
65314    struct OP_RowSetRead_stack_vars {
65315      i64 val;
65316    } ca;
65317    struct OP_RowSetTest_stack_vars {
65318      int iSet;
65319      int exists;
65320    } cb;
65321    struct OP_Program_stack_vars {
65322      int nMem;               /* Number of memory registers for sub-program */
65323      int nByte;              /* Bytes of runtime space required for sub-program */
65324      Mem *pRt;               /* Register to allocate runtime space */
65325      Mem *pMem;              /* Used to iterate through memory cells */
65326      Mem *pEnd;              /* Last memory cell in new array */
65327      VdbeFrame *pFrame;      /* New vdbe frame to execute in */
65328      SubProgram *pProgram;   /* Sub-program to execute */
65329      void *t;                /* Token identifying trigger */
65330    } cc;
65331    struct OP_Param_stack_vars {
65332      VdbeFrame *pFrame;
65333      Mem *pIn;
65334    } cd;
65335    struct OP_MemMax_stack_vars {
65336      Mem *pIn1;
65337      VdbeFrame *pFrame;
65338    } ce;
65339    struct OP_AggStep_stack_vars {
65340      int n;
65341      int i;
65342      Mem *pMem;
65343      Mem *pRec;
65344      sqlite3_context ctx;
65345      sqlite3_value **apVal;
65346    } cf;
65347    struct OP_AggFinal_stack_vars {
65348      Mem *pMem;
65349    } cg;
65350    struct OP_Checkpoint_stack_vars {
65351      int i;                          /* Loop counter */
65352      int aRes[3];                    /* Results */
65353      Mem *pMem;                      /* Write results here */
65354    } ch;
65355    struct OP_JournalMode_stack_vars {
65356      Btree *pBt;                     /* Btree to change journal mode of */
65357      Pager *pPager;                  /* Pager associated with pBt */
65358      int eNew;                       /* New journal mode */
65359      int eOld;                       /* The old journal mode */
65360      const char *zFilename;          /* Name of database file for pPager */
65361    } ci;
65362    struct OP_IncrVacuum_stack_vars {
65363      Btree *pBt;
65364    } cj;
65365    struct OP_VBegin_stack_vars {
65366      VTable *pVTab;
65367    } ck;
65368    struct OP_VOpen_stack_vars {
65369      VdbeCursor *pCur;
65370      sqlite3_vtab_cursor *pVtabCursor;
65371      sqlite3_vtab *pVtab;
65372      sqlite3_module *pModule;
65373    } cl;
65374    struct OP_VFilter_stack_vars {
65375      int nArg;
65376      int iQuery;
65377      const sqlite3_module *pModule;
65378      Mem *pQuery;
65379      Mem *pArgc;
65380      sqlite3_vtab_cursor *pVtabCursor;
65381      sqlite3_vtab *pVtab;
65382      VdbeCursor *pCur;
65383      int res;
65384      int i;
65385      Mem **apArg;
65386    } cm;
65387    struct OP_VColumn_stack_vars {
65388      sqlite3_vtab *pVtab;
65389      const sqlite3_module *pModule;
65390      Mem *pDest;
65391      sqlite3_context sContext;
65392    } cn;
65393    struct OP_VNext_stack_vars {
65394      sqlite3_vtab *pVtab;
65395      const sqlite3_module *pModule;
65396      int res;
65397      VdbeCursor *pCur;
65398    } co;
65399    struct OP_VRename_stack_vars {
65400      sqlite3_vtab *pVtab;
65401      Mem *pName;
65402    } cp;
65403    struct OP_VUpdate_stack_vars {
65404      sqlite3_vtab *pVtab;
65405      sqlite3_module *pModule;
65406      int nArg;
65407      int i;
65408      sqlite_int64 rowid;
65409      Mem **apArg;
65410      Mem *pX;
65411    } cq;
65412    struct OP_Trace_stack_vars {
65413      char *zTrace;
65414      char *z;
65415    } cr;
65416  } u;
65417  /* End automatically generated code
65418  ********************************************************************/
65419
65420  assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
65421  sqlite3VdbeEnter(p);
65422  if( p->rc==SQLITE_NOMEM ){
65423    /* This happens if a malloc() inside a call to sqlite3_column_text() or
65424    ** sqlite3_column_text16() failed.  */
65425    goto no_mem;
65426  }
65427  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
65428  p->rc = SQLITE_OK;
65429  assert( p->explain==0 );
65430  p->pResultSet = 0;
65431  db->busyHandler.nBusy = 0;
65432  CHECK_FOR_INTERRUPT;
65433  sqlite3VdbeIOTraceSql(p);
65434#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65435  checkProgress = db->xProgress!=0;
65436#endif
65437#ifdef SQLITE_DEBUG
65438  sqlite3BeginBenignMalloc();
65439  if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
65440    int i;
65441    printf("VDBE Program Listing:\n");
65442    sqlite3VdbePrintSql(p);
65443    for(i=0; i<p->nOp; i++){
65444      sqlite3VdbePrintOp(stdout, i, &aOp[i]);
65445    }
65446  }
65447  sqlite3EndBenignMalloc();
65448#endif
65449  for(pc=p->pc; rc==SQLITE_OK; pc++){
65450    assert( pc>=0 && pc<p->nOp );
65451    if( db->mallocFailed ) goto no_mem;
65452#ifdef VDBE_PROFILE
65453    origPc = pc;
65454    start = sqlite3Hwtime();
65455#endif
65456    pOp = &aOp[pc];
65457
65458    /* Only allow tracing if SQLITE_DEBUG is defined.
65459    */
65460#ifdef SQLITE_DEBUG
65461    if( p->trace ){
65462      if( pc==0 ){
65463        printf("VDBE Execution Trace:\n");
65464        sqlite3VdbePrintSql(p);
65465      }
65466      sqlite3VdbePrintOp(p->trace, pc, pOp);
65467    }
65468#endif
65469
65470
65471    /* Check to see if we need to simulate an interrupt.  This only happens
65472    ** if we have a special test build.
65473    */
65474#ifdef SQLITE_TEST
65475    if( sqlite3_interrupt_count>0 ){
65476      sqlite3_interrupt_count--;
65477      if( sqlite3_interrupt_count==0 ){
65478        sqlite3_interrupt(db);
65479      }
65480    }
65481#endif
65482
65483#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65484    /* Call the progress callback if it is configured and the required number
65485    ** of VDBE ops have been executed (either since this invocation of
65486    ** sqlite3VdbeExec() or since last time the progress callback was called).
65487    ** If the progress callback returns non-zero, exit the virtual machine with
65488    ** a return code SQLITE_ABORT.
65489    */
65490    if( checkProgress ){
65491      if( db->nProgressOps==nProgressOps ){
65492        int prc;
65493        prc = db->xProgress(db->pProgressArg);
65494        if( prc!=0 ){
65495          rc = SQLITE_INTERRUPT;
65496          goto vdbe_error_halt;
65497        }
65498        nProgressOps = 0;
65499      }
65500      nProgressOps++;
65501    }
65502#endif
65503
65504    /* On any opcode with the "out2-prerelase" tag, free any
65505    ** external allocations out of mem[p2] and set mem[p2] to be
65506    ** an undefined integer.  Opcodes will either fill in the integer
65507    ** value or convert mem[p2] to a different type.
65508    */
65509    assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
65510    if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
65511      assert( pOp->p2>0 );
65512      assert( pOp->p2<=p->nMem );
65513      pOut = &aMem[pOp->p2];
65514      memAboutToChange(p, pOut);
65515      VdbeMemRelease(pOut);
65516      pOut->flags = MEM_Int;
65517    }
65518
65519    /* Sanity checking on other operands */
65520#ifdef SQLITE_DEBUG
65521    if( (pOp->opflags & OPFLG_IN1)!=0 ){
65522      assert( pOp->p1>0 );
65523      assert( pOp->p1<=p->nMem );
65524      assert( memIsValid(&aMem[pOp->p1]) );
65525      REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
65526    }
65527    if( (pOp->opflags & OPFLG_IN2)!=0 ){
65528      assert( pOp->p2>0 );
65529      assert( pOp->p2<=p->nMem );
65530      assert( memIsValid(&aMem[pOp->p2]) );
65531      REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
65532    }
65533    if( (pOp->opflags & OPFLG_IN3)!=0 ){
65534      assert( pOp->p3>0 );
65535      assert( pOp->p3<=p->nMem );
65536      assert( memIsValid(&aMem[pOp->p3]) );
65537      REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
65538    }
65539    if( (pOp->opflags & OPFLG_OUT2)!=0 ){
65540      assert( pOp->p2>0 );
65541      assert( pOp->p2<=p->nMem );
65542      memAboutToChange(p, &aMem[pOp->p2]);
65543    }
65544    if( (pOp->opflags & OPFLG_OUT3)!=0 ){
65545      assert( pOp->p3>0 );
65546      assert( pOp->p3<=p->nMem );
65547      memAboutToChange(p, &aMem[pOp->p3]);
65548    }
65549#endif
65550
65551    switch( pOp->opcode ){
65552
65553/*****************************************************************************
65554** What follows is a massive switch statement where each case implements a
65555** separate instruction in the virtual machine.  If we follow the usual
65556** indentation conventions, each case should be indented by 6 spaces.  But
65557** that is a lot of wasted space on the left margin.  So the code within
65558** the switch statement will break with convention and be flush-left. Another
65559** big comment (similar to this one) will mark the point in the code where
65560** we transition back to normal indentation.
65561**
65562** The formatting of each case is important.  The makefile for SQLite
65563** generates two C files "opcodes.h" and "opcodes.c" by scanning this
65564** file looking for lines that begin with "case OP_".  The opcodes.h files
65565** will be filled with #defines that give unique integer values to each
65566** opcode and the opcodes.c file is filled with an array of strings where
65567** each string is the symbolic name for the corresponding opcode.  If the
65568** case statement is followed by a comment of the form "/# same as ... #/"
65569** that comment is used to determine the particular value of the opcode.
65570**
65571** Other keywords in the comment that follows each case are used to
65572** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
65573** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
65574** the mkopcodeh.awk script for additional information.
65575**
65576** Documentation about VDBE opcodes is generated by scanning this file
65577** for lines of that contain "Opcode:".  That line and all subsequent
65578** comment lines are used in the generation of the opcode.html documentation
65579** file.
65580**
65581** SUMMARY:
65582**
65583**     Formatting is important to scripts that scan this file.
65584**     Do not deviate from the formatting style currently in use.
65585**
65586*****************************************************************************/
65587
65588/* Opcode:  Goto * P2 * * *
65589**
65590** An unconditional jump to address P2.
65591** The next instruction executed will be
65592** the one at index P2 from the beginning of
65593** the program.
65594*/
65595case OP_Goto: {             /* jump */
65596  CHECK_FOR_INTERRUPT;
65597  pc = pOp->p2 - 1;
65598  break;
65599}
65600
65601/* Opcode:  Gosub P1 P2 * * *
65602**
65603** Write the current address onto register P1
65604** and then jump to address P2.
65605*/
65606case OP_Gosub: {            /* jump */
65607  assert( pOp->p1>0 && pOp->p1<=p->nMem );
65608  pIn1 = &aMem[pOp->p1];
65609  assert( (pIn1->flags & MEM_Dyn)==0 );
65610  memAboutToChange(p, pIn1);
65611  pIn1->flags = MEM_Int;
65612  pIn1->u.i = pc;
65613  REGISTER_TRACE(pOp->p1, pIn1);
65614  pc = pOp->p2 - 1;
65615  break;
65616}
65617
65618/* Opcode:  Return P1 * * * *
65619**
65620** Jump to the next instruction after the address in register P1.
65621*/
65622case OP_Return: {           /* in1 */
65623  pIn1 = &aMem[pOp->p1];
65624  assert( pIn1->flags & MEM_Int );
65625  pc = (int)pIn1->u.i;
65626  break;
65627}
65628
65629/* Opcode:  Yield P1 * * * *
65630**
65631** Swap the program counter with the value in register P1.
65632*/
65633case OP_Yield: {            /* in1 */
65634#if 0  /* local variables moved into u.aa */
65635  int pcDest;
65636#endif /* local variables moved into u.aa */
65637  pIn1 = &aMem[pOp->p1];
65638  assert( (pIn1->flags & MEM_Dyn)==0 );
65639  pIn1->flags = MEM_Int;
65640  u.aa.pcDest = (int)pIn1->u.i;
65641  pIn1->u.i = pc;
65642  REGISTER_TRACE(pOp->p1, pIn1);
65643  pc = u.aa.pcDest;
65644  break;
65645}
65646
65647/* Opcode:  HaltIfNull  P1 P2 P3 P4 *
65648**
65649** Check the value in register P3.  If it is NULL then Halt using
65650** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
65651** value in register P3 is not NULL, then this routine is a no-op.
65652*/
65653case OP_HaltIfNull: {      /* in3 */
65654  pIn3 = &aMem[pOp->p3];
65655  if( (pIn3->flags & MEM_Null)==0 ) break;
65656  /* Fall through into OP_Halt */
65657}
65658
65659/* Opcode:  Halt P1 P2 * P4 *
65660**
65661** Exit immediately.  All open cursors, etc are closed
65662** automatically.
65663**
65664** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
65665** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
65666** For errors, it can be some other value.  If P1!=0 then P2 will determine
65667** whether or not to rollback the current transaction.  Do not rollback
65668** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
65669** then back out all changes that have occurred during this execution of the
65670** VDBE, but do not rollback the transaction.
65671**
65672** If P4 is not null then it is an error message string.
65673**
65674** There is an implied "Halt 0 0 0" instruction inserted at the very end of
65675** every program.  So a jump past the last instruction of the program
65676** is the same as executing Halt.
65677*/
65678case OP_Halt: {
65679  if( pOp->p1==SQLITE_OK && p->pFrame ){
65680    /* Halt the sub-program. Return control to the parent frame. */
65681    VdbeFrame *pFrame = p->pFrame;
65682    p->pFrame = pFrame->pParent;
65683    p->nFrame--;
65684    sqlite3VdbeSetChanges(db, p->nChange);
65685    pc = sqlite3VdbeFrameRestore(pFrame);
65686    lastRowid = db->lastRowid;
65687    if( pOp->p2==OE_Ignore ){
65688      /* Instruction pc is the OP_Program that invoked the sub-program
65689      ** currently being halted. If the p2 instruction of this OP_Halt
65690      ** instruction is set to OE_Ignore, then the sub-program is throwing
65691      ** an IGNORE exception. In this case jump to the address specified
65692      ** as the p2 of the calling OP_Program.  */
65693      pc = p->aOp[pc].p2-1;
65694    }
65695    aOp = p->aOp;
65696    aMem = p->aMem;
65697    break;
65698  }
65699
65700  p->rc = pOp->p1;
65701  p->errorAction = (u8)pOp->p2;
65702  p->pc = pc;
65703  if( pOp->p4.z ){
65704    assert( p->rc!=SQLITE_OK );
65705    sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
65706    testcase( sqlite3GlobalConfig.xLog!=0 );
65707    sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
65708  }else if( p->rc ){
65709    testcase( sqlite3GlobalConfig.xLog!=0 );
65710    sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
65711  }
65712  rc = sqlite3VdbeHalt(p);
65713  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
65714  if( rc==SQLITE_BUSY ){
65715    p->rc = rc = SQLITE_BUSY;
65716  }else{
65717    assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
65718    assert( rc==SQLITE_OK || db->nDeferredCons>0 );
65719    rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
65720  }
65721  goto vdbe_return;
65722}
65723
65724/* Opcode: Integer P1 P2 * * *
65725**
65726** The 32-bit integer value P1 is written into register P2.
65727*/
65728case OP_Integer: {         /* out2-prerelease */
65729  pOut->u.i = pOp->p1;
65730  break;
65731}
65732
65733/* Opcode: Int64 * P2 * P4 *
65734**
65735** P4 is a pointer to a 64-bit integer value.
65736** Write that value into register P2.
65737*/
65738case OP_Int64: {           /* out2-prerelease */
65739  assert( pOp->p4.pI64!=0 );
65740  pOut->u.i = *pOp->p4.pI64;
65741  break;
65742}
65743
65744#ifndef SQLITE_OMIT_FLOATING_POINT
65745/* Opcode: Real * P2 * P4 *
65746**
65747** P4 is a pointer to a 64-bit floating point value.
65748** Write that value into register P2.
65749*/
65750case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
65751  pOut->flags = MEM_Real;
65752  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
65753  pOut->r = *pOp->p4.pReal;
65754  break;
65755}
65756#endif
65757
65758/* Opcode: String8 * P2 * P4 *
65759**
65760** P4 points to a nul terminated UTF-8 string. This opcode is transformed
65761** into an OP_String before it is executed for the first time.
65762*/
65763case OP_String8: {         /* same as TK_STRING, out2-prerelease */
65764  assert( pOp->p4.z!=0 );
65765  pOp->opcode = OP_String;
65766  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
65767
65768#ifndef SQLITE_OMIT_UTF16
65769  if( encoding!=SQLITE_UTF8 ){
65770    rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
65771    if( rc==SQLITE_TOOBIG ) goto too_big;
65772    if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
65773    assert( pOut->zMalloc==pOut->z );
65774    assert( pOut->flags & MEM_Dyn );
65775    pOut->zMalloc = 0;
65776    pOut->flags |= MEM_Static;
65777    pOut->flags &= ~MEM_Dyn;
65778    if( pOp->p4type==P4_DYNAMIC ){
65779      sqlite3DbFree(db, pOp->p4.z);
65780    }
65781    pOp->p4type = P4_DYNAMIC;
65782    pOp->p4.z = pOut->z;
65783    pOp->p1 = pOut->n;
65784  }
65785#endif
65786  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
65787    goto too_big;
65788  }
65789  /* Fall through to the next case, OP_String */
65790}
65791
65792/* Opcode: String P1 P2 * P4 *
65793**
65794** The string value P4 of length P1 (bytes) is stored in register P2.
65795*/
65796case OP_String: {          /* out2-prerelease */
65797  assert( pOp->p4.z!=0 );
65798  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
65799  pOut->z = pOp->p4.z;
65800  pOut->n = pOp->p1;
65801  pOut->enc = encoding;
65802  UPDATE_MAX_BLOBSIZE(pOut);
65803  break;
65804}
65805
65806/* Opcode: Null * P2 P3 * *
65807**
65808** Write a NULL into registers P2.  If P3 greater than P2, then also write
65809** NULL into register P3 and ever register in between P2 and P3.  If P3
65810** is less than P2 (typically P3 is zero) then only register P2 is
65811** set to NULL
65812*/
65813case OP_Null: {           /* out2-prerelease */
65814#if 0  /* local variables moved into u.ab */
65815  int cnt;
65816#endif /* local variables moved into u.ab */
65817  u.ab.cnt = pOp->p3-pOp->p2;
65818  assert( pOp->p3<=p->nMem );
65819  pOut->flags = MEM_Null;
65820  while( u.ab.cnt>0 ){
65821    pOut++;
65822    memAboutToChange(p, pOut);
65823    VdbeMemRelease(pOut);
65824    pOut->flags = MEM_Null;
65825    u.ab.cnt--;
65826  }
65827  break;
65828}
65829
65830
65831/* Opcode: Blob P1 P2 * P4
65832**
65833** P4 points to a blob of data P1 bytes long.  Store this
65834** blob in register P2.
65835*/
65836case OP_Blob: {                /* out2-prerelease */
65837  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
65838  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
65839  pOut->enc = encoding;
65840  UPDATE_MAX_BLOBSIZE(pOut);
65841  break;
65842}
65843
65844/* Opcode: Variable P1 P2 * P4 *
65845**
65846** Transfer the values of bound parameter P1 into register P2
65847**
65848** If the parameter is named, then its name appears in P4 and P3==1.
65849** The P4 value is used by sqlite3_bind_parameter_name().
65850*/
65851case OP_Variable: {            /* out2-prerelease */
65852#if 0  /* local variables moved into u.ac */
65853  Mem *pVar;       /* Value being transferred */
65854#endif /* local variables moved into u.ac */
65855
65856  assert( pOp->p1>0 && pOp->p1<=p->nVar );
65857  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
65858  u.ac.pVar = &p->aVar[pOp->p1 - 1];
65859  if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
65860    goto too_big;
65861  }
65862  sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
65863  UPDATE_MAX_BLOBSIZE(pOut);
65864  break;
65865}
65866
65867/* Opcode: Move P1 P2 P3 * *
65868**
65869** Move the values in register P1..P1+P3-1 over into
65870** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
65871** left holding a NULL.  It is an error for register ranges
65872** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
65873*/
65874case OP_Move: {
65875#if 0  /* local variables moved into u.ad */
65876  char *zMalloc;   /* Holding variable for allocated memory */
65877  int n;           /* Number of registers left to copy */
65878  int p1;          /* Register to copy from */
65879  int p2;          /* Register to copy to */
65880#endif /* local variables moved into u.ad */
65881
65882  u.ad.n = pOp->p3;
65883  u.ad.p1 = pOp->p1;
65884  u.ad.p2 = pOp->p2;
65885  assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
65886  assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
65887
65888  pIn1 = &aMem[u.ad.p1];
65889  pOut = &aMem[u.ad.p2];
65890  while( u.ad.n-- ){
65891    assert( pOut<=&aMem[p->nMem] );
65892    assert( pIn1<=&aMem[p->nMem] );
65893    assert( memIsValid(pIn1) );
65894    memAboutToChange(p, pOut);
65895    u.ad.zMalloc = pOut->zMalloc;
65896    pOut->zMalloc = 0;
65897    sqlite3VdbeMemMove(pOut, pIn1);
65898#ifdef SQLITE_DEBUG
65899    if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
65900      pOut->pScopyFrom += u.ad.p1 - pOp->p2;
65901    }
65902#endif
65903    pIn1->zMalloc = u.ad.zMalloc;
65904    REGISTER_TRACE(u.ad.p2++, pOut);
65905    pIn1++;
65906    pOut++;
65907  }
65908  break;
65909}
65910
65911/* Opcode: Copy P1 P2 * * *
65912**
65913** Make a copy of register P1 into register P2.
65914**
65915** This instruction makes a deep copy of the value.  A duplicate
65916** is made of any string or blob constant.  See also OP_SCopy.
65917*/
65918case OP_Copy: {             /* in1, out2 */
65919  pIn1 = &aMem[pOp->p1];
65920  pOut = &aMem[pOp->p2];
65921  assert( pOut!=pIn1 );
65922  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65923  Deephemeralize(pOut);
65924  REGISTER_TRACE(pOp->p2, pOut);
65925  break;
65926}
65927
65928/* Opcode: SCopy P1 P2 * * *
65929**
65930** Make a shallow copy of register P1 into register P2.
65931**
65932** This instruction makes a shallow copy of the value.  If the value
65933** is a string or blob, then the copy is only a pointer to the
65934** original and hence if the original changes so will the copy.
65935** Worse, if the original is deallocated, the copy becomes invalid.
65936** Thus the program must guarantee that the original will not change
65937** during the lifetime of the copy.  Use OP_Copy to make a complete
65938** copy.
65939*/
65940case OP_SCopy: {            /* in1, out2 */
65941  pIn1 = &aMem[pOp->p1];
65942  pOut = &aMem[pOp->p2];
65943  assert( pOut!=pIn1 );
65944  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
65945#ifdef SQLITE_DEBUG
65946  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
65947#endif
65948  REGISTER_TRACE(pOp->p2, pOut);
65949  break;
65950}
65951
65952/* Opcode: ResultRow P1 P2 * * *
65953**
65954** The registers P1 through P1+P2-1 contain a single row of
65955** results. This opcode causes the sqlite3_step() call to terminate
65956** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
65957** structure to provide access to the top P1 values as the result
65958** row.
65959*/
65960case OP_ResultRow: {
65961#if 0  /* local variables moved into u.ae */
65962  Mem *pMem;
65963  int i;
65964#endif /* local variables moved into u.ae */
65965  assert( p->nResColumn==pOp->p2 );
65966  assert( pOp->p1>0 );
65967  assert( pOp->p1+pOp->p2<=p->nMem+1 );
65968
65969  /* If this statement has violated immediate foreign key constraints, do
65970  ** not return the number of rows modified. And do not RELEASE the statement
65971  ** transaction. It needs to be rolled back.  */
65972  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
65973    assert( db->flags&SQLITE_CountRows );
65974    assert( p->usesStmtJournal );
65975    break;
65976  }
65977
65978  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
65979  ** DML statements invoke this opcode to return the number of rows
65980  ** modified to the user. This is the only way that a VM that
65981  ** opens a statement transaction may invoke this opcode.
65982  **
65983  ** In case this is such a statement, close any statement transaction
65984  ** opened by this VM before returning control to the user. This is to
65985  ** ensure that statement-transactions are always nested, not overlapping.
65986  ** If the open statement-transaction is not closed here, then the user
65987  ** may step another VM that opens its own statement transaction. This
65988  ** may lead to overlapping statement transactions.
65989  **
65990  ** The statement transaction is never a top-level transaction.  Hence
65991  ** the RELEASE call below can never fail.
65992  */
65993  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
65994  rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
65995  if( NEVER(rc!=SQLITE_OK) ){
65996    break;
65997  }
65998
65999  /* Invalidate all ephemeral cursor row caches */
66000  p->cacheCtr = (p->cacheCtr + 2)|1;
66001
66002  /* Make sure the results of the current row are \000 terminated
66003  ** and have an assigned type.  The results are de-ephemeralized as
66004  ** a side effect.
66005  */
66006  u.ae.pMem = p->pResultSet = &aMem[pOp->p1];
66007  for(u.ae.i=0; u.ae.i<pOp->p2; u.ae.i++){
66008    assert( memIsValid(&u.ae.pMem[u.ae.i]) );
66009    Deephemeralize(&u.ae.pMem[u.ae.i]);
66010    assert( (u.ae.pMem[u.ae.i].flags & MEM_Ephem)==0
66011            || (u.ae.pMem[u.ae.i].flags & (MEM_Str|MEM_Blob))==0 );
66012    sqlite3VdbeMemNulTerminate(&u.ae.pMem[u.ae.i]);
66013    sqlite3VdbeMemStoreType(&u.ae.pMem[u.ae.i]);
66014    REGISTER_TRACE(pOp->p1+u.ae.i, &u.ae.pMem[u.ae.i]);
66015  }
66016  if( db->mallocFailed ) goto no_mem;
66017
66018  /* Return SQLITE_ROW
66019  */
66020  p->pc = pc + 1;
66021  rc = SQLITE_ROW;
66022  goto vdbe_return;
66023}
66024
66025/* Opcode: Concat P1 P2 P3 * *
66026**
66027** Add the text in register P1 onto the end of the text in
66028** register P2 and store the result in register P3.
66029** If either the P1 or P2 text are NULL then store NULL in P3.
66030**
66031**   P3 = P2 || P1
66032**
66033** It is illegal for P1 and P3 to be the same register. Sometimes,
66034** if P3 is the same register as P2, the implementation is able
66035** to avoid a memcpy().
66036*/
66037case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
66038#if 0  /* local variables moved into u.af */
66039  i64 nByte;
66040#endif /* local variables moved into u.af */
66041
66042  pIn1 = &aMem[pOp->p1];
66043  pIn2 = &aMem[pOp->p2];
66044  pOut = &aMem[pOp->p3];
66045  assert( pIn1!=pOut );
66046  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66047    sqlite3VdbeMemSetNull(pOut);
66048    break;
66049  }
66050  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
66051  Stringify(pIn1, encoding);
66052  Stringify(pIn2, encoding);
66053  u.af.nByte = pIn1->n + pIn2->n;
66054  if( u.af.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66055    goto too_big;
66056  }
66057  MemSetTypeFlag(pOut, MEM_Str);
66058  if( sqlite3VdbeMemGrow(pOut, (int)u.af.nByte+2, pOut==pIn2) ){
66059    goto no_mem;
66060  }
66061  if( pOut!=pIn2 ){
66062    memcpy(pOut->z, pIn2->z, pIn2->n);
66063  }
66064  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
66065  pOut->z[u.af.nByte] = 0;
66066  pOut->z[u.af.nByte+1] = 0;
66067  pOut->flags |= MEM_Term;
66068  pOut->n = (int)u.af.nByte;
66069  pOut->enc = encoding;
66070  UPDATE_MAX_BLOBSIZE(pOut);
66071  break;
66072}
66073
66074/* Opcode: Add P1 P2 P3 * *
66075**
66076** Add the value in register P1 to the value in register P2
66077** and store the result in register P3.
66078** If either input is NULL, the result is NULL.
66079*/
66080/* Opcode: Multiply P1 P2 P3 * *
66081**
66082**
66083** Multiply the value in register P1 by the value in register P2
66084** and store the result in register P3.
66085** If either input is NULL, the result is NULL.
66086*/
66087/* Opcode: Subtract P1 P2 P3 * *
66088**
66089** Subtract the value in register P1 from the value in register P2
66090** and store the result in register P3.
66091** If either input is NULL, the result is NULL.
66092*/
66093/* Opcode: Divide P1 P2 P3 * *
66094**
66095** Divide the value in register P1 by the value in register P2
66096** and store the result in register P3 (P3=P2/P1). If the value in
66097** register P1 is zero, then the result is NULL. If either input is
66098** NULL, the result is NULL.
66099*/
66100/* Opcode: Remainder P1 P2 P3 * *
66101**
66102** Compute the remainder after integer division of the value in
66103** register P1 by the value in register P2 and store the result in P3.
66104** If the value in register P2 is zero the result is NULL.
66105** If either operand is NULL, the result is NULL.
66106*/
66107case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
66108case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
66109case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
66110case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
66111case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
66112#if 0  /* local variables moved into u.ag */
66113  int flags;      /* Combined MEM_* flags from both inputs */
66114  i64 iA;         /* Integer value of left operand */
66115  i64 iB;         /* Integer value of right operand */
66116  double rA;      /* Real value of left operand */
66117  double rB;      /* Real value of right operand */
66118#endif /* local variables moved into u.ag */
66119
66120  pIn1 = &aMem[pOp->p1];
66121  applyNumericAffinity(pIn1);
66122  pIn2 = &aMem[pOp->p2];
66123  applyNumericAffinity(pIn2);
66124  pOut = &aMem[pOp->p3];
66125  u.ag.flags = pIn1->flags | pIn2->flags;
66126  if( (u.ag.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
66127  if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
66128    u.ag.iA = pIn1->u.i;
66129    u.ag.iB = pIn2->u.i;
66130    switch( pOp->opcode ){
66131      case OP_Add:       if( sqlite3AddInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
66132      case OP_Subtract:  if( sqlite3SubInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
66133      case OP_Multiply:  if( sqlite3MulInt64(&u.ag.iB,u.ag.iA) ) goto fp_math;  break;
66134      case OP_Divide: {
66135        if( u.ag.iA==0 ) goto arithmetic_result_is_null;
66136        if( u.ag.iA==-1 && u.ag.iB==SMALLEST_INT64 ) goto fp_math;
66137        u.ag.iB /= u.ag.iA;
66138        break;
66139      }
66140      default: {
66141        if( u.ag.iA==0 ) goto arithmetic_result_is_null;
66142        if( u.ag.iA==-1 ) u.ag.iA = 1;
66143        u.ag.iB %= u.ag.iA;
66144        break;
66145      }
66146    }
66147    pOut->u.i = u.ag.iB;
66148    MemSetTypeFlag(pOut, MEM_Int);
66149  }else{
66150fp_math:
66151    u.ag.rA = sqlite3VdbeRealValue(pIn1);
66152    u.ag.rB = sqlite3VdbeRealValue(pIn2);
66153    switch( pOp->opcode ){
66154      case OP_Add:         u.ag.rB += u.ag.rA;       break;
66155      case OP_Subtract:    u.ag.rB -= u.ag.rA;       break;
66156      case OP_Multiply:    u.ag.rB *= u.ag.rA;       break;
66157      case OP_Divide: {
66158        /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
66159        if( u.ag.rA==(double)0 ) goto arithmetic_result_is_null;
66160        u.ag.rB /= u.ag.rA;
66161        break;
66162      }
66163      default: {
66164        u.ag.iA = (i64)u.ag.rA;
66165        u.ag.iB = (i64)u.ag.rB;
66166        if( u.ag.iA==0 ) goto arithmetic_result_is_null;
66167        if( u.ag.iA==-1 ) u.ag.iA = 1;
66168        u.ag.rB = (double)(u.ag.iB % u.ag.iA);
66169        break;
66170      }
66171    }
66172#ifdef SQLITE_OMIT_FLOATING_POINT
66173    pOut->u.i = u.ag.rB;
66174    MemSetTypeFlag(pOut, MEM_Int);
66175#else
66176    if( sqlite3IsNaN(u.ag.rB) ){
66177      goto arithmetic_result_is_null;
66178    }
66179    pOut->r = u.ag.rB;
66180    MemSetTypeFlag(pOut, MEM_Real);
66181    if( (u.ag.flags & MEM_Real)==0 ){
66182      sqlite3VdbeIntegerAffinity(pOut);
66183    }
66184#endif
66185  }
66186  break;
66187
66188arithmetic_result_is_null:
66189  sqlite3VdbeMemSetNull(pOut);
66190  break;
66191}
66192
66193/* Opcode: CollSeq P1 * * P4
66194**
66195** P4 is a pointer to a CollSeq struct. If the next call to a user function
66196** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
66197** be returned. This is used by the built-in min(), max() and nullif()
66198** functions.
66199**
66200** If P1 is not zero, then it is a register that a subsequent min() or
66201** max() aggregate will set to 1 if the current row is not the minimum or
66202** maximum.  The P1 register is initialized to 0 by this instruction.
66203**
66204** The interface used by the implementation of the aforementioned functions
66205** to retrieve the collation sequence set by this opcode is not available
66206** publicly, only to user functions defined in func.c.
66207*/
66208case OP_CollSeq: {
66209  assert( pOp->p4type==P4_COLLSEQ );
66210  if( pOp->p1 ){
66211    sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
66212  }
66213  break;
66214}
66215
66216/* Opcode: Function P1 P2 P3 P4 P5
66217**
66218** Invoke a user function (P4 is a pointer to a Function structure that
66219** defines the function) with P5 arguments taken from register P2 and
66220** successors.  The result of the function is stored in register P3.
66221** Register P3 must not be one of the function inputs.
66222**
66223** P1 is a 32-bit bitmask indicating whether or not each argument to the
66224** function was determined to be constant at compile time. If the first
66225** argument was constant then bit 0 of P1 is set. This is used to determine
66226** whether meta data associated with a user function argument using the
66227** sqlite3_set_auxdata() API may be safely retained until the next
66228** invocation of this opcode.
66229**
66230** See also: AggStep and AggFinal
66231*/
66232case OP_Function: {
66233#if 0  /* local variables moved into u.ah */
66234  int i;
66235  Mem *pArg;
66236  sqlite3_context ctx;
66237  sqlite3_value **apVal;
66238  int n;
66239#endif /* local variables moved into u.ah */
66240
66241  u.ah.n = pOp->p5;
66242  u.ah.apVal = p->apArg;
66243  assert( u.ah.apVal || u.ah.n==0 );
66244  assert( pOp->p3>0 && pOp->p3<=p->nMem );
66245  pOut = &aMem[pOp->p3];
66246  memAboutToChange(p, pOut);
66247
66248  assert( u.ah.n==0 || (pOp->p2>0 && pOp->p2+u.ah.n<=p->nMem+1) );
66249  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ah.n );
66250  u.ah.pArg = &aMem[pOp->p2];
66251  for(u.ah.i=0; u.ah.i<u.ah.n; u.ah.i++, u.ah.pArg++){
66252    assert( memIsValid(u.ah.pArg) );
66253    u.ah.apVal[u.ah.i] = u.ah.pArg;
66254    Deephemeralize(u.ah.pArg);
66255    sqlite3VdbeMemStoreType(u.ah.pArg);
66256    REGISTER_TRACE(pOp->p2+u.ah.i, u.ah.pArg);
66257  }
66258
66259  assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
66260  if( pOp->p4type==P4_FUNCDEF ){
66261    u.ah.ctx.pFunc = pOp->p4.pFunc;
66262    u.ah.ctx.pVdbeFunc = 0;
66263  }else{
66264    u.ah.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
66265    u.ah.ctx.pFunc = u.ah.ctx.pVdbeFunc->pFunc;
66266  }
66267
66268  u.ah.ctx.s.flags = MEM_Null;
66269  u.ah.ctx.s.db = db;
66270  u.ah.ctx.s.xDel = 0;
66271  u.ah.ctx.s.zMalloc = 0;
66272
66273  /* The output cell may already have a buffer allocated. Move
66274  ** the pointer to u.ah.ctx.s so in case the user-function can use
66275  ** the already allocated buffer instead of allocating a new one.
66276  */
66277  sqlite3VdbeMemMove(&u.ah.ctx.s, pOut);
66278  MemSetTypeFlag(&u.ah.ctx.s, MEM_Null);
66279
66280  u.ah.ctx.isError = 0;
66281  if( u.ah.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
66282    assert( pOp>aOp );
66283    assert( pOp[-1].p4type==P4_COLLSEQ );
66284    assert( pOp[-1].opcode==OP_CollSeq );
66285    u.ah.ctx.pColl = pOp[-1].p4.pColl;
66286  }
66287  db->lastRowid = lastRowid;
66288  (*u.ah.ctx.pFunc->xFunc)(&u.ah.ctx, u.ah.n, u.ah.apVal); /* IMP: R-24505-23230 */
66289  lastRowid = db->lastRowid;
66290
66291  /* If any auxiliary data functions have been called by this user function,
66292  ** immediately call the destructor for any non-static values.
66293  */
66294  if( u.ah.ctx.pVdbeFunc ){
66295    sqlite3VdbeDeleteAuxData(u.ah.ctx.pVdbeFunc, pOp->p1);
66296    pOp->p4.pVdbeFunc = u.ah.ctx.pVdbeFunc;
66297    pOp->p4type = P4_VDBEFUNC;
66298  }
66299
66300  if( db->mallocFailed ){
66301    /* Even though a malloc() has failed, the implementation of the
66302    ** user function may have called an sqlite3_result_XXX() function
66303    ** to return a value. The following call releases any resources
66304    ** associated with such a value.
66305    */
66306    sqlite3VdbeMemRelease(&u.ah.ctx.s);
66307    goto no_mem;
66308  }
66309
66310  /* If the function returned an error, throw an exception */
66311  if( u.ah.ctx.isError ){
66312    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ah.ctx.s));
66313    rc = u.ah.ctx.isError;
66314  }
66315
66316  /* Copy the result of the function into register P3 */
66317  sqlite3VdbeChangeEncoding(&u.ah.ctx.s, encoding);
66318  sqlite3VdbeMemMove(pOut, &u.ah.ctx.s);
66319  if( sqlite3VdbeMemTooBig(pOut) ){
66320    goto too_big;
66321  }
66322
66323#if 0
66324  /* The app-defined function has done something that as caused this
66325  ** statement to expire.  (Perhaps the function called sqlite3_exec()
66326  ** with a CREATE TABLE statement.)
66327  */
66328  if( p->expired ) rc = SQLITE_ABORT;
66329#endif
66330
66331  REGISTER_TRACE(pOp->p3, pOut);
66332  UPDATE_MAX_BLOBSIZE(pOut);
66333  break;
66334}
66335
66336/* Opcode: BitAnd P1 P2 P3 * *
66337**
66338** Take the bit-wise AND of the values in register P1 and P2 and
66339** store the result in register P3.
66340** If either input is NULL, the result is NULL.
66341*/
66342/* Opcode: BitOr P1 P2 P3 * *
66343**
66344** Take the bit-wise OR of the values in register P1 and P2 and
66345** store the result in register P3.
66346** If either input is NULL, the result is NULL.
66347*/
66348/* Opcode: ShiftLeft P1 P2 P3 * *
66349**
66350** Shift the integer value in register P2 to the left by the
66351** number of bits specified by the integer in register P1.
66352** Store the result in register P3.
66353** If either input is NULL, the result is NULL.
66354*/
66355/* Opcode: ShiftRight P1 P2 P3 * *
66356**
66357** Shift the integer value in register P2 to the right by the
66358** number of bits specified by the integer in register P1.
66359** Store the result in register P3.
66360** If either input is NULL, the result is NULL.
66361*/
66362case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
66363case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
66364case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
66365case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
66366#if 0  /* local variables moved into u.ai */
66367  i64 iA;
66368  u64 uA;
66369  i64 iB;
66370  u8 op;
66371#endif /* local variables moved into u.ai */
66372
66373  pIn1 = &aMem[pOp->p1];
66374  pIn2 = &aMem[pOp->p2];
66375  pOut = &aMem[pOp->p3];
66376  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66377    sqlite3VdbeMemSetNull(pOut);
66378    break;
66379  }
66380  u.ai.iA = sqlite3VdbeIntValue(pIn2);
66381  u.ai.iB = sqlite3VdbeIntValue(pIn1);
66382  u.ai.op = pOp->opcode;
66383  if( u.ai.op==OP_BitAnd ){
66384    u.ai.iA &= u.ai.iB;
66385  }else if( u.ai.op==OP_BitOr ){
66386    u.ai.iA |= u.ai.iB;
66387  }else if( u.ai.iB!=0 ){
66388    assert( u.ai.op==OP_ShiftRight || u.ai.op==OP_ShiftLeft );
66389
66390    /* If shifting by a negative amount, shift in the other direction */
66391    if( u.ai.iB<0 ){
66392      assert( OP_ShiftRight==OP_ShiftLeft+1 );
66393      u.ai.op = 2*OP_ShiftLeft + 1 - u.ai.op;
66394      u.ai.iB = u.ai.iB>(-64) ? -u.ai.iB : 64;
66395    }
66396
66397    if( u.ai.iB>=64 ){
66398      u.ai.iA = (u.ai.iA>=0 || u.ai.op==OP_ShiftLeft) ? 0 : -1;
66399    }else{
66400      memcpy(&u.ai.uA, &u.ai.iA, sizeof(u.ai.uA));
66401      if( u.ai.op==OP_ShiftLeft ){
66402        u.ai.uA <<= u.ai.iB;
66403      }else{
66404        u.ai.uA >>= u.ai.iB;
66405        /* Sign-extend on a right shift of a negative number */
66406        if( u.ai.iA<0 ) u.ai.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.ai.iB);
66407      }
66408      memcpy(&u.ai.iA, &u.ai.uA, sizeof(u.ai.iA));
66409    }
66410  }
66411  pOut->u.i = u.ai.iA;
66412  MemSetTypeFlag(pOut, MEM_Int);
66413  break;
66414}
66415
66416/* Opcode: AddImm  P1 P2 * * *
66417**
66418** Add the constant P2 to the value in register P1.
66419** The result is always an integer.
66420**
66421** To force any register to be an integer, just add 0.
66422*/
66423case OP_AddImm: {            /* in1 */
66424  pIn1 = &aMem[pOp->p1];
66425  memAboutToChange(p, pIn1);
66426  sqlite3VdbeMemIntegerify(pIn1);
66427  pIn1->u.i += pOp->p2;
66428  break;
66429}
66430
66431/* Opcode: MustBeInt P1 P2 * * *
66432**
66433** Force the value in register P1 to be an integer.  If the value
66434** in P1 is not an integer and cannot be converted into an integer
66435** without data loss, then jump immediately to P2, or if P2==0
66436** raise an SQLITE_MISMATCH exception.
66437*/
66438case OP_MustBeInt: {            /* jump, in1 */
66439  pIn1 = &aMem[pOp->p1];
66440  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
66441  if( (pIn1->flags & MEM_Int)==0 ){
66442    if( pOp->p2==0 ){
66443      rc = SQLITE_MISMATCH;
66444      goto abort_due_to_error;
66445    }else{
66446      pc = pOp->p2 - 1;
66447    }
66448  }else{
66449    MemSetTypeFlag(pIn1, MEM_Int);
66450  }
66451  break;
66452}
66453
66454#ifndef SQLITE_OMIT_FLOATING_POINT
66455/* Opcode: RealAffinity P1 * * * *
66456**
66457** If register P1 holds an integer convert it to a real value.
66458**
66459** This opcode is used when extracting information from a column that
66460** has REAL affinity.  Such column values may still be stored as
66461** integers, for space efficiency, but after extraction we want them
66462** to have only a real value.
66463*/
66464case OP_RealAffinity: {                  /* in1 */
66465  pIn1 = &aMem[pOp->p1];
66466  if( pIn1->flags & MEM_Int ){
66467    sqlite3VdbeMemRealify(pIn1);
66468  }
66469  break;
66470}
66471#endif
66472
66473#ifndef SQLITE_OMIT_CAST
66474/* Opcode: ToText P1 * * * *
66475**
66476** Force the value in register P1 to be text.
66477** If the value is numeric, convert it to a string using the
66478** equivalent of printf().  Blob values are unchanged and
66479** are afterwards simply interpreted as text.
66480**
66481** A NULL value is not changed by this routine.  It remains NULL.
66482*/
66483case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
66484  pIn1 = &aMem[pOp->p1];
66485  memAboutToChange(p, pIn1);
66486  if( pIn1->flags & MEM_Null ) break;
66487  assert( MEM_Str==(MEM_Blob>>3) );
66488  pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
66489  applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
66490  rc = ExpandBlob(pIn1);
66491  assert( pIn1->flags & MEM_Str || db->mallocFailed );
66492  pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
66493  UPDATE_MAX_BLOBSIZE(pIn1);
66494  break;
66495}
66496
66497/* Opcode: ToBlob P1 * * * *
66498**
66499** Force the value in register P1 to be a BLOB.
66500** If the value is numeric, convert it to a string first.
66501** Strings are simply reinterpreted as blobs with no change
66502** to the underlying data.
66503**
66504** A NULL value is not changed by this routine.  It remains NULL.
66505*/
66506case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
66507  pIn1 = &aMem[pOp->p1];
66508  if( pIn1->flags & MEM_Null ) break;
66509  if( (pIn1->flags & MEM_Blob)==0 ){
66510    applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
66511    assert( pIn1->flags & MEM_Str || db->mallocFailed );
66512    MemSetTypeFlag(pIn1, MEM_Blob);
66513  }else{
66514    pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
66515  }
66516  UPDATE_MAX_BLOBSIZE(pIn1);
66517  break;
66518}
66519
66520/* Opcode: ToNumeric P1 * * * *
66521**
66522** Force the value in register P1 to be numeric (either an
66523** integer or a floating-point number.)
66524** If the value is text or blob, try to convert it to an using the
66525** equivalent of atoi() or atof() and store 0 if no such conversion
66526** is possible.
66527**
66528** A NULL value is not changed by this routine.  It remains NULL.
66529*/
66530case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
66531  pIn1 = &aMem[pOp->p1];
66532  sqlite3VdbeMemNumerify(pIn1);
66533  break;
66534}
66535#endif /* SQLITE_OMIT_CAST */
66536
66537/* Opcode: ToInt P1 * * * *
66538**
66539** Force the value in register P1 to be an integer.  If
66540** The value is currently a real number, drop its fractional part.
66541** If the value is text or blob, try to convert it to an integer using the
66542** equivalent of atoi() and store 0 if no such conversion is possible.
66543**
66544** A NULL value is not changed by this routine.  It remains NULL.
66545*/
66546case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
66547  pIn1 = &aMem[pOp->p1];
66548  if( (pIn1->flags & MEM_Null)==0 ){
66549    sqlite3VdbeMemIntegerify(pIn1);
66550  }
66551  break;
66552}
66553
66554#if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
66555/* Opcode: ToReal P1 * * * *
66556**
66557** Force the value in register P1 to be a floating point number.
66558** If The value is currently an integer, convert it.
66559** If the value is text or blob, try to convert it to an integer using the
66560** equivalent of atoi() and store 0.0 if no such conversion is possible.
66561**
66562** A NULL value is not changed by this routine.  It remains NULL.
66563*/
66564case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
66565  pIn1 = &aMem[pOp->p1];
66566  memAboutToChange(p, pIn1);
66567  if( (pIn1->flags & MEM_Null)==0 ){
66568    sqlite3VdbeMemRealify(pIn1);
66569  }
66570  break;
66571}
66572#endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
66573
66574/* Opcode: Lt P1 P2 P3 P4 P5
66575**
66576** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
66577** jump to address P2.
66578**
66579** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
66580** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL
66581** bit is clear then fall through if either operand is NULL.
66582**
66583** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
66584** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
66585** to coerce both inputs according to this affinity before the
66586** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
66587** affinity is used. Note that the affinity conversions are stored
66588** back into the input registers P1 and P3.  So this opcode can cause
66589** persistent changes to registers P1 and P3.
66590**
66591** Once any conversions have taken place, and neither value is NULL,
66592** the values are compared. If both values are blobs then memcmp() is
66593** used to determine the results of the comparison.  If both values
66594** are text, then the appropriate collating function specified in
66595** P4 is  used to do the comparison.  If P4 is not specified then
66596** memcmp() is used to compare text string.  If both values are
66597** numeric, then a numeric comparison is used. If the two values
66598** are of different types, then numbers are considered less than
66599** strings and strings are considered less than blobs.
66600**
66601** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
66602** store a boolean result (either 0, or 1, or NULL) in register P2.
66603*/
66604/* Opcode: Ne P1 P2 P3 P4 P5
66605**
66606** This works just like the Lt opcode except that the jump is taken if
66607** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
66608** additional information.
66609**
66610** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
66611** true or false and is never NULL.  If both operands are NULL then the result
66612** of comparison is false.  If either operand is NULL then the result is true.
66613** If neither operand is NULL the result is the same as it would be if
66614** the SQLITE_NULLEQ flag were omitted from P5.
66615*/
66616/* Opcode: Eq P1 P2 P3 P4 P5
66617**
66618** This works just like the Lt opcode except that the jump is taken if
66619** the operands in registers P1 and P3 are equal.
66620** See the Lt opcode for additional information.
66621**
66622** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
66623** true or false and is never NULL.  If both operands are NULL then the result
66624** of comparison is true.  If either operand is NULL then the result is false.
66625** If neither operand is NULL the result is the same as it would be if
66626** the SQLITE_NULLEQ flag were omitted from P5.
66627*/
66628/* Opcode: Le P1 P2 P3 P4 P5
66629**
66630** This works just like the Lt opcode except that the jump is taken if
66631** the content of register P3 is less than or equal to the content of
66632** register P1.  See the Lt opcode for additional information.
66633*/
66634/* Opcode: Gt P1 P2 P3 P4 P5
66635**
66636** This works just like the Lt opcode except that the jump is taken if
66637** the content of register P3 is greater than the content of
66638** register P1.  See the Lt opcode for additional information.
66639*/
66640/* Opcode: Ge P1 P2 P3 P4 P5
66641**
66642** This works just like the Lt opcode except that the jump is taken if
66643** the content of register P3 is greater than or equal to the content of
66644** register P1.  See the Lt opcode for additional information.
66645*/
66646case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
66647case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
66648case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
66649case OP_Le:               /* same as TK_LE, jump, in1, in3 */
66650case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
66651case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
66652#if 0  /* local variables moved into u.aj */
66653  int res;            /* Result of the comparison of pIn1 against pIn3 */
66654  char affinity;      /* Affinity to use for comparison */
66655  u16 flags1;         /* Copy of initial value of pIn1->flags */
66656  u16 flags3;         /* Copy of initial value of pIn3->flags */
66657#endif /* local variables moved into u.aj */
66658
66659  pIn1 = &aMem[pOp->p1];
66660  pIn3 = &aMem[pOp->p3];
66661  u.aj.flags1 = pIn1->flags;
66662  u.aj.flags3 = pIn3->flags;
66663  if( (u.aj.flags1 | u.aj.flags3)&MEM_Null ){
66664    /* One or both operands are NULL */
66665    if( pOp->p5 & SQLITE_NULLEQ ){
66666      /* If SQLITE_NULLEQ is set (which will only happen if the operator is
66667      ** OP_Eq or OP_Ne) then take the jump or not depending on whether
66668      ** or not both operands are null.
66669      */
66670      assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
66671      u.aj.res = (u.aj.flags1 & u.aj.flags3 & MEM_Null)==0;
66672    }else{
66673      /* SQLITE_NULLEQ is clear and at least one operand is NULL,
66674      ** then the result is always NULL.
66675      ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
66676      */
66677      if( pOp->p5 & SQLITE_STOREP2 ){
66678        pOut = &aMem[pOp->p2];
66679        MemSetTypeFlag(pOut, MEM_Null);
66680        REGISTER_TRACE(pOp->p2, pOut);
66681      }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
66682        pc = pOp->p2-1;
66683      }
66684      break;
66685    }
66686  }else{
66687    /* Neither operand is NULL.  Do a comparison. */
66688    u.aj.affinity = pOp->p5 & SQLITE_AFF_MASK;
66689    if( u.aj.affinity ){
66690      applyAffinity(pIn1, u.aj.affinity, encoding);
66691      applyAffinity(pIn3, u.aj.affinity, encoding);
66692      if( db->mallocFailed ) goto no_mem;
66693    }
66694
66695    assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
66696    ExpandBlob(pIn1);
66697    ExpandBlob(pIn3);
66698    u.aj.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
66699  }
66700  switch( pOp->opcode ){
66701    case OP_Eq:    u.aj.res = u.aj.res==0;     break;
66702    case OP_Ne:    u.aj.res = u.aj.res!=0;     break;
66703    case OP_Lt:    u.aj.res = u.aj.res<0;      break;
66704    case OP_Le:    u.aj.res = u.aj.res<=0;     break;
66705    case OP_Gt:    u.aj.res = u.aj.res>0;      break;
66706    default:       u.aj.res = u.aj.res>=0;     break;
66707  }
66708
66709  if( pOp->p5 & SQLITE_STOREP2 ){
66710    pOut = &aMem[pOp->p2];
66711    memAboutToChange(p, pOut);
66712    MemSetTypeFlag(pOut, MEM_Int);
66713    pOut->u.i = u.aj.res;
66714    REGISTER_TRACE(pOp->p2, pOut);
66715  }else if( u.aj.res ){
66716    pc = pOp->p2-1;
66717  }
66718
66719  /* Undo any changes made by applyAffinity() to the input registers. */
66720  pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.aj.flags1&MEM_TypeMask);
66721  pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.aj.flags3&MEM_TypeMask);
66722  break;
66723}
66724
66725/* Opcode: Permutation * * * P4 *
66726**
66727** Set the permutation used by the OP_Compare operator to be the array
66728** of integers in P4.
66729**
66730** The permutation is only valid until the next OP_Permutation, OP_Compare,
66731** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
66732** immediately prior to the OP_Compare.
66733*/
66734case OP_Permutation: {
66735  assert( pOp->p4type==P4_INTARRAY );
66736  assert( pOp->p4.ai );
66737  aPermute = pOp->p4.ai;
66738  break;
66739}
66740
66741/* Opcode: Compare P1 P2 P3 P4 *
66742**
66743** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
66744** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
66745** the comparison for use by the next OP_Jump instruct.
66746**
66747** P4 is a KeyInfo structure that defines collating sequences and sort
66748** orders for the comparison.  The permutation applies to registers
66749** only.  The KeyInfo elements are used sequentially.
66750**
66751** The comparison is a sort comparison, so NULLs compare equal,
66752** NULLs are less than numbers, numbers are less than strings,
66753** and strings are less than blobs.
66754*/
66755case OP_Compare: {
66756#if 0  /* local variables moved into u.ak */
66757  int n;
66758  int i;
66759  int p1;
66760  int p2;
66761  const KeyInfo *pKeyInfo;
66762  int idx;
66763  CollSeq *pColl;    /* Collating sequence to use on this term */
66764  int bRev;          /* True for DESCENDING sort order */
66765#endif /* local variables moved into u.ak */
66766
66767  u.ak.n = pOp->p3;
66768  u.ak.pKeyInfo = pOp->p4.pKeyInfo;
66769  assert( u.ak.n>0 );
66770  assert( u.ak.pKeyInfo!=0 );
66771  u.ak.p1 = pOp->p1;
66772  u.ak.p2 = pOp->p2;
66773#if SQLITE_DEBUG
66774  if( aPermute ){
66775    int k, mx = 0;
66776    for(k=0; k<u.ak.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
66777    assert( u.ak.p1>0 && u.ak.p1+mx<=p->nMem+1 );
66778    assert( u.ak.p2>0 && u.ak.p2+mx<=p->nMem+1 );
66779  }else{
66780    assert( u.ak.p1>0 && u.ak.p1+u.ak.n<=p->nMem+1 );
66781    assert( u.ak.p2>0 && u.ak.p2+u.ak.n<=p->nMem+1 );
66782  }
66783#endif /* SQLITE_DEBUG */
66784  for(u.ak.i=0; u.ak.i<u.ak.n; u.ak.i++){
66785    u.ak.idx = aPermute ? aPermute[u.ak.i] : u.ak.i;
66786    assert( memIsValid(&aMem[u.ak.p1+u.ak.idx]) );
66787    assert( memIsValid(&aMem[u.ak.p2+u.ak.idx]) );
66788    REGISTER_TRACE(u.ak.p1+u.ak.idx, &aMem[u.ak.p1+u.ak.idx]);
66789    REGISTER_TRACE(u.ak.p2+u.ak.idx, &aMem[u.ak.p2+u.ak.idx]);
66790    assert( u.ak.i<u.ak.pKeyInfo->nField );
66791    u.ak.pColl = u.ak.pKeyInfo->aColl[u.ak.i];
66792    u.ak.bRev = u.ak.pKeyInfo->aSortOrder[u.ak.i];
66793    iCompare = sqlite3MemCompare(&aMem[u.ak.p1+u.ak.idx], &aMem[u.ak.p2+u.ak.idx], u.ak.pColl);
66794    if( iCompare ){
66795      if( u.ak.bRev ) iCompare = -iCompare;
66796      break;
66797    }
66798  }
66799  aPermute = 0;
66800  break;
66801}
66802
66803/* Opcode: Jump P1 P2 P3 * *
66804**
66805** Jump to the instruction at address P1, P2, or P3 depending on whether
66806** in the most recent OP_Compare instruction the P1 vector was less than
66807** equal to, or greater than the P2 vector, respectively.
66808*/
66809case OP_Jump: {             /* jump */
66810  if( iCompare<0 ){
66811    pc = pOp->p1 - 1;
66812  }else if( iCompare==0 ){
66813    pc = pOp->p2 - 1;
66814  }else{
66815    pc = pOp->p3 - 1;
66816  }
66817  break;
66818}
66819
66820/* Opcode: And P1 P2 P3 * *
66821**
66822** Take the logical AND of the values in registers P1 and P2 and
66823** write the result into register P3.
66824**
66825** If either P1 or P2 is 0 (false) then the result is 0 even if
66826** the other input is NULL.  A NULL and true or two NULLs give
66827** a NULL output.
66828*/
66829/* Opcode: Or P1 P2 P3 * *
66830**
66831** Take the logical OR of the values in register P1 and P2 and
66832** store the answer in register P3.
66833**
66834** If either P1 or P2 is nonzero (true) then the result is 1 (true)
66835** even if the other input is NULL.  A NULL and false or two NULLs
66836** give a NULL output.
66837*/
66838case OP_And:              /* same as TK_AND, in1, in2, out3 */
66839case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
66840#if 0  /* local variables moved into u.al */
66841  int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66842  int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
66843#endif /* local variables moved into u.al */
66844
66845  pIn1 = &aMem[pOp->p1];
66846  if( pIn1->flags & MEM_Null ){
66847    u.al.v1 = 2;
66848  }else{
66849    u.al.v1 = sqlite3VdbeIntValue(pIn1)!=0;
66850  }
66851  pIn2 = &aMem[pOp->p2];
66852  if( pIn2->flags & MEM_Null ){
66853    u.al.v2 = 2;
66854  }else{
66855    u.al.v2 = sqlite3VdbeIntValue(pIn2)!=0;
66856  }
66857  if( pOp->opcode==OP_And ){
66858    static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
66859    u.al.v1 = and_logic[u.al.v1*3+u.al.v2];
66860  }else{
66861    static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
66862    u.al.v1 = or_logic[u.al.v1*3+u.al.v2];
66863  }
66864  pOut = &aMem[pOp->p3];
66865  if( u.al.v1==2 ){
66866    MemSetTypeFlag(pOut, MEM_Null);
66867  }else{
66868    pOut->u.i = u.al.v1;
66869    MemSetTypeFlag(pOut, MEM_Int);
66870  }
66871  break;
66872}
66873
66874/* Opcode: Not P1 P2 * * *
66875**
66876** Interpret the value in register P1 as a boolean value.  Store the
66877** boolean complement in register P2.  If the value in register P1 is
66878** NULL, then a NULL is stored in P2.
66879*/
66880case OP_Not: {                /* same as TK_NOT, in1, out2 */
66881  pIn1 = &aMem[pOp->p1];
66882  pOut = &aMem[pOp->p2];
66883  if( pIn1->flags & MEM_Null ){
66884    sqlite3VdbeMemSetNull(pOut);
66885  }else{
66886    sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
66887  }
66888  break;
66889}
66890
66891/* Opcode: BitNot P1 P2 * * *
66892**
66893** Interpret the content of register P1 as an integer.  Store the
66894** ones-complement of the P1 value into register P2.  If P1 holds
66895** a NULL then store a NULL in P2.
66896*/
66897case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
66898  pIn1 = &aMem[pOp->p1];
66899  pOut = &aMem[pOp->p2];
66900  if( pIn1->flags & MEM_Null ){
66901    sqlite3VdbeMemSetNull(pOut);
66902  }else{
66903    sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
66904  }
66905  break;
66906}
66907
66908/* Opcode: Once P1 P2 * * *
66909**
66910** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
66911** set the flag and fall through to the next instruction.
66912**
66913** See also: JumpOnce
66914*/
66915case OP_Once: {             /* jump */
66916  assert( pOp->p1<p->nOnceFlag );
66917  if( p->aOnceFlag[pOp->p1] ){
66918    pc = pOp->p2-1;
66919  }else{
66920    p->aOnceFlag[pOp->p1] = 1;
66921  }
66922  break;
66923}
66924
66925/* Opcode: If P1 P2 P3 * *
66926**
66927** Jump to P2 if the value in register P1 is true.  The value
66928** is considered true if it is numeric and non-zero.  If the value
66929** in P1 is NULL then take the jump if P3 is non-zero.
66930*/
66931/* Opcode: IfNot P1 P2 P3 * *
66932**
66933** Jump to P2 if the value in register P1 is False.  The value
66934** is considered false if it has a numeric value of zero.  If the value
66935** in P1 is NULL then take the jump if P3 is zero.
66936*/
66937case OP_If:                 /* jump, in1 */
66938case OP_IfNot: {            /* jump, in1 */
66939#if 0  /* local variables moved into u.am */
66940  int c;
66941#endif /* local variables moved into u.am */
66942  pIn1 = &aMem[pOp->p1];
66943  if( pIn1->flags & MEM_Null ){
66944    u.am.c = pOp->p3;
66945  }else{
66946#ifdef SQLITE_OMIT_FLOATING_POINT
66947    u.am.c = sqlite3VdbeIntValue(pIn1)!=0;
66948#else
66949    u.am.c = sqlite3VdbeRealValue(pIn1)!=0.0;
66950#endif
66951    if( pOp->opcode==OP_IfNot ) u.am.c = !u.am.c;
66952  }
66953  if( u.am.c ){
66954    pc = pOp->p2-1;
66955  }
66956  break;
66957}
66958
66959/* Opcode: IsNull P1 P2 * * *
66960**
66961** Jump to P2 if the value in register P1 is NULL.
66962*/
66963case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
66964  pIn1 = &aMem[pOp->p1];
66965  if( (pIn1->flags & MEM_Null)!=0 ){
66966    pc = pOp->p2 - 1;
66967  }
66968  break;
66969}
66970
66971/* Opcode: NotNull P1 P2 * * *
66972**
66973** Jump to P2 if the value in register P1 is not NULL.
66974*/
66975case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
66976  pIn1 = &aMem[pOp->p1];
66977  if( (pIn1->flags & MEM_Null)==0 ){
66978    pc = pOp->p2 - 1;
66979  }
66980  break;
66981}
66982
66983/* Opcode: Column P1 P2 P3 P4 P5
66984**
66985** Interpret the data that cursor P1 points to as a structure built using
66986** the MakeRecord instruction.  (See the MakeRecord opcode for additional
66987** information about the format of the data.)  Extract the P2-th column
66988** from this record.  If there are less that (P2+1)
66989** values in the record, extract a NULL.
66990**
66991** The value extracted is stored in register P3.
66992**
66993** If the column contains fewer than P2 fields, then extract a NULL.  Or,
66994** if the P4 argument is a P4_MEM use the value of the P4 argument as
66995** the result.
66996**
66997** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
66998** then the cache of the cursor is reset prior to extracting the column.
66999** The first OP_Column against a pseudo-table after the value of the content
67000** register has changed should have this bit set.
67001*/
67002case OP_Column: {
67003#if 0  /* local variables moved into u.an */
67004  u32 payloadSize;   /* Number of bytes in the record */
67005  i64 payloadSize64; /* Number of bytes in the record */
67006  int p1;            /* P1 value of the opcode */
67007  int p2;            /* column number to retrieve */
67008  VdbeCursor *pC;    /* The VDBE cursor */
67009  char *zRec;        /* Pointer to complete record-data */
67010  BtCursor *pCrsr;   /* The BTree cursor */
67011  u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
67012  u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
67013  int nField;        /* number of fields in the record */
67014  int len;           /* The length of the serialized data for the column */
67015  int i;             /* Loop counter */
67016  char *zData;       /* Part of the record being decoded */
67017  Mem *pDest;        /* Where to write the extracted value */
67018  Mem sMem;          /* For storing the record being decoded */
67019  u8 *zIdx;          /* Index into header */
67020  u8 *zEndHdr;       /* Pointer to first byte after the header */
67021  u32 offset;        /* Offset into the data */
67022  u32 szField;       /* Number of bytes in the content of a field */
67023  int szHdr;         /* Size of the header size field at start of record */
67024  int avail;         /* Number of bytes of available data */
67025  u32 t;             /* A type code from the record header */
67026  Mem *pReg;         /* PseudoTable input register */
67027#endif /* local variables moved into u.an */
67028
67029
67030  u.an.p1 = pOp->p1;
67031  u.an.p2 = pOp->p2;
67032  u.an.pC = 0;
67033  memset(&u.an.sMem, 0, sizeof(u.an.sMem));
67034  assert( u.an.p1<p->nCursor );
67035  assert( pOp->p3>0 && pOp->p3<=p->nMem );
67036  u.an.pDest = &aMem[pOp->p3];
67037  memAboutToChange(p, u.an.pDest);
67038  u.an.zRec = 0;
67039
67040  /* This block sets the variable u.an.payloadSize to be the total number of
67041  ** bytes in the record.
67042  **
67043  ** u.an.zRec is set to be the complete text of the record if it is available.
67044  ** The complete record text is always available for pseudo-tables
67045  ** If the record is stored in a cursor, the complete record text
67046  ** might be available in the  u.an.pC->aRow cache.  Or it might not be.
67047  ** If the data is unavailable,  u.an.zRec is set to NULL.
67048  **
67049  ** We also compute the number of columns in the record.  For cursors,
67050  ** the number of columns is stored in the VdbeCursor.nField element.
67051  */
67052  u.an.pC = p->apCsr[u.an.p1];
67053  assert( u.an.pC!=0 );
67054#ifndef SQLITE_OMIT_VIRTUALTABLE
67055  assert( u.an.pC->pVtabCursor==0 );
67056#endif
67057  u.an.pCrsr = u.an.pC->pCursor;
67058  if( u.an.pCrsr!=0 ){
67059    /* The record is stored in a B-Tree */
67060    rc = sqlite3VdbeCursorMoveto(u.an.pC);
67061    if( rc ) goto abort_due_to_error;
67062    if( u.an.pC->nullRow ){
67063      u.an.payloadSize = 0;
67064    }else if( u.an.pC->cacheStatus==p->cacheCtr ){
67065      u.an.payloadSize = u.an.pC->payloadSize;
67066      u.an.zRec = (char*)u.an.pC->aRow;
67067    }else if( u.an.pC->isIndex ){
67068      assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
67069      VVA_ONLY(rc =) sqlite3BtreeKeySize(u.an.pCrsr, &u.an.payloadSize64);
67070      assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
67071      /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
67072      ** payload size, so it is impossible for u.an.payloadSize64 to be
67073      ** larger than 32 bits. */
67074      assert( (u.an.payloadSize64 & SQLITE_MAX_U32)==(u64)u.an.payloadSize64 );
67075      u.an.payloadSize = (u32)u.an.payloadSize64;
67076    }else{
67077      assert( sqlite3BtreeCursorIsValid(u.an.pCrsr) );
67078      VVA_ONLY(rc =) sqlite3BtreeDataSize(u.an.pCrsr, &u.an.payloadSize);
67079      assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
67080    }
67081  }else if( ALWAYS(u.an.pC->pseudoTableReg>0) ){
67082    u.an.pReg = &aMem[u.an.pC->pseudoTableReg];
67083    assert( u.an.pReg->flags & MEM_Blob );
67084    assert( memIsValid(u.an.pReg) );
67085    u.an.payloadSize = u.an.pReg->n;
67086    u.an.zRec = u.an.pReg->z;
67087    u.an.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
67088    assert( u.an.payloadSize==0 || u.an.zRec!=0 );
67089  }else{
67090    /* Consider the row to be NULL */
67091    u.an.payloadSize = 0;
67092  }
67093
67094  /* If u.an.payloadSize is 0, then just store a NULL.  This can happen because of
67095  ** nullRow or because of a corrupt database. */
67096  if( u.an.payloadSize==0 ){
67097    MemSetTypeFlag(u.an.pDest, MEM_Null);
67098    goto op_column_out;
67099  }
67100  assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
67101  if( u.an.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67102    goto too_big;
67103  }
67104
67105  u.an.nField = u.an.pC->nField;
67106  assert( u.an.p2<u.an.nField );
67107
67108  /* Read and parse the table header.  Store the results of the parse
67109  ** into the record header cache fields of the cursor.
67110  */
67111  u.an.aType = u.an.pC->aType;
67112  if( u.an.pC->cacheStatus==p->cacheCtr ){
67113    u.an.aOffset = u.an.pC->aOffset;
67114  }else{
67115    assert(u.an.aType);
67116    u.an.avail = 0;
67117    u.an.pC->aOffset = u.an.aOffset = &u.an.aType[u.an.nField];
67118    u.an.pC->payloadSize = u.an.payloadSize;
67119    u.an.pC->cacheStatus = p->cacheCtr;
67120
67121    /* Figure out how many bytes are in the header */
67122    if( u.an.zRec ){
67123      u.an.zData = u.an.zRec;
67124    }else{
67125      if( u.an.pC->isIndex ){
67126        u.an.zData = (char*)sqlite3BtreeKeyFetch(u.an.pCrsr, &u.an.avail);
67127      }else{
67128        u.an.zData = (char*)sqlite3BtreeDataFetch(u.an.pCrsr, &u.an.avail);
67129      }
67130      /* If KeyFetch()/DataFetch() managed to get the entire payload,
67131      ** save the payload in the u.an.pC->aRow cache.  That will save us from
67132      ** having to make additional calls to fetch the content portion of
67133      ** the record.
67134      */
67135      assert( u.an.avail>=0 );
67136      if( u.an.payloadSize <= (u32)u.an.avail ){
67137        u.an.zRec = u.an.zData;
67138        u.an.pC->aRow = (u8*)u.an.zData;
67139      }else{
67140        u.an.pC->aRow = 0;
67141      }
67142    }
67143    /* The following assert is true in all cases accept when
67144    ** the database file has been corrupted externally.
67145    **    assert( u.an.zRec!=0 || u.an.avail>=u.an.payloadSize || u.an.avail>=9 ); */
67146    u.an.szHdr = getVarint32((u8*)u.an.zData, u.an.offset);
67147
67148    /* Make sure a corrupt database has not given us an oversize header.
67149    ** Do this now to avoid an oversize memory allocation.
67150    **
67151    ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
67152    ** types use so much data space that there can only be 4096 and 32 of
67153    ** them, respectively.  So the maximum header length results from a
67154    ** 3-byte type for each of the maximum of 32768 columns plus three
67155    ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
67156    */
67157    if( u.an.offset > 98307 ){
67158      rc = SQLITE_CORRUPT_BKPT;
67159      goto op_column_out;
67160    }
67161
67162    /* Compute in u.an.len the number of bytes of data we need to read in order
67163    ** to get u.an.nField type values.  u.an.offset is an upper bound on this.  But
67164    ** u.an.nField might be significantly less than the true number of columns
67165    ** in the table, and in that case, 5*u.an.nField+3 might be smaller than u.an.offset.
67166    ** We want to minimize u.an.len in order to limit the size of the memory
67167    ** allocation, especially if a corrupt database file has caused u.an.offset
67168    ** to be oversized. Offset is limited to 98307 above.  But 98307 might
67169    ** still exceed Robson memory allocation limits on some configurations.
67170    ** On systems that cannot tolerate large memory allocations, u.an.nField*5+3
67171    ** will likely be much smaller since u.an.nField will likely be less than
67172    ** 20 or so.  This insures that Robson memory allocation limits are
67173    ** not exceeded even for corrupt database files.
67174    */
67175    u.an.len = u.an.nField*5 + 3;
67176    if( u.an.len > (int)u.an.offset ) u.an.len = (int)u.an.offset;
67177
67178    /* The KeyFetch() or DataFetch() above are fast and will get the entire
67179    ** record header in most cases.  But they will fail to get the complete
67180    ** record header if the record header does not fit on a single page
67181    ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
67182    ** acquire the complete header text.
67183    */
67184    if( !u.an.zRec && u.an.avail<u.an.len ){
67185      u.an.sMem.flags = 0;
67186      u.an.sMem.db = 0;
67187      rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, 0, u.an.len, u.an.pC->isIndex, &u.an.sMem);
67188      if( rc!=SQLITE_OK ){
67189        goto op_column_out;
67190      }
67191      u.an.zData = u.an.sMem.z;
67192    }
67193    u.an.zEndHdr = (u8 *)&u.an.zData[u.an.len];
67194    u.an.zIdx = (u8 *)&u.an.zData[u.an.szHdr];
67195
67196    /* Scan the header and use it to fill in the u.an.aType[] and u.an.aOffset[]
67197    ** arrays.  u.an.aType[u.an.i] will contain the type integer for the u.an.i-th
67198    ** column and u.an.aOffset[u.an.i] will contain the u.an.offset from the beginning
67199    ** of the record to the start of the data for the u.an.i-th column
67200    */
67201    for(u.an.i=0; u.an.i<u.an.nField; u.an.i++){
67202      if( u.an.zIdx<u.an.zEndHdr ){
67203        u.an.aOffset[u.an.i] = u.an.offset;
67204        if( u.an.zIdx[0]<0x80 ){
67205          u.an.t = u.an.zIdx[0];
67206          u.an.zIdx++;
67207        }else{
67208          u.an.zIdx += sqlite3GetVarint32(u.an.zIdx, &u.an.t);
67209        }
67210        u.an.aType[u.an.i] = u.an.t;
67211        u.an.szField = sqlite3VdbeSerialTypeLen(u.an.t);
67212        u.an.offset += u.an.szField;
67213        if( u.an.offset<u.an.szField ){  /* True if u.an.offset overflows */
67214          u.an.zIdx = &u.an.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
67215          break;
67216        }
67217      }else{
67218        /* If u.an.i is less that u.an.nField, then there are less fields in this
67219        ** record than SetNumColumns indicated there are columns in the
67220        ** table. Set the u.an.offset for any extra columns not present in
67221        ** the record to 0. This tells code below to store a NULL
67222        ** instead of deserializing a value from the record.
67223        */
67224        u.an.aOffset[u.an.i] = 0;
67225      }
67226    }
67227    sqlite3VdbeMemRelease(&u.an.sMem);
67228    u.an.sMem.flags = MEM_Null;
67229
67230    /* If we have read more header data than was contained in the header,
67231    ** or if the end of the last field appears to be past the end of the
67232    ** record, or if the end of the last field appears to be before the end
67233    ** of the record (when all fields present), then we must be dealing
67234    ** with a corrupt database.
67235    */
67236    if( (u.an.zIdx > u.an.zEndHdr) || (u.an.offset > u.an.payloadSize)
67237         || (u.an.zIdx==u.an.zEndHdr && u.an.offset!=u.an.payloadSize) ){
67238      rc = SQLITE_CORRUPT_BKPT;
67239      goto op_column_out;
67240    }
67241  }
67242
67243  /* Get the column information. If u.an.aOffset[u.an.p2] is non-zero, then
67244  ** deserialize the value from the record. If u.an.aOffset[u.an.p2] is zero,
67245  ** then there are not enough fields in the record to satisfy the
67246  ** request.  In this case, set the value NULL or to P4 if P4 is
67247  ** a pointer to a Mem object.
67248  */
67249  if( u.an.aOffset[u.an.p2] ){
67250    assert( rc==SQLITE_OK );
67251    if( u.an.zRec ){
67252      VdbeMemRelease(u.an.pDest);
67253      sqlite3VdbeSerialGet((u8 *)&u.an.zRec[u.an.aOffset[u.an.p2]], u.an.aType[u.an.p2], u.an.pDest);
67254    }else{
67255      u.an.len = sqlite3VdbeSerialTypeLen(u.an.aType[u.an.p2]);
67256      sqlite3VdbeMemMove(&u.an.sMem, u.an.pDest);
67257      rc = sqlite3VdbeMemFromBtree(u.an.pCrsr, u.an.aOffset[u.an.p2], u.an.len, u.an.pC->isIndex, &u.an.sMem);
67258      if( rc!=SQLITE_OK ){
67259        goto op_column_out;
67260      }
67261      u.an.zData = u.an.sMem.z;
67262      sqlite3VdbeSerialGet((u8*)u.an.zData, u.an.aType[u.an.p2], u.an.pDest);
67263    }
67264    u.an.pDest->enc = encoding;
67265  }else{
67266    if( pOp->p4type==P4_MEM ){
67267      sqlite3VdbeMemShallowCopy(u.an.pDest, pOp->p4.pMem, MEM_Static);
67268    }else{
67269      MemSetTypeFlag(u.an.pDest, MEM_Null);
67270    }
67271  }
67272
67273  /* If we dynamically allocated space to hold the data (in the
67274  ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
67275  ** dynamically allocated space over to the u.an.pDest structure.
67276  ** This prevents a memory copy.
67277  */
67278  if( u.an.sMem.zMalloc ){
67279    assert( u.an.sMem.z==u.an.sMem.zMalloc );
67280    assert( !(u.an.pDest->flags & MEM_Dyn) );
67281    assert( !(u.an.pDest->flags & (MEM_Blob|MEM_Str)) || u.an.pDest->z==u.an.sMem.z );
67282    u.an.pDest->flags &= ~(MEM_Ephem|MEM_Static);
67283    u.an.pDest->flags |= MEM_Term;
67284    u.an.pDest->z = u.an.sMem.z;
67285    u.an.pDest->zMalloc = u.an.sMem.zMalloc;
67286  }
67287
67288  rc = sqlite3VdbeMemMakeWriteable(u.an.pDest);
67289
67290op_column_out:
67291  UPDATE_MAX_BLOBSIZE(u.an.pDest);
67292  REGISTER_TRACE(pOp->p3, u.an.pDest);
67293  break;
67294}
67295
67296/* Opcode: Affinity P1 P2 * P4 *
67297**
67298** Apply affinities to a range of P2 registers starting with P1.
67299**
67300** P4 is a string that is P2 characters long. The nth character of the
67301** string indicates the column affinity that should be used for the nth
67302** memory cell in the range.
67303*/
67304case OP_Affinity: {
67305#if 0  /* local variables moved into u.ao */
67306  const char *zAffinity;   /* The affinity to be applied */
67307  char cAff;               /* A single character of affinity */
67308#endif /* local variables moved into u.ao */
67309
67310  u.ao.zAffinity = pOp->p4.z;
67311  assert( u.ao.zAffinity!=0 );
67312  assert( u.ao.zAffinity[pOp->p2]==0 );
67313  pIn1 = &aMem[pOp->p1];
67314  while( (u.ao.cAff = *(u.ao.zAffinity++))!=0 ){
67315    assert( pIn1 <= &p->aMem[p->nMem] );
67316    assert( memIsValid(pIn1) );
67317    ExpandBlob(pIn1);
67318    applyAffinity(pIn1, u.ao.cAff, encoding);
67319    pIn1++;
67320  }
67321  break;
67322}
67323
67324/* Opcode: MakeRecord P1 P2 P3 P4 *
67325**
67326** Convert P2 registers beginning with P1 into the [record format]
67327** use as a data record in a database table or as a key
67328** in an index.  The OP_Column opcode can decode the record later.
67329**
67330** P4 may be a string that is P2 characters long.  The nth character of the
67331** string indicates the column affinity that should be used for the nth
67332** field of the index key.
67333**
67334** The mapping from character to affinity is given by the SQLITE_AFF_
67335** macros defined in sqliteInt.h.
67336**
67337** If P4 is NULL then all index fields have the affinity NONE.
67338*/
67339case OP_MakeRecord: {
67340#if 0  /* local variables moved into u.ap */
67341  u8 *zNewRecord;        /* A buffer to hold the data for the new record */
67342  Mem *pRec;             /* The new record */
67343  u64 nData;             /* Number of bytes of data space */
67344  int nHdr;              /* Number of bytes of header space */
67345  i64 nByte;             /* Data space required for this record */
67346  int nZero;             /* Number of zero bytes at the end of the record */
67347  int nVarint;           /* Number of bytes in a varint */
67348  u32 serial_type;       /* Type field */
67349  Mem *pData0;           /* First field to be combined into the record */
67350  Mem *pLast;            /* Last field of the record */
67351  int nField;            /* Number of fields in the record */
67352  char *zAffinity;       /* The affinity string for the record */
67353  int file_format;       /* File format to use for encoding */
67354  int i;                 /* Space used in zNewRecord[] */
67355  int len;               /* Length of a field */
67356#endif /* local variables moved into u.ap */
67357
67358  /* Assuming the record contains N fields, the record format looks
67359  ** like this:
67360  **
67361  ** ------------------------------------------------------------------------
67362  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
67363  ** ------------------------------------------------------------------------
67364  **
67365  ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
67366  ** and so froth.
67367  **
67368  ** Each type field is a varint representing the serial type of the
67369  ** corresponding data element (see sqlite3VdbeSerialType()). The
67370  ** hdr-size field is also a varint which is the offset from the beginning
67371  ** of the record to data0.
67372  */
67373  u.ap.nData = 0;         /* Number of bytes of data space */
67374  u.ap.nHdr = 0;          /* Number of bytes of header space */
67375  u.ap.nZero = 0;         /* Number of zero bytes at the end of the record */
67376  u.ap.nField = pOp->p1;
67377  u.ap.zAffinity = pOp->p4.z;
67378  assert( u.ap.nField>0 && pOp->p2>0 && pOp->p2+u.ap.nField<=p->nMem+1 );
67379  u.ap.pData0 = &aMem[u.ap.nField];
67380  u.ap.nField = pOp->p2;
67381  u.ap.pLast = &u.ap.pData0[u.ap.nField-1];
67382  u.ap.file_format = p->minWriteFileFormat;
67383
67384  /* Identify the output register */
67385  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
67386  pOut = &aMem[pOp->p3];
67387  memAboutToChange(p, pOut);
67388
67389  /* Loop through the elements that will make up the record to figure
67390  ** out how much space is required for the new record.
67391  */
67392  for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
67393    assert( memIsValid(u.ap.pRec) );
67394    if( u.ap.zAffinity ){
67395      applyAffinity(u.ap.pRec, u.ap.zAffinity[u.ap.pRec-u.ap.pData0], encoding);
67396    }
67397    if( u.ap.pRec->flags&MEM_Zero && u.ap.pRec->n>0 ){
67398      sqlite3VdbeMemExpandBlob(u.ap.pRec);
67399    }
67400    u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
67401    u.ap.len = sqlite3VdbeSerialTypeLen(u.ap.serial_type);
67402    u.ap.nData += u.ap.len;
67403    u.ap.nHdr += sqlite3VarintLen(u.ap.serial_type);
67404    if( u.ap.pRec->flags & MEM_Zero ){
67405      /* Only pure zero-filled BLOBs can be input to this Opcode.
67406      ** We do not allow blobs with a prefix and a zero-filled tail. */
67407      u.ap.nZero += u.ap.pRec->u.nZero;
67408    }else if( u.ap.len ){
67409      u.ap.nZero = 0;
67410    }
67411  }
67412
67413  /* Add the initial header varint and total the size */
67414  u.ap.nHdr += u.ap.nVarint = sqlite3VarintLen(u.ap.nHdr);
67415  if( u.ap.nVarint<sqlite3VarintLen(u.ap.nHdr) ){
67416    u.ap.nHdr++;
67417  }
67418  u.ap.nByte = u.ap.nHdr+u.ap.nData-u.ap.nZero;
67419  if( u.ap.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
67420    goto too_big;
67421  }
67422
67423  /* Make sure the output register has a buffer large enough to store
67424  ** the new record. The output register (pOp->p3) is not allowed to
67425  ** be one of the input registers (because the following call to
67426  ** sqlite3VdbeMemGrow() could clobber the value before it is used).
67427  */
67428  if( sqlite3VdbeMemGrow(pOut, (int)u.ap.nByte, 0) ){
67429    goto no_mem;
67430  }
67431  u.ap.zNewRecord = (u8 *)pOut->z;
67432
67433  /* Write the record */
67434  u.ap.i = putVarint32(u.ap.zNewRecord, u.ap.nHdr);
67435  for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){
67436    u.ap.serial_type = sqlite3VdbeSerialType(u.ap.pRec, u.ap.file_format);
67437    u.ap.i += putVarint32(&u.ap.zNewRecord[u.ap.i], u.ap.serial_type);      /* serial type */
67438  }
67439  for(u.ap.pRec=u.ap.pData0; u.ap.pRec<=u.ap.pLast; u.ap.pRec++){  /* serial data */
67440    u.ap.i += sqlite3VdbeSerialPut(&u.ap.zNewRecord[u.ap.i], (int)(u.ap.nByte-u.ap.i), u.ap.pRec,u.ap.file_format);
67441  }
67442  assert( u.ap.i==u.ap.nByte );
67443
67444  assert( pOp->p3>0 && pOp->p3<=p->nMem );
67445  pOut->n = (int)u.ap.nByte;
67446  pOut->flags = MEM_Blob | MEM_Dyn;
67447  pOut->xDel = 0;
67448  if( u.ap.nZero ){
67449    pOut->u.nZero = u.ap.nZero;
67450    pOut->flags |= MEM_Zero;
67451  }
67452  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
67453  REGISTER_TRACE(pOp->p3, pOut);
67454  UPDATE_MAX_BLOBSIZE(pOut);
67455  break;
67456}
67457
67458/* Opcode: Count P1 P2 * * *
67459**
67460** Store the number of entries (an integer value) in the table or index
67461** opened by cursor P1 in register P2
67462*/
67463#ifndef SQLITE_OMIT_BTREECOUNT
67464case OP_Count: {         /* out2-prerelease */
67465#if 0  /* local variables moved into u.aq */
67466  i64 nEntry;
67467  BtCursor *pCrsr;
67468#endif /* local variables moved into u.aq */
67469
67470  u.aq.pCrsr = p->apCsr[pOp->p1]->pCursor;
67471  if( ALWAYS(u.aq.pCrsr) ){
67472    rc = sqlite3BtreeCount(u.aq.pCrsr, &u.aq.nEntry);
67473  }else{
67474    u.aq.nEntry = 0;
67475  }
67476  pOut->u.i = u.aq.nEntry;
67477  break;
67478}
67479#endif
67480
67481/* Opcode: Savepoint P1 * * P4 *
67482**
67483** Open, release or rollback the savepoint named by parameter P4, depending
67484** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
67485** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
67486*/
67487case OP_Savepoint: {
67488#if 0  /* local variables moved into u.ar */
67489  int p1;                         /* Value of P1 operand */
67490  char *zName;                    /* Name of savepoint */
67491  int nName;
67492  Savepoint *pNew;
67493  Savepoint *pSavepoint;
67494  Savepoint *pTmp;
67495  int iSavepoint;
67496  int ii;
67497#endif /* local variables moved into u.ar */
67498
67499  u.ar.p1 = pOp->p1;
67500  u.ar.zName = pOp->p4.z;
67501
67502  /* Assert that the u.ar.p1 parameter is valid. Also that if there is no open
67503  ** transaction, then there cannot be any savepoints.
67504  */
67505  assert( db->pSavepoint==0 || db->autoCommit==0 );
67506  assert( u.ar.p1==SAVEPOINT_BEGIN||u.ar.p1==SAVEPOINT_RELEASE||u.ar.p1==SAVEPOINT_ROLLBACK );
67507  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
67508  assert( checkSavepointCount(db) );
67509
67510  if( u.ar.p1==SAVEPOINT_BEGIN ){
67511    if( db->writeVdbeCnt>0 ){
67512      /* A new savepoint cannot be created if there are active write
67513      ** statements (i.e. open read/write incremental blob handles).
67514      */
67515      sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
67516        "SQL statements in progress");
67517      rc = SQLITE_BUSY;
67518    }else{
67519      u.ar.nName = sqlite3Strlen30(u.ar.zName);
67520
67521#ifndef SQLITE_OMIT_VIRTUALTABLE
67522      /* This call is Ok even if this savepoint is actually a transaction
67523      ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
67524      ** If this is a transaction savepoint being opened, it is guaranteed
67525      ** that the db->aVTrans[] array is empty.  */
67526      assert( db->autoCommit==0 || db->nVTrans==0 );
67527      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
67528                                db->nStatement+db->nSavepoint);
67529      if( rc!=SQLITE_OK ) goto abort_due_to_error;
67530#endif
67531
67532      /* Create a new savepoint structure. */
67533      u.ar.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.ar.nName+1);
67534      if( u.ar.pNew ){
67535        u.ar.pNew->zName = (char *)&u.ar.pNew[1];
67536        memcpy(u.ar.pNew->zName, u.ar.zName, u.ar.nName+1);
67537
67538        /* If there is no open transaction, then mark this as a special
67539        ** "transaction savepoint". */
67540        if( db->autoCommit ){
67541          db->autoCommit = 0;
67542          db->isTransactionSavepoint = 1;
67543        }else{
67544          db->nSavepoint++;
67545        }
67546
67547        /* Link the new savepoint into the database handle's list. */
67548        u.ar.pNew->pNext = db->pSavepoint;
67549        db->pSavepoint = u.ar.pNew;
67550        u.ar.pNew->nDeferredCons = db->nDeferredCons;
67551      }
67552    }
67553  }else{
67554    u.ar.iSavepoint = 0;
67555
67556    /* Find the named savepoint. If there is no such savepoint, then an
67557    ** an error is returned to the user.  */
67558    for(
67559      u.ar.pSavepoint = db->pSavepoint;
67560      u.ar.pSavepoint && sqlite3StrICmp(u.ar.pSavepoint->zName, u.ar.zName);
67561      u.ar.pSavepoint = u.ar.pSavepoint->pNext
67562    ){
67563      u.ar.iSavepoint++;
67564    }
67565    if( !u.ar.pSavepoint ){
67566      sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.ar.zName);
67567      rc = SQLITE_ERROR;
67568    }else if( db->writeVdbeCnt>0 && u.ar.p1==SAVEPOINT_RELEASE ){
67569      /* It is not possible to release (commit) a savepoint if there are
67570      ** active write statements.
67571      */
67572      sqlite3SetString(&p->zErrMsg, db,
67573        "cannot release savepoint - SQL statements in progress"
67574      );
67575      rc = SQLITE_BUSY;
67576    }else{
67577
67578      /* Determine whether or not this is a transaction savepoint. If so,
67579      ** and this is a RELEASE command, then the current transaction
67580      ** is committed.
67581      */
67582      int isTransaction = u.ar.pSavepoint->pNext==0 && db->isTransactionSavepoint;
67583      if( isTransaction && u.ar.p1==SAVEPOINT_RELEASE ){
67584        if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
67585          goto vdbe_return;
67586        }
67587        db->autoCommit = 1;
67588        if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
67589          p->pc = pc;
67590          db->autoCommit = 0;
67591          p->rc = rc = SQLITE_BUSY;
67592          goto vdbe_return;
67593        }
67594        db->isTransactionSavepoint = 0;
67595        rc = p->rc;
67596      }else{
67597        u.ar.iSavepoint = db->nSavepoint - u.ar.iSavepoint - 1;
67598        for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
67599          sqlite3BtreeTripAllCursors(db->aDb[u.ar.ii].pBt, SQLITE_ABORT);
67600        }
67601        for(u.ar.ii=0; u.ar.ii<db->nDb; u.ar.ii++){
67602          rc = sqlite3BtreeSavepoint(db->aDb[u.ar.ii].pBt, u.ar.p1, u.ar.iSavepoint);
67603          if( rc!=SQLITE_OK ){
67604            goto abort_due_to_error;
67605          }
67606        }
67607        if( u.ar.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
67608          sqlite3ExpirePreparedStatements(db);
67609          sqlite3ResetInternalSchema(db, -1);
67610          db->flags = (db->flags | SQLITE_InternChanges);
67611        }
67612      }
67613
67614      /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
67615      ** savepoints nested inside of the savepoint being operated on. */
67616      while( db->pSavepoint!=u.ar.pSavepoint ){
67617        u.ar.pTmp = db->pSavepoint;
67618        db->pSavepoint = u.ar.pTmp->pNext;
67619        sqlite3DbFree(db, u.ar.pTmp);
67620        db->nSavepoint--;
67621      }
67622
67623      /* If it is a RELEASE, then destroy the savepoint being operated on
67624      ** too. If it is a ROLLBACK TO, then set the number of deferred
67625      ** constraint violations present in the database to the value stored
67626      ** when the savepoint was created.  */
67627      if( u.ar.p1==SAVEPOINT_RELEASE ){
67628        assert( u.ar.pSavepoint==db->pSavepoint );
67629        db->pSavepoint = u.ar.pSavepoint->pNext;
67630        sqlite3DbFree(db, u.ar.pSavepoint);
67631        if( !isTransaction ){
67632          db->nSavepoint--;
67633        }
67634      }else{
67635        db->nDeferredCons = u.ar.pSavepoint->nDeferredCons;
67636      }
67637
67638      if( !isTransaction ){
67639        rc = sqlite3VtabSavepoint(db, u.ar.p1, u.ar.iSavepoint);
67640        if( rc!=SQLITE_OK ) goto abort_due_to_error;
67641      }
67642    }
67643  }
67644
67645  break;
67646}
67647
67648/* Opcode: AutoCommit P1 P2 * * *
67649**
67650** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
67651** back any currently active btree transactions. If there are any active
67652** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
67653** there are active writing VMs or active VMs that use shared cache.
67654**
67655** This instruction causes the VM to halt.
67656*/
67657case OP_AutoCommit: {
67658#if 0  /* local variables moved into u.as */
67659  int desiredAutoCommit;
67660  int iRollback;
67661  int turnOnAC;
67662#endif /* local variables moved into u.as */
67663
67664  u.as.desiredAutoCommit = pOp->p1;
67665  u.as.iRollback = pOp->p2;
67666  u.as.turnOnAC = u.as.desiredAutoCommit && !db->autoCommit;
67667  assert( u.as.desiredAutoCommit==1 || u.as.desiredAutoCommit==0 );
67668  assert( u.as.desiredAutoCommit==1 || u.as.iRollback==0 );
67669  assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
67670
67671#if 0
67672  if( u.as.turnOnAC && u.as.iRollback && db->activeVdbeCnt>1 ){
67673    /* If this instruction implements a ROLLBACK and other VMs are
67674    ** still running, and a transaction is active, return an error indicating
67675    ** that the other VMs must complete first.
67676    */
67677    sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
67678        "SQL statements in progress");
67679    rc = SQLITE_BUSY;
67680  }else
67681#endif
67682  if( u.as.turnOnAC && !u.as.iRollback && db->writeVdbeCnt>0 ){
67683    /* If this instruction implements a COMMIT and other VMs are writing
67684    ** return an error indicating that the other VMs must complete first.
67685    */
67686    sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
67687        "SQL statements in progress");
67688    rc = SQLITE_BUSY;
67689  }else if( u.as.desiredAutoCommit!=db->autoCommit ){
67690    if( u.as.iRollback ){
67691      assert( u.as.desiredAutoCommit==1 );
67692      sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
67693      db->autoCommit = 1;
67694    }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
67695      goto vdbe_return;
67696    }else{
67697      db->autoCommit = (u8)u.as.desiredAutoCommit;
67698      if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
67699        p->pc = pc;
67700        db->autoCommit = (u8)(1-u.as.desiredAutoCommit);
67701        p->rc = rc = SQLITE_BUSY;
67702        goto vdbe_return;
67703      }
67704    }
67705    assert( db->nStatement==0 );
67706    sqlite3CloseSavepoints(db);
67707    if( p->rc==SQLITE_OK ){
67708      rc = SQLITE_DONE;
67709    }else{
67710      rc = SQLITE_ERROR;
67711    }
67712    goto vdbe_return;
67713  }else{
67714    sqlite3SetString(&p->zErrMsg, db,
67715        (!u.as.desiredAutoCommit)?"cannot start a transaction within a transaction":(
67716        (u.as.iRollback)?"cannot rollback - no transaction is active":
67717                   "cannot commit - no transaction is active"));
67718
67719    rc = SQLITE_ERROR;
67720  }
67721  break;
67722}
67723
67724/* Opcode: Transaction P1 P2 * * *
67725**
67726** Begin a transaction.  The transaction ends when a Commit or Rollback
67727** opcode is encountered.  Depending on the ON CONFLICT setting, the
67728** transaction might also be rolled back if an error is encountered.
67729**
67730** P1 is the index of the database file on which the transaction is
67731** started.  Index 0 is the main database file and index 1 is the
67732** file used for temporary tables.  Indices of 2 or more are used for
67733** attached databases.
67734**
67735** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
67736** obtained on the database file when a write-transaction is started.  No
67737** other process can start another write transaction while this transaction is
67738** underway.  Starting a write transaction also creates a rollback journal. A
67739** write transaction must be started before any changes can be made to the
67740** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
67741** on the file.
67742**
67743** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
67744** true (this flag is set if the Vdbe may modify more than one row and may
67745** throw an ABORT exception), a statement transaction may also be opened.
67746** More specifically, a statement transaction is opened iff the database
67747** connection is currently not in autocommit mode, or if there are other
67748** active statements. A statement transaction allows the changes made by this
67749** VDBE to be rolled back after an error without having to roll back the
67750** entire transaction. If no error is encountered, the statement transaction
67751** will automatically commit when the VDBE halts.
67752**
67753** If P2 is zero, then a read-lock is obtained on the database file.
67754*/
67755case OP_Transaction: {
67756#if 0  /* local variables moved into u.at */
67757  Btree *pBt;
67758#endif /* local variables moved into u.at */
67759
67760  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67761  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67762  u.at.pBt = db->aDb[pOp->p1].pBt;
67763
67764  if( u.at.pBt ){
67765    rc = sqlite3BtreeBeginTrans(u.at.pBt, pOp->p2);
67766    if( rc==SQLITE_BUSY ){
67767      p->pc = pc;
67768      p->rc = rc = SQLITE_BUSY;
67769      goto vdbe_return;
67770    }
67771    if( rc!=SQLITE_OK ){
67772      goto abort_due_to_error;
67773    }
67774
67775    if( pOp->p2 && p->usesStmtJournal
67776     && (db->autoCommit==0 || db->activeVdbeCnt>1)
67777    ){
67778      assert( sqlite3BtreeIsInTrans(u.at.pBt) );
67779      if( p->iStatement==0 ){
67780        assert( db->nStatement>=0 && db->nSavepoint>=0 );
67781        db->nStatement++;
67782        p->iStatement = db->nSavepoint + db->nStatement;
67783      }
67784
67785      rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
67786      if( rc==SQLITE_OK ){
67787        rc = sqlite3BtreeBeginStmt(u.at.pBt, p->iStatement);
67788      }
67789
67790      /* Store the current value of the database handles deferred constraint
67791      ** counter. If the statement transaction needs to be rolled back,
67792      ** the value of this counter needs to be restored too.  */
67793      p->nStmtDefCons = db->nDeferredCons;
67794    }
67795  }
67796  break;
67797}
67798
67799/* Opcode: ReadCookie P1 P2 P3 * *
67800**
67801** Read cookie number P3 from database P1 and write it into register P2.
67802** P3==1 is the schema version.  P3==2 is the database format.
67803** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
67804** the main database file and P1==1 is the database file used to store
67805** temporary tables.
67806**
67807** There must be a read-lock on the database (either a transaction
67808** must be started or there must be an open cursor) before
67809** executing this instruction.
67810*/
67811case OP_ReadCookie: {               /* out2-prerelease */
67812#if 0  /* local variables moved into u.au */
67813  int iMeta;
67814  int iDb;
67815  int iCookie;
67816#endif /* local variables moved into u.au */
67817
67818  u.au.iDb = pOp->p1;
67819  u.au.iCookie = pOp->p3;
67820  assert( pOp->p3<SQLITE_N_BTREE_META );
67821  assert( u.au.iDb>=0 && u.au.iDb<db->nDb );
67822  assert( db->aDb[u.au.iDb].pBt!=0 );
67823  assert( (p->btreeMask & (((yDbMask)1)<<u.au.iDb))!=0 );
67824
67825  sqlite3BtreeGetMeta(db->aDb[u.au.iDb].pBt, u.au.iCookie, (u32 *)&u.au.iMeta);
67826  pOut->u.i = u.au.iMeta;
67827  break;
67828}
67829
67830/* Opcode: SetCookie P1 P2 P3 * *
67831**
67832** Write the content of register P3 (interpreted as an integer)
67833** into cookie number P2 of database P1.  P2==1 is the schema version.
67834** P2==2 is the database format. P2==3 is the recommended pager cache
67835** size, and so forth.  P1==0 is the main database file and P1==1 is the
67836** database file used to store temporary tables.
67837**
67838** A transaction must be started before executing this opcode.
67839*/
67840case OP_SetCookie: {       /* in3 */
67841#if 0  /* local variables moved into u.av */
67842  Db *pDb;
67843#endif /* local variables moved into u.av */
67844  assert( pOp->p2<SQLITE_N_BTREE_META );
67845  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67846  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67847  u.av.pDb = &db->aDb[pOp->p1];
67848  assert( u.av.pDb->pBt!=0 );
67849  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
67850  pIn3 = &aMem[pOp->p3];
67851  sqlite3VdbeMemIntegerify(pIn3);
67852  /* See note about index shifting on OP_ReadCookie */
67853  rc = sqlite3BtreeUpdateMeta(u.av.pDb->pBt, pOp->p2, (int)pIn3->u.i);
67854  if( pOp->p2==BTREE_SCHEMA_VERSION ){
67855    /* When the schema cookie changes, record the new cookie internally */
67856    u.av.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
67857    db->flags |= SQLITE_InternChanges;
67858  }else if( pOp->p2==BTREE_FILE_FORMAT ){
67859    /* Record changes in the file format */
67860    u.av.pDb->pSchema->file_format = (u8)pIn3->u.i;
67861  }
67862  if( pOp->p1==1 ){
67863    /* Invalidate all prepared statements whenever the TEMP database
67864    ** schema is changed.  Ticket #1644 */
67865    sqlite3ExpirePreparedStatements(db);
67866    p->expired = 0;
67867  }
67868  break;
67869}
67870
67871/* Opcode: VerifyCookie P1 P2 P3 * *
67872**
67873** Check the value of global database parameter number 0 (the
67874** schema version) and make sure it is equal to P2 and that the
67875** generation counter on the local schema parse equals P3.
67876**
67877** P1 is the database number which is 0 for the main database file
67878** and 1 for the file holding temporary tables and some higher number
67879** for auxiliary databases.
67880**
67881** The cookie changes its value whenever the database schema changes.
67882** This operation is used to detect when that the cookie has changed
67883** and that the current process needs to reread the schema.
67884**
67885** Either a transaction needs to have been started or an OP_Open needs
67886** to be executed (to establish a read lock) before this opcode is
67887** invoked.
67888*/
67889case OP_VerifyCookie: {
67890#if 0  /* local variables moved into u.aw */
67891  int iMeta;
67892  int iGen;
67893  Btree *pBt;
67894#endif /* local variables moved into u.aw */
67895
67896  assert( pOp->p1>=0 && pOp->p1<db->nDb );
67897  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
67898  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
67899  u.aw.pBt = db->aDb[pOp->p1].pBt;
67900  if( u.aw.pBt ){
67901    sqlite3BtreeGetMeta(u.aw.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.aw.iMeta);
67902    u.aw.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
67903  }else{
67904    u.aw.iGen = u.aw.iMeta = 0;
67905  }
67906  if( u.aw.iMeta!=pOp->p2 || u.aw.iGen!=pOp->p3 ){
67907    sqlite3DbFree(db, p->zErrMsg);
67908    p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
67909    /* If the schema-cookie from the database file matches the cookie
67910    ** stored with the in-memory representation of the schema, do
67911    ** not reload the schema from the database file.
67912    **
67913    ** If virtual-tables are in use, this is not just an optimization.
67914    ** Often, v-tables store their data in other SQLite tables, which
67915    ** are queried from within xNext() and other v-table methods using
67916    ** prepared queries. If such a query is out-of-date, we do not want to
67917    ** discard the database schema, as the user code implementing the
67918    ** v-table would have to be ready for the sqlite3_vtab structure itself
67919    ** to be invalidated whenever sqlite3_step() is called from within
67920    ** a v-table method.
67921    */
67922    if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.aw.iMeta ){
67923      sqlite3ResetInternalSchema(db, pOp->p1);
67924    }
67925
67926    p->expired = 1;
67927    rc = SQLITE_SCHEMA;
67928  }
67929  break;
67930}
67931
67932/* Opcode: OpenRead P1 P2 P3 P4 P5
67933**
67934** Open a read-only cursor for the database table whose root page is
67935** P2 in a database file.  The database file is determined by P3.
67936** P3==0 means the main database, P3==1 means the database used for
67937** temporary tables, and P3>1 means used the corresponding attached
67938** database.  Give the new cursor an identifier of P1.  The P1
67939** values need not be contiguous but all P1 values should be small integers.
67940** It is an error for P1 to be negative.
67941**
67942** If P5!=0 then use the content of register P2 as the root page, not
67943** the value of P2 itself.
67944**
67945** There will be a read lock on the database whenever there is an
67946** open cursor.  If the database was unlocked prior to this instruction
67947** then a read lock is acquired as part of this instruction.  A read
67948** lock allows other processes to read the database but prohibits
67949** any other process from modifying the database.  The read lock is
67950** released when all cursors are closed.  If this instruction attempts
67951** to get a read lock but fails, the script terminates with an
67952** SQLITE_BUSY error code.
67953**
67954** The P4 value may be either an integer (P4_INT32) or a pointer to
67955** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
67956** structure, then said structure defines the content and collating
67957** sequence of the index being opened. Otherwise, if P4 is an integer
67958** value, it is set to the number of columns in the table.
67959**
67960** See also OpenWrite.
67961*/
67962/* Opcode: OpenWrite P1 P2 P3 P4 P5
67963**
67964** Open a read/write cursor named P1 on the table or index whose root
67965** page is P2.  Or if P5!=0 use the content of register P2 to find the
67966** root page.
67967**
67968** The P4 value may be either an integer (P4_INT32) or a pointer to
67969** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
67970** structure, then said structure defines the content and collating
67971** sequence of the index being opened. Otherwise, if P4 is an integer
67972** value, it is set to the number of columns in the table, or to the
67973** largest index of any column of the table that is actually used.
67974**
67975** This instruction works just like OpenRead except that it opens the cursor
67976** in read/write mode.  For a given table, there can be one or more read-only
67977** cursors or a single read/write cursor but not both.
67978**
67979** See also OpenRead.
67980*/
67981case OP_OpenRead:
67982case OP_OpenWrite: {
67983#if 0  /* local variables moved into u.ax */
67984  int nField;
67985  KeyInfo *pKeyInfo;
67986  int p2;
67987  int iDb;
67988  int wrFlag;
67989  Btree *pX;
67990  VdbeCursor *pCur;
67991  Db *pDb;
67992#endif /* local variables moved into u.ax */
67993
67994  if( p->expired ){
67995    rc = SQLITE_ABORT;
67996    break;
67997  }
67998
67999  u.ax.nField = 0;
68000  u.ax.pKeyInfo = 0;
68001  u.ax.p2 = pOp->p2;
68002  u.ax.iDb = pOp->p3;
68003  assert( u.ax.iDb>=0 && u.ax.iDb<db->nDb );
68004  assert( (p->btreeMask & (((yDbMask)1)<<u.ax.iDb))!=0 );
68005  u.ax.pDb = &db->aDb[u.ax.iDb];
68006  u.ax.pX = u.ax.pDb->pBt;
68007  assert( u.ax.pX!=0 );
68008  if( pOp->opcode==OP_OpenWrite ){
68009    u.ax.wrFlag = 1;
68010    assert( sqlite3SchemaMutexHeld(db, u.ax.iDb, 0) );
68011    if( u.ax.pDb->pSchema->file_format < p->minWriteFileFormat ){
68012      p->minWriteFileFormat = u.ax.pDb->pSchema->file_format;
68013    }
68014  }else{
68015    u.ax.wrFlag = 0;
68016  }
68017  if( pOp->p5 ){
68018    assert( u.ax.p2>0 );
68019    assert( u.ax.p2<=p->nMem );
68020    pIn2 = &aMem[u.ax.p2];
68021    assert( memIsValid(pIn2) );
68022    assert( (pIn2->flags & MEM_Int)!=0 );
68023    sqlite3VdbeMemIntegerify(pIn2);
68024    u.ax.p2 = (int)pIn2->u.i;
68025    /* The u.ax.p2 value always comes from a prior OP_CreateTable opcode and
68026    ** that opcode will always set the u.ax.p2 value to 2 or more or else fail.
68027    ** If there were a failure, the prepared statement would have halted
68028    ** before reaching this instruction. */
68029    if( NEVER(u.ax.p2<2) ) {
68030      rc = SQLITE_CORRUPT_BKPT;
68031      goto abort_due_to_error;
68032    }
68033  }
68034  if( pOp->p4type==P4_KEYINFO ){
68035    u.ax.pKeyInfo = pOp->p4.pKeyInfo;
68036    u.ax.pKeyInfo->enc = ENC(p->db);
68037    u.ax.nField = u.ax.pKeyInfo->nField+1;
68038  }else if( pOp->p4type==P4_INT32 ){
68039    u.ax.nField = pOp->p4.i;
68040  }
68041  assert( pOp->p1>=0 );
68042  u.ax.pCur = allocateCursor(p, pOp->p1, u.ax.nField, u.ax.iDb, 1);
68043  if( u.ax.pCur==0 ) goto no_mem;
68044  u.ax.pCur->nullRow = 1;
68045  u.ax.pCur->isOrdered = 1;
68046  rc = sqlite3BtreeCursor(u.ax.pX, u.ax.p2, u.ax.wrFlag, u.ax.pKeyInfo, u.ax.pCur->pCursor);
68047  u.ax.pCur->pKeyInfo = u.ax.pKeyInfo;
68048
68049  /* Since it performs no memory allocation or IO, the only value that
68050  ** sqlite3BtreeCursor() may return is SQLITE_OK. */
68051  assert( rc==SQLITE_OK );
68052
68053  /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
68054  ** SQLite used to check if the root-page flags were sane at this point
68055  ** and report database corruption if they were not, but this check has
68056  ** since moved into the btree layer.  */
68057  u.ax.pCur->isTable = pOp->p4type!=P4_KEYINFO;
68058  u.ax.pCur->isIndex = !u.ax.pCur->isTable;
68059  break;
68060}
68061
68062/* Opcode: OpenEphemeral P1 P2 * P4 P5
68063**
68064** Open a new cursor P1 to a transient table.
68065** The cursor is always opened read/write even if
68066** the main database is read-only.  The ephemeral
68067** table is deleted automatically when the cursor is closed.
68068**
68069** P2 is the number of columns in the ephemeral table.
68070** The cursor points to a BTree table if P4==0 and to a BTree index
68071** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
68072** that defines the format of keys in the index.
68073**
68074** This opcode was once called OpenTemp.  But that created
68075** confusion because the term "temp table", might refer either
68076** to a TEMP table at the SQL level, or to a table opened by
68077** this opcode.  Then this opcode was call OpenVirtual.  But
68078** that created confusion with the whole virtual-table idea.
68079**
68080** The P5 parameter can be a mask of the BTREE_* flags defined
68081** in btree.h.  These flags control aspects of the operation of
68082** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
68083** added automatically.
68084*/
68085/* Opcode: OpenAutoindex P1 P2 * P4 *
68086**
68087** This opcode works the same as OP_OpenEphemeral.  It has a
68088** different name to distinguish its use.  Tables created using
68089** by this opcode will be used for automatically created transient
68090** indices in joins.
68091*/
68092case OP_OpenAutoindex:
68093case OP_OpenEphemeral: {
68094#if 0  /* local variables moved into u.ay */
68095  VdbeCursor *pCx;
68096#endif /* local variables moved into u.ay */
68097  static const int vfsFlags =
68098      SQLITE_OPEN_READWRITE |
68099      SQLITE_OPEN_CREATE |
68100      SQLITE_OPEN_EXCLUSIVE |
68101      SQLITE_OPEN_DELETEONCLOSE |
68102      SQLITE_OPEN_TRANSIENT_DB;
68103
68104  assert( pOp->p1>=0 );
68105  u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68106  if( u.ay.pCx==0 ) goto no_mem;
68107  u.ay.pCx->nullRow = 1;
68108  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.ay.pCx->pBt,
68109                        BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
68110  if( rc==SQLITE_OK ){
68111    rc = sqlite3BtreeBeginTrans(u.ay.pCx->pBt, 1);
68112  }
68113  if( rc==SQLITE_OK ){
68114    /* If a transient index is required, create it by calling
68115    ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
68116    ** opening it. If a transient table is required, just use the
68117    ** automatically created table with root-page 1 (an BLOB_INTKEY table).
68118    */
68119    if( pOp->p4.pKeyInfo ){
68120      int pgno;
68121      assert( pOp->p4type==P4_KEYINFO );
68122      rc = sqlite3BtreeCreateTable(u.ay.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
68123      if( rc==SQLITE_OK ){
68124        assert( pgno==MASTER_ROOT+1 );
68125        rc = sqlite3BtreeCursor(u.ay.pCx->pBt, pgno, 1,
68126                                (KeyInfo*)pOp->p4.z, u.ay.pCx->pCursor);
68127        u.ay.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68128        u.ay.pCx->pKeyInfo->enc = ENC(p->db);
68129      }
68130      u.ay.pCx->isTable = 0;
68131    }else{
68132      rc = sqlite3BtreeCursor(u.ay.pCx->pBt, MASTER_ROOT, 1, 0, u.ay.pCx->pCursor);
68133      u.ay.pCx->isTable = 1;
68134    }
68135  }
68136  u.ay.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
68137  u.ay.pCx->isIndex = !u.ay.pCx->isTable;
68138  break;
68139}
68140
68141/* Opcode: OpenSorter P1 P2 * P4 *
68142**
68143** This opcode works like OP_OpenEphemeral except that it opens
68144** a transient index that is specifically designed to sort large
68145** tables using an external merge-sort algorithm.
68146*/
68147case OP_SorterOpen: {
68148#if 0  /* local variables moved into u.az */
68149  VdbeCursor *pCx;
68150#endif /* local variables moved into u.az */
68151#ifndef SQLITE_OMIT_MERGE_SORT
68152  u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68153  if( u.az.pCx==0 ) goto no_mem;
68154  u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68155  u.az.pCx->pKeyInfo->enc = ENC(p->db);
68156  u.az.pCx->isSorter = 1;
68157  rc = sqlite3VdbeSorterInit(db, u.az.pCx);
68158#else
68159  pOp->opcode = OP_OpenEphemeral;
68160  pc--;
68161#endif
68162  break;
68163}
68164
68165/* Opcode: OpenPseudo P1 P2 P3 * *
68166**
68167** Open a new cursor that points to a fake table that contains a single
68168** row of data.  The content of that one row in the content of memory
68169** register P2.  In other words, cursor P1 becomes an alias for the
68170** MEM_Blob content contained in register P2.
68171**
68172** A pseudo-table created by this opcode is used to hold a single
68173** row output from the sorter so that the row can be decomposed into
68174** individual columns using the OP_Column opcode.  The OP_Column opcode
68175** is the only cursor opcode that works with a pseudo-table.
68176**
68177** P3 is the number of fields in the records that will be stored by
68178** the pseudo-table.
68179*/
68180case OP_OpenPseudo: {
68181#if 0  /* local variables moved into u.ba */
68182  VdbeCursor *pCx;
68183#endif /* local variables moved into u.ba */
68184
68185  assert( pOp->p1>=0 );
68186  u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
68187  if( u.ba.pCx==0 ) goto no_mem;
68188  u.ba.pCx->nullRow = 1;
68189  u.ba.pCx->pseudoTableReg = pOp->p2;
68190  u.ba.pCx->isTable = 1;
68191  u.ba.pCx->isIndex = 0;
68192  break;
68193}
68194
68195/* Opcode: Close P1 * * * *
68196**
68197** Close a cursor previously opened as P1.  If P1 is not
68198** currently open, this instruction is a no-op.
68199*/
68200case OP_Close: {
68201  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68202  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
68203  p->apCsr[pOp->p1] = 0;
68204  break;
68205}
68206
68207/* Opcode: SeekGe P1 P2 P3 P4 *
68208**
68209** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68210** use the value in register P3 as the key.  If cursor P1 refers
68211** to an SQL index, then P3 is the first in an array of P4 registers
68212** that are used as an unpacked index key.
68213**
68214** Reposition cursor P1 so that  it points to the smallest entry that
68215** is greater than or equal to the key value. If there are no records
68216** greater than or equal to the key and P2 is not zero, then jump to P2.
68217**
68218** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
68219*/
68220/* Opcode: SeekGt P1 P2 P3 P4 *
68221**
68222** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68223** use the value in register P3 as a key. If cursor P1 refers
68224** to an SQL index, then P3 is the first in an array of P4 registers
68225** that are used as an unpacked index key.
68226**
68227** Reposition cursor P1 so that  it points to the smallest entry that
68228** is greater than the key value. If there are no records greater than
68229** the key and P2 is not zero, then jump to P2.
68230**
68231** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
68232*/
68233/* Opcode: SeekLt P1 P2 P3 P4 *
68234**
68235** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68236** use the value in register P3 as a key. If cursor P1 refers
68237** to an SQL index, then P3 is the first in an array of P4 registers
68238** that are used as an unpacked index key.
68239**
68240** Reposition cursor P1 so that  it points to the largest entry that
68241** is less than the key value. If there are no records less than
68242** the key and P2 is not zero, then jump to P2.
68243**
68244** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
68245*/
68246/* Opcode: SeekLe P1 P2 P3 P4 *
68247**
68248** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
68249** use the value in register P3 as a key. If cursor P1 refers
68250** to an SQL index, then P3 is the first in an array of P4 registers
68251** that are used as an unpacked index key.
68252**
68253** Reposition cursor P1 so that it points to the largest entry that
68254** is less than or equal to the key value. If there are no records
68255** less than or equal to the key and P2 is not zero, then jump to P2.
68256**
68257** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
68258*/
68259case OP_SeekLt:         /* jump, in3 */
68260case OP_SeekLe:         /* jump, in3 */
68261case OP_SeekGe:         /* jump, in3 */
68262case OP_SeekGt: {       /* jump, in3 */
68263#if 0  /* local variables moved into u.bb */
68264  int res;
68265  int oc;
68266  VdbeCursor *pC;
68267  UnpackedRecord r;
68268  int nField;
68269  i64 iKey;      /* The rowid we are to seek to */
68270#endif /* local variables moved into u.bb */
68271
68272  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68273  assert( pOp->p2!=0 );
68274  u.bb.pC = p->apCsr[pOp->p1];
68275  assert( u.bb.pC!=0 );
68276  assert( u.bb.pC->pseudoTableReg==0 );
68277  assert( OP_SeekLe == OP_SeekLt+1 );
68278  assert( OP_SeekGe == OP_SeekLt+2 );
68279  assert( OP_SeekGt == OP_SeekLt+3 );
68280  assert( u.bb.pC->isOrdered );
68281  if( ALWAYS(u.bb.pC->pCursor!=0) ){
68282    u.bb.oc = pOp->opcode;
68283    u.bb.pC->nullRow = 0;
68284    if( u.bb.pC->isTable ){
68285      /* The input value in P3 might be of any type: integer, real, string,
68286      ** blob, or NULL.  But it needs to be an integer before we can do
68287      ** the seek, so covert it. */
68288      pIn3 = &aMem[pOp->p3];
68289      applyNumericAffinity(pIn3);
68290      u.bb.iKey = sqlite3VdbeIntValue(pIn3);
68291      u.bb.pC->rowidIsValid = 0;
68292
68293      /* If the P3 value could not be converted into an integer without
68294      ** loss of information, then special processing is required... */
68295      if( (pIn3->flags & MEM_Int)==0 ){
68296        if( (pIn3->flags & MEM_Real)==0 ){
68297          /* If the P3 value cannot be converted into any kind of a number,
68298          ** then the seek is not possible, so jump to P2 */
68299          pc = pOp->p2 - 1;
68300          break;
68301        }
68302        /* If we reach this point, then the P3 value must be a floating
68303        ** point number. */
68304        assert( (pIn3->flags & MEM_Real)!=0 );
68305
68306        if( u.bb.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bb.iKey || pIn3->r>0) ){
68307          /* The P3 value is too large in magnitude to be expressed as an
68308          ** integer. */
68309          u.bb.res = 1;
68310          if( pIn3->r<0 ){
68311            if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
68312              rc = sqlite3BtreeFirst(u.bb.pC->pCursor, &u.bb.res);
68313              if( rc!=SQLITE_OK ) goto abort_due_to_error;
68314            }
68315          }else{
68316            if( u.bb.oc<=OP_SeekLe ){  assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
68317              rc = sqlite3BtreeLast(u.bb.pC->pCursor, &u.bb.res);
68318              if( rc!=SQLITE_OK ) goto abort_due_to_error;
68319            }
68320          }
68321          if( u.bb.res ){
68322            pc = pOp->p2 - 1;
68323          }
68324          break;
68325        }else if( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekGe ){
68326          /* Use the ceiling() function to convert real->int */
68327          if( pIn3->r > (double)u.bb.iKey ) u.bb.iKey++;
68328        }else{
68329          /* Use the floor() function to convert real->int */
68330          assert( u.bb.oc==OP_SeekLe || u.bb.oc==OP_SeekGt );
68331          if( pIn3->r < (double)u.bb.iKey ) u.bb.iKey--;
68332        }
68333      }
68334      rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, 0, (u64)u.bb.iKey, 0, &u.bb.res);
68335      if( rc!=SQLITE_OK ){
68336        goto abort_due_to_error;
68337      }
68338      if( u.bb.res==0 ){
68339        u.bb.pC->rowidIsValid = 1;
68340        u.bb.pC->lastRowid = u.bb.iKey;
68341      }
68342    }else{
68343      u.bb.nField = pOp->p4.i;
68344      assert( pOp->p4type==P4_INT32 );
68345      assert( u.bb.nField>0 );
68346      u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
68347      u.bb.r.nField = (u16)u.bb.nField;
68348
68349      /* The next line of code computes as follows, only faster:
68350      **   if( u.bb.oc==OP_SeekGt || u.bb.oc==OP_SeekLe ){
68351      **     u.bb.r.flags = UNPACKED_INCRKEY;
68352      **   }else{
68353      **     u.bb.r.flags = 0;
68354      **   }
68355      */
68356      u.bb.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.bb.oc - OP_SeekLt)));
68357      assert( u.bb.oc!=OP_SeekGt || u.bb.r.flags==UNPACKED_INCRKEY );
68358      assert( u.bb.oc!=OP_SeekLe || u.bb.r.flags==UNPACKED_INCRKEY );
68359      assert( u.bb.oc!=OP_SeekGe || u.bb.r.flags==0 );
68360      assert( u.bb.oc!=OP_SeekLt || u.bb.r.flags==0 );
68361
68362      u.bb.r.aMem = &aMem[pOp->p3];
68363#ifdef SQLITE_DEBUG
68364      { int i; for(i=0; i<u.bb.r.nField; i++) assert( memIsValid(&u.bb.r.aMem[i]) ); }
68365#endif
68366      ExpandBlob(u.bb.r.aMem);
68367      rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, &u.bb.r, 0, 0, &u.bb.res);
68368      if( rc!=SQLITE_OK ){
68369        goto abort_due_to_error;
68370      }
68371      u.bb.pC->rowidIsValid = 0;
68372    }
68373    u.bb.pC->deferredMoveto = 0;
68374    u.bb.pC->cacheStatus = CACHE_STALE;
68375#ifdef SQLITE_TEST
68376    sqlite3_search_count++;
68377#endif
68378    if( u.bb.oc>=OP_SeekGe ){  assert( u.bb.oc==OP_SeekGe || u.bb.oc==OP_SeekGt );
68379      if( u.bb.res<0 || (u.bb.res==0 && u.bb.oc==OP_SeekGt) ){
68380        rc = sqlite3BtreeNext(u.bb.pC->pCursor, &u.bb.res);
68381        if( rc!=SQLITE_OK ) goto abort_due_to_error;
68382        u.bb.pC->rowidIsValid = 0;
68383      }else{
68384        u.bb.res = 0;
68385      }
68386    }else{
68387      assert( u.bb.oc==OP_SeekLt || u.bb.oc==OP_SeekLe );
68388      if( u.bb.res>0 || (u.bb.res==0 && u.bb.oc==OP_SeekLt) ){
68389        rc = sqlite3BtreePrevious(u.bb.pC->pCursor, &u.bb.res);
68390        if( rc!=SQLITE_OK ) goto abort_due_to_error;
68391        u.bb.pC->rowidIsValid = 0;
68392      }else{
68393        /* u.bb.res might be negative because the table is empty.  Check to
68394        ** see if this is the case.
68395        */
68396        u.bb.res = sqlite3BtreeEof(u.bb.pC->pCursor);
68397      }
68398    }
68399    assert( pOp->p2>0 );
68400    if( u.bb.res ){
68401      pc = pOp->p2 - 1;
68402    }
68403  }else{
68404    /* This happens when attempting to open the sqlite3_master table
68405    ** for read access returns SQLITE_EMPTY. In this case always
68406    ** take the jump (since there are no records in the table).
68407    */
68408    pc = pOp->p2 - 1;
68409  }
68410  break;
68411}
68412
68413/* Opcode: Seek P1 P2 * * *
68414**
68415** P1 is an open table cursor and P2 is a rowid integer.  Arrange
68416** for P1 to move so that it points to the rowid given by P2.
68417**
68418** This is actually a deferred seek.  Nothing actually happens until
68419** the cursor is used to read a record.  That way, if no reads
68420** occur, no unnecessary I/O happens.
68421*/
68422case OP_Seek: {    /* in2 */
68423#if 0  /* local variables moved into u.bc */
68424  VdbeCursor *pC;
68425#endif /* local variables moved into u.bc */
68426
68427  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68428  u.bc.pC = p->apCsr[pOp->p1];
68429  assert( u.bc.pC!=0 );
68430  if( ALWAYS(u.bc.pC->pCursor!=0) ){
68431    assert( u.bc.pC->isTable );
68432    u.bc.pC->nullRow = 0;
68433    pIn2 = &aMem[pOp->p2];
68434    u.bc.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
68435    u.bc.pC->rowidIsValid = 0;
68436    u.bc.pC->deferredMoveto = 1;
68437  }
68438  break;
68439}
68440
68441
68442/* Opcode: Found P1 P2 P3 P4 *
68443**
68444** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68445** P4>0 then register P3 is the first of P4 registers that form an unpacked
68446** record.
68447**
68448** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68449** is a prefix of any entry in P1 then a jump is made to P2 and
68450** P1 is left pointing at the matching entry.
68451*/
68452/* Opcode: NotFound P1 P2 P3 P4 *
68453**
68454** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68455** P4>0 then register P3 is the first of P4 registers that form an unpacked
68456** record.
68457**
68458** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68459** is not the prefix of any entry in P1 then a jump is made to P2.  If P1
68460** does contain an entry whose prefix matches the P3/P4 record then control
68461** falls through to the next instruction and P1 is left pointing at the
68462** matching entry.
68463**
68464** See also: Found, NotExists, IsUnique
68465*/
68466case OP_NotFound:       /* jump, in3 */
68467case OP_Found: {        /* jump, in3 */
68468#if 0  /* local variables moved into u.bd */
68469  int alreadyExists;
68470  VdbeCursor *pC;
68471  int res;
68472  char *pFree;
68473  UnpackedRecord *pIdxKey;
68474  UnpackedRecord r;
68475  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
68476#endif /* local variables moved into u.bd */
68477
68478#ifdef SQLITE_TEST
68479  sqlite3_found_count++;
68480#endif
68481
68482  u.bd.alreadyExists = 0;
68483  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68484  assert( pOp->p4type==P4_INT32 );
68485  u.bd.pC = p->apCsr[pOp->p1];
68486  assert( u.bd.pC!=0 );
68487  pIn3 = &aMem[pOp->p3];
68488  if( ALWAYS(u.bd.pC->pCursor!=0) ){
68489
68490    assert( u.bd.pC->isTable==0 );
68491    if( pOp->p4.i>0 ){
68492      u.bd.r.pKeyInfo = u.bd.pC->pKeyInfo;
68493      u.bd.r.nField = (u16)pOp->p4.i;
68494      u.bd.r.aMem = pIn3;
68495#ifdef SQLITE_DEBUG
68496      { int i; for(i=0; i<u.bd.r.nField; i++) assert( memIsValid(&u.bd.r.aMem[i]) ); }
68497#endif
68498      u.bd.r.flags = UNPACKED_PREFIX_MATCH;
68499      u.bd.pIdxKey = &u.bd.r;
68500    }else{
68501      u.bd.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
68502          u.bd.pC->pKeyInfo, u.bd.aTempRec, sizeof(u.bd.aTempRec), &u.bd.pFree
68503      );
68504      if( u.bd.pIdxKey==0 ) goto no_mem;
68505      assert( pIn3->flags & MEM_Blob );
68506      assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
68507      sqlite3VdbeRecordUnpack(u.bd.pC->pKeyInfo, pIn3->n, pIn3->z, u.bd.pIdxKey);
68508      u.bd.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
68509    }
68510    rc = sqlite3BtreeMovetoUnpacked(u.bd.pC->pCursor, u.bd.pIdxKey, 0, 0, &u.bd.res);
68511    if( pOp->p4.i==0 ){
68512      sqlite3DbFree(db, u.bd.pFree);
68513    }
68514    if( rc!=SQLITE_OK ){
68515      break;
68516    }
68517    u.bd.alreadyExists = (u.bd.res==0);
68518    u.bd.pC->deferredMoveto = 0;
68519    u.bd.pC->cacheStatus = CACHE_STALE;
68520  }
68521  if( pOp->opcode==OP_Found ){
68522    if( u.bd.alreadyExists ) pc = pOp->p2 - 1;
68523  }else{
68524    if( !u.bd.alreadyExists ) pc = pOp->p2 - 1;
68525  }
68526  break;
68527}
68528
68529/* Opcode: IsUnique P1 P2 P3 P4 *
68530**
68531** Cursor P1 is open on an index b-tree - that is to say, a btree which
68532** no data and where the key are records generated by OP_MakeRecord with
68533** the list field being the integer ROWID of the entry that the index
68534** entry refers to.
68535**
68536** The P3 register contains an integer record number. Call this record
68537** number R. Register P4 is the first in a set of N contiguous registers
68538** that make up an unpacked index key that can be used with cursor P1.
68539** The value of N can be inferred from the cursor. N includes the rowid
68540** value appended to the end of the index record. This rowid value may
68541** or may not be the same as R.
68542**
68543** If any of the N registers beginning with register P4 contains a NULL
68544** value, jump immediately to P2.
68545**
68546** Otherwise, this instruction checks if cursor P1 contains an entry
68547** where the first (N-1) fields match but the rowid value at the end
68548** of the index entry is not R. If there is no such entry, control jumps
68549** to instruction P2. Otherwise, the rowid of the conflicting index
68550** entry is copied to register P3 and control falls through to the next
68551** instruction.
68552**
68553** See also: NotFound, NotExists, Found
68554*/
68555case OP_IsUnique: {        /* jump, in3 */
68556#if 0  /* local variables moved into u.be */
68557  u16 ii;
68558  VdbeCursor *pCx;
68559  BtCursor *pCrsr;
68560  u16 nField;
68561  Mem *aMx;
68562  UnpackedRecord r;                  /* B-Tree index search key */
68563  i64 R;                             /* Rowid stored in register P3 */
68564#endif /* local variables moved into u.be */
68565
68566  pIn3 = &aMem[pOp->p3];
68567  u.be.aMx = &aMem[pOp->p4.i];
68568  /* Assert that the values of parameters P1 and P4 are in range. */
68569  assert( pOp->p4type==P4_INT32 );
68570  assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
68571  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68572
68573  /* Find the index cursor. */
68574  u.be.pCx = p->apCsr[pOp->p1];
68575  assert( u.be.pCx->deferredMoveto==0 );
68576  u.be.pCx->seekResult = 0;
68577  u.be.pCx->cacheStatus = CACHE_STALE;
68578  u.be.pCrsr = u.be.pCx->pCursor;
68579
68580  /* If any of the values are NULL, take the jump. */
68581  u.be.nField = u.be.pCx->pKeyInfo->nField;
68582  for(u.be.ii=0; u.be.ii<u.be.nField; u.be.ii++){
68583    if( u.be.aMx[u.be.ii].flags & MEM_Null ){
68584      pc = pOp->p2 - 1;
68585      u.be.pCrsr = 0;
68586      break;
68587    }
68588  }
68589  assert( (u.be.aMx[u.be.nField].flags & MEM_Null)==0 );
68590
68591  if( u.be.pCrsr!=0 ){
68592    /* Populate the index search key. */
68593    u.be.r.pKeyInfo = u.be.pCx->pKeyInfo;
68594    u.be.r.nField = u.be.nField + 1;
68595    u.be.r.flags = UNPACKED_PREFIX_SEARCH;
68596    u.be.r.aMem = u.be.aMx;
68597#ifdef SQLITE_DEBUG
68598    { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
68599#endif
68600
68601    /* Extract the value of u.be.R from register P3. */
68602    sqlite3VdbeMemIntegerify(pIn3);
68603    u.be.R = pIn3->u.i;
68604
68605    /* Search the B-Tree index. If no conflicting record is found, jump
68606    ** to P2. Otherwise, copy the rowid of the conflicting record to
68607    ** register P3 and fall through to the next instruction.  */
68608    rc = sqlite3BtreeMovetoUnpacked(u.be.pCrsr, &u.be.r, 0, 0, &u.be.pCx->seekResult);
68609    if( (u.be.r.flags & UNPACKED_PREFIX_SEARCH) || u.be.r.rowid==u.be.R ){
68610      pc = pOp->p2 - 1;
68611    }else{
68612      pIn3->u.i = u.be.r.rowid;
68613    }
68614  }
68615  break;
68616}
68617
68618/* Opcode: NotExists P1 P2 P3 * *
68619**
68620** Use the content of register P3 as an integer key.  If a record
68621** with that key does not exist in table of P1, then jump to P2.
68622** If the record does exist, then fall through.  The cursor is left
68623** pointing to the record if it exists.
68624**
68625** The difference between this operation and NotFound is that this
68626** operation assumes the key is an integer and that P1 is a table whereas
68627** NotFound assumes key is a blob constructed from MakeRecord and
68628** P1 is an index.
68629**
68630** See also: Found, NotFound, IsUnique
68631*/
68632case OP_NotExists: {        /* jump, in3 */
68633#if 0  /* local variables moved into u.bf */
68634  VdbeCursor *pC;
68635  BtCursor *pCrsr;
68636  int res;
68637  u64 iKey;
68638#endif /* local variables moved into u.bf */
68639
68640  pIn3 = &aMem[pOp->p3];
68641  assert( pIn3->flags & MEM_Int );
68642  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68643  u.bf.pC = p->apCsr[pOp->p1];
68644  assert( u.bf.pC!=0 );
68645  assert( u.bf.pC->isTable );
68646  assert( u.bf.pC->pseudoTableReg==0 );
68647  u.bf.pCrsr = u.bf.pC->pCursor;
68648  if( ALWAYS(u.bf.pCrsr!=0) ){
68649    u.bf.res = 0;
68650    u.bf.iKey = pIn3->u.i;
68651    rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, 0, u.bf.iKey, 0, &u.bf.res);
68652    u.bf.pC->lastRowid = pIn3->u.i;
68653    u.bf.pC->rowidIsValid = u.bf.res==0 ?1:0;
68654    u.bf.pC->nullRow = 0;
68655    u.bf.pC->cacheStatus = CACHE_STALE;
68656    u.bf.pC->deferredMoveto = 0;
68657    if( u.bf.res!=0 ){
68658      pc = pOp->p2 - 1;
68659      assert( u.bf.pC->rowidIsValid==0 );
68660    }
68661    u.bf.pC->seekResult = u.bf.res;
68662  }else{
68663    /* This happens when an attempt to open a read cursor on the
68664    ** sqlite_master table returns SQLITE_EMPTY.
68665    */
68666    pc = pOp->p2 - 1;
68667    assert( u.bf.pC->rowidIsValid==0 );
68668    u.bf.pC->seekResult = 0;
68669  }
68670  break;
68671}
68672
68673/* Opcode: Sequence P1 P2 * * *
68674**
68675** Find the next available sequence number for cursor P1.
68676** Write the sequence number into register P2.
68677** The sequence number on the cursor is incremented after this
68678** instruction.
68679*/
68680case OP_Sequence: {           /* out2-prerelease */
68681  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68682  assert( p->apCsr[pOp->p1]!=0 );
68683  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
68684  break;
68685}
68686
68687
68688/* Opcode: NewRowid P1 P2 P3 * *
68689**
68690** Get a new integer record number (a.k.a "rowid") used as the key to a table.
68691** The record number is not previously used as a key in the database
68692** table that cursor P1 points to.  The new record number is written
68693** written to register P2.
68694**
68695** If P3>0 then P3 is a register in the root frame of this VDBE that holds
68696** the largest previously generated record number. No new record numbers are
68697** allowed to be less than this value. When this value reaches its maximum,
68698** an SQLITE_FULL error is generated. The P3 register is updated with the '
68699** generated record number. This P3 mechanism is used to help implement the
68700** AUTOINCREMENT feature.
68701*/
68702case OP_NewRowid: {           /* out2-prerelease */
68703#if 0  /* local variables moved into u.bg */
68704  i64 v;                 /* The new rowid */
68705  VdbeCursor *pC;        /* Cursor of table to get the new rowid */
68706  int res;               /* Result of an sqlite3BtreeLast() */
68707  int cnt;               /* Counter to limit the number of searches */
68708  Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
68709  VdbeFrame *pFrame;     /* Root frame of VDBE */
68710#endif /* local variables moved into u.bg */
68711
68712  u.bg.v = 0;
68713  u.bg.res = 0;
68714  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68715  u.bg.pC = p->apCsr[pOp->p1];
68716  assert( u.bg.pC!=0 );
68717  if( NEVER(u.bg.pC->pCursor==0) ){
68718    /* The zero initialization above is all that is needed */
68719  }else{
68720    /* The next rowid or record number (different terms for the same
68721    ** thing) is obtained in a two-step algorithm.
68722    **
68723    ** First we attempt to find the largest existing rowid and add one
68724    ** to that.  But if the largest existing rowid is already the maximum
68725    ** positive integer, we have to fall through to the second
68726    ** probabilistic algorithm
68727    **
68728    ** The second algorithm is to select a rowid at random and see if
68729    ** it already exists in the table.  If it does not exist, we have
68730    ** succeeded.  If the random rowid does exist, we select a new one
68731    ** and try again, up to 100 times.
68732    */
68733    assert( u.bg.pC->isTable );
68734
68735#ifdef SQLITE_32BIT_ROWID
68736#   define MAX_ROWID 0x7fffffff
68737#else
68738    /* Some compilers complain about constants of the form 0x7fffffffffffffff.
68739    ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
68740    ** to provide the constant while making all compilers happy.
68741    */
68742#   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
68743#endif
68744
68745    if( !u.bg.pC->useRandomRowid ){
68746      u.bg.v = sqlite3BtreeGetCachedRowid(u.bg.pC->pCursor);
68747      if( u.bg.v==0 ){
68748        rc = sqlite3BtreeLast(u.bg.pC->pCursor, &u.bg.res);
68749        if( rc!=SQLITE_OK ){
68750          goto abort_due_to_error;
68751        }
68752        if( u.bg.res ){
68753          u.bg.v = 1;   /* IMP: R-61914-48074 */
68754        }else{
68755          assert( sqlite3BtreeCursorIsValid(u.bg.pC->pCursor) );
68756          rc = sqlite3BtreeKeySize(u.bg.pC->pCursor, &u.bg.v);
68757          assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
68758          if( u.bg.v>=MAX_ROWID ){
68759            u.bg.pC->useRandomRowid = 1;
68760          }else{
68761            u.bg.v++;   /* IMP: R-29538-34987 */
68762          }
68763        }
68764      }
68765
68766#ifndef SQLITE_OMIT_AUTOINCREMENT
68767      if( pOp->p3 ){
68768        /* Assert that P3 is a valid memory cell. */
68769        assert( pOp->p3>0 );
68770        if( p->pFrame ){
68771          for(u.bg.pFrame=p->pFrame; u.bg.pFrame->pParent; u.bg.pFrame=u.bg.pFrame->pParent);
68772          /* Assert that P3 is a valid memory cell. */
68773          assert( pOp->p3<=u.bg.pFrame->nMem );
68774          u.bg.pMem = &u.bg.pFrame->aMem[pOp->p3];
68775        }else{
68776          /* Assert that P3 is a valid memory cell. */
68777          assert( pOp->p3<=p->nMem );
68778          u.bg.pMem = &aMem[pOp->p3];
68779          memAboutToChange(p, u.bg.pMem);
68780        }
68781        assert( memIsValid(u.bg.pMem) );
68782
68783        REGISTER_TRACE(pOp->p3, u.bg.pMem);
68784        sqlite3VdbeMemIntegerify(u.bg.pMem);
68785        assert( (u.bg.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
68786        if( u.bg.pMem->u.i==MAX_ROWID || u.bg.pC->useRandomRowid ){
68787          rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
68788          goto abort_due_to_error;
68789        }
68790        if( u.bg.v<u.bg.pMem->u.i+1 ){
68791          u.bg.v = u.bg.pMem->u.i + 1;
68792        }
68793        u.bg.pMem->u.i = u.bg.v;
68794      }
68795#endif
68796
68797      sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, u.bg.v<MAX_ROWID ? u.bg.v+1 : 0);
68798    }
68799    if( u.bg.pC->useRandomRowid ){
68800      /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
68801      ** largest possible integer (9223372036854775807) then the database
68802      ** engine starts picking positive candidate ROWIDs at random until
68803      ** it finds one that is not previously used. */
68804      assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
68805                             ** an AUTOINCREMENT table. */
68806      /* on the first attempt, simply do one more than previous */
68807      u.bg.v = lastRowid;
68808      u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68809      u.bg.v++; /* ensure non-zero */
68810      u.bg.cnt = 0;
68811      while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bg.pC->pCursor, 0, (u64)u.bg.v,
68812                                                 0, &u.bg.res))==SQLITE_OK)
68813            && (u.bg.res==0)
68814            && (++u.bg.cnt<100)){
68815        /* collision - try another random rowid */
68816        sqlite3_randomness(sizeof(u.bg.v), &u.bg.v);
68817        if( u.bg.cnt<5 ){
68818          /* try "small" random rowids for the initial attempts */
68819          u.bg.v &= 0xffffff;
68820        }else{
68821          u.bg.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
68822        }
68823        u.bg.v++; /* ensure non-zero */
68824      }
68825      if( rc==SQLITE_OK && u.bg.res==0 ){
68826        rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
68827        goto abort_due_to_error;
68828      }
68829      assert( u.bg.v>0 );  /* EV: R-40812-03570 */
68830    }
68831    u.bg.pC->rowidIsValid = 0;
68832    u.bg.pC->deferredMoveto = 0;
68833    u.bg.pC->cacheStatus = CACHE_STALE;
68834  }
68835  pOut->u.i = u.bg.v;
68836  break;
68837}
68838
68839/* Opcode: Insert P1 P2 P3 P4 P5
68840**
68841** Write an entry into the table of cursor P1.  A new entry is
68842** created if it doesn't already exist or the data for an existing
68843** entry is overwritten.  The data is the value MEM_Blob stored in register
68844** number P2. The key is stored in register P3. The key must
68845** be a MEM_Int.
68846**
68847** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
68848** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
68849** then rowid is stored for subsequent return by the
68850** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
68851**
68852** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
68853** the last seek operation (OP_NotExists) was a success, then this
68854** operation will not attempt to find the appropriate row before doing
68855** the insert but will instead overwrite the row that the cursor is
68856** currently pointing to.  Presumably, the prior OP_NotExists opcode
68857** has already positioned the cursor correctly.  This is an optimization
68858** that boosts performance by avoiding redundant seeks.
68859**
68860** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
68861** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
68862** is part of an INSERT operation.  The difference is only important to
68863** the update hook.
68864**
68865** Parameter P4 may point to a string containing the table-name, or
68866** may be NULL. If it is not NULL, then the update-hook
68867** (sqlite3.xUpdateCallback) is invoked following a successful insert.
68868**
68869** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
68870** allocated, then ownership of P2 is transferred to the pseudo-cursor
68871** and register P2 becomes ephemeral.  If the cursor is changed, the
68872** value of register P2 will then change.  Make sure this does not
68873** cause any problems.)
68874**
68875** This instruction only works on tables.  The equivalent instruction
68876** for indices is OP_IdxInsert.
68877*/
68878/* Opcode: InsertInt P1 P2 P3 P4 P5
68879**
68880** This works exactly like OP_Insert except that the key is the
68881** integer value P3, not the value of the integer stored in register P3.
68882*/
68883case OP_Insert:
68884case OP_InsertInt: {
68885#if 0  /* local variables moved into u.bh */
68886  Mem *pData;       /* MEM cell holding data for the record to be inserted */
68887  Mem *pKey;        /* MEM cell holding key  for the record */
68888  i64 iKey;         /* The integer ROWID or key for the record to be inserted */
68889  VdbeCursor *pC;   /* Cursor to table into which insert is written */
68890  int nZero;        /* Number of zero-bytes to append */
68891  int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
68892  const char *zDb;  /* database name - used by the update hook */
68893  const char *zTbl; /* Table name - used by the opdate hook */
68894  int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
68895#endif /* local variables moved into u.bh */
68896
68897  u.bh.pData = &aMem[pOp->p2];
68898  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68899  assert( memIsValid(u.bh.pData) );
68900  u.bh.pC = p->apCsr[pOp->p1];
68901  assert( u.bh.pC!=0 );
68902  assert( u.bh.pC->pCursor!=0 );
68903  assert( u.bh.pC->pseudoTableReg==0 );
68904  assert( u.bh.pC->isTable );
68905  REGISTER_TRACE(pOp->p2, u.bh.pData);
68906
68907  if( pOp->opcode==OP_Insert ){
68908    u.bh.pKey = &aMem[pOp->p3];
68909    assert( u.bh.pKey->flags & MEM_Int );
68910    assert( memIsValid(u.bh.pKey) );
68911    REGISTER_TRACE(pOp->p3, u.bh.pKey);
68912    u.bh.iKey = u.bh.pKey->u.i;
68913  }else{
68914    assert( pOp->opcode==OP_InsertInt );
68915    u.bh.iKey = pOp->p3;
68916  }
68917
68918  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
68919  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bh.iKey;
68920  if( u.bh.pData->flags & MEM_Null ){
68921    u.bh.pData->z = 0;
68922    u.bh.pData->n = 0;
68923  }else{
68924    assert( u.bh.pData->flags & (MEM_Blob|MEM_Str) );
68925  }
68926  u.bh.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bh.pC->seekResult : 0);
68927  if( u.bh.pData->flags & MEM_Zero ){
68928    u.bh.nZero = u.bh.pData->u.nZero;
68929  }else{
68930    u.bh.nZero = 0;
68931  }
68932  sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, 0);
68933  rc = sqlite3BtreeInsert(u.bh.pC->pCursor, 0, u.bh.iKey,
68934                          u.bh.pData->z, u.bh.pData->n, u.bh.nZero,
68935                          pOp->p5 & OPFLAG_APPEND, u.bh.seekResult
68936  );
68937  u.bh.pC->rowidIsValid = 0;
68938  u.bh.pC->deferredMoveto = 0;
68939  u.bh.pC->cacheStatus = CACHE_STALE;
68940
68941  /* Invoke the update-hook if required. */
68942  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
68943    u.bh.zDb = db->aDb[u.bh.pC->iDb].zName;
68944    u.bh.zTbl = pOp->p4.z;
68945    u.bh.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
68946    assert( u.bh.pC->isTable );
68947    db->xUpdateCallback(db->pUpdateArg, u.bh.op, u.bh.zDb, u.bh.zTbl, u.bh.iKey);
68948    assert( u.bh.pC->iDb>=0 );
68949  }
68950  break;
68951}
68952
68953/* Opcode: Delete P1 P2 * P4 *
68954**
68955** Delete the record at which the P1 cursor is currently pointing.
68956**
68957** The cursor will be left pointing at either the next or the previous
68958** record in the table. If it is left pointing at the next record, then
68959** the next Next instruction will be a no-op.  Hence it is OK to delete
68960** a record from within an Next loop.
68961**
68962** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
68963** incremented (otherwise not).
68964**
68965** P1 must not be pseudo-table.  It has to be a real table with
68966** multiple rows.
68967**
68968** If P4 is not NULL, then it is the name of the table that P1 is
68969** pointing to.  The update hook will be invoked, if it exists.
68970** If P4 is not NULL then the P1 cursor must have been positioned
68971** using OP_NotFound prior to invoking this opcode.
68972*/
68973case OP_Delete: {
68974#if 0  /* local variables moved into u.bi */
68975  i64 iKey;
68976  VdbeCursor *pC;
68977#endif /* local variables moved into u.bi */
68978
68979  u.bi.iKey = 0;
68980  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68981  u.bi.pC = p->apCsr[pOp->p1];
68982  assert( u.bi.pC!=0 );
68983  assert( u.bi.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
68984
68985  /* If the update-hook will be invoked, set u.bi.iKey to the rowid of the
68986  ** row being deleted.
68987  */
68988  if( db->xUpdateCallback && pOp->p4.z ){
68989    assert( u.bi.pC->isTable );
68990    assert( u.bi.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
68991    u.bi.iKey = u.bi.pC->lastRowid;
68992  }
68993
68994  /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
68995  ** OP_Column on the same table without any intervening operations that
68996  ** might move or invalidate the cursor.  Hence cursor u.bi.pC is always pointing
68997  ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
68998  ** below is always a no-op and cannot fail.  We will run it anyhow, though,
68999  ** to guard against future changes to the code generator.
69000  **/
69001  assert( u.bi.pC->deferredMoveto==0 );
69002  rc = sqlite3VdbeCursorMoveto(u.bi.pC);
69003  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69004
69005  sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
69006  rc = sqlite3BtreeDelete(u.bi.pC->pCursor);
69007  u.bi.pC->cacheStatus = CACHE_STALE;
69008
69009  /* Invoke the update-hook if required. */
69010  if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69011    const char *zDb = db->aDb[u.bi.pC->iDb].zName;
69012    const char *zTbl = pOp->p4.z;
69013    db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bi.iKey);
69014    assert( u.bi.pC->iDb>=0 );
69015  }
69016  if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
69017  break;
69018}
69019/* Opcode: ResetCount * * * * *
69020**
69021** The value of the change counter is copied to the database handle
69022** change counter (returned by subsequent calls to sqlite3_changes()).
69023** Then the VMs internal change counter resets to 0.
69024** This is used by trigger programs.
69025*/
69026case OP_ResetCount: {
69027  sqlite3VdbeSetChanges(db, p->nChange);
69028  p->nChange = 0;
69029  break;
69030}
69031
69032/* Opcode: SorterCompare P1 P2 P3
69033**
69034** P1 is a sorter cursor. This instruction compares the record blob in
69035** register P3 with the entry that the sorter cursor currently points to.
69036** If, excluding the rowid fields at the end, the two records are a match,
69037** fall through to the next instruction. Otherwise, jump to instruction P2.
69038*/
69039case OP_SorterCompare: {
69040#if 0  /* local variables moved into u.bj */
69041  VdbeCursor *pC;
69042  int res;
69043#endif /* local variables moved into u.bj */
69044
69045  u.bj.pC = p->apCsr[pOp->p1];
69046  assert( isSorter(u.bj.pC) );
69047  pIn3 = &aMem[pOp->p3];
69048  rc = sqlite3VdbeSorterCompare(u.bj.pC, pIn3, &u.bj.res);
69049  if( u.bj.res ){
69050    pc = pOp->p2-1;
69051  }
69052  break;
69053};
69054
69055/* Opcode: SorterData P1 P2 * * *
69056**
69057** Write into register P2 the current sorter data for sorter cursor P1.
69058*/
69059case OP_SorterData: {
69060#if 0  /* local variables moved into u.bk */
69061  VdbeCursor *pC;
69062#endif /* local variables moved into u.bk */
69063#ifndef SQLITE_OMIT_MERGE_SORT
69064  pOut = &aMem[pOp->p2];
69065  u.bk.pC = p->apCsr[pOp->p1];
69066  assert( u.bk.pC->isSorter );
69067  rc = sqlite3VdbeSorterRowkey(u.bk.pC, pOut);
69068#else
69069  pOp->opcode = OP_RowKey;
69070  pc--;
69071#endif
69072  break;
69073}
69074
69075/* Opcode: RowData P1 P2 * * *
69076**
69077** Write into register P2 the complete row data for cursor P1.
69078** There is no interpretation of the data.
69079** It is just copied onto the P2 register exactly as
69080** it is found in the database file.
69081**
69082** If the P1 cursor must be pointing to a valid row (not a NULL row)
69083** of a real table, not a pseudo-table.
69084*/
69085/* Opcode: RowKey P1 P2 * * *
69086**
69087** Write into register P2 the complete row key for cursor P1.
69088** There is no interpretation of the data.
69089** The key is copied onto the P3 register exactly as
69090** it is found in the database file.
69091**
69092** If the P1 cursor must be pointing to a valid row (not a NULL row)
69093** of a real table, not a pseudo-table.
69094*/
69095case OP_RowKey:
69096case OP_RowData: {
69097#if 0  /* local variables moved into u.bl */
69098  VdbeCursor *pC;
69099  BtCursor *pCrsr;
69100  u32 n;
69101  i64 n64;
69102#endif /* local variables moved into u.bl */
69103
69104  pOut = &aMem[pOp->p2];
69105  memAboutToChange(p, pOut);
69106
69107  /* Note that RowKey and RowData are really exactly the same instruction */
69108  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69109  u.bl.pC = p->apCsr[pOp->p1];
69110  assert( u.bl.pC->isSorter==0 );
69111  assert( u.bl.pC->isTable || pOp->opcode!=OP_RowData );
69112  assert( u.bl.pC->isIndex || pOp->opcode==OP_RowData );
69113  assert( u.bl.pC!=0 );
69114  assert( u.bl.pC->nullRow==0 );
69115  assert( u.bl.pC->pseudoTableReg==0 );
69116  assert( !u.bl.pC->isSorter );
69117  assert( u.bl.pC->pCursor!=0 );
69118  u.bl.pCrsr = u.bl.pC->pCursor;
69119  assert( sqlite3BtreeCursorIsValid(u.bl.pCrsr) );
69120
69121  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
69122  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
69123  ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
69124  ** a no-op and can never fail.  But we leave it in place as a safety.
69125  */
69126  assert( u.bl.pC->deferredMoveto==0 );
69127  rc = sqlite3VdbeCursorMoveto(u.bl.pC);
69128  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69129
69130  if( u.bl.pC->isIndex ){
69131    assert( !u.bl.pC->isTable );
69132    VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bl.pCrsr, &u.bl.n64);
69133    assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
69134    if( u.bl.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
69135      goto too_big;
69136    }
69137    u.bl.n = (u32)u.bl.n64;
69138  }else{
69139    VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bl.pCrsr, &u.bl.n);
69140    assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
69141    if( u.bl.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
69142      goto too_big;
69143    }
69144  }
69145  if( sqlite3VdbeMemGrow(pOut, u.bl.n, 0) ){
69146    goto no_mem;
69147  }
69148  pOut->n = u.bl.n;
69149  MemSetTypeFlag(pOut, MEM_Blob);
69150  if( u.bl.pC->isIndex ){
69151    rc = sqlite3BtreeKey(u.bl.pCrsr, 0, u.bl.n, pOut->z);
69152  }else{
69153    rc = sqlite3BtreeData(u.bl.pCrsr, 0, u.bl.n, pOut->z);
69154  }
69155  pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
69156  UPDATE_MAX_BLOBSIZE(pOut);
69157  break;
69158}
69159
69160/* Opcode: Rowid P1 P2 * * *
69161**
69162** Store in register P2 an integer which is the key of the table entry that
69163** P1 is currently point to.
69164**
69165** P1 can be either an ordinary table or a virtual table.  There used to
69166** be a separate OP_VRowid opcode for use with virtual tables, but this
69167** one opcode now works for both table types.
69168*/
69169case OP_Rowid: {                 /* out2-prerelease */
69170#if 0  /* local variables moved into u.bm */
69171  VdbeCursor *pC;
69172  i64 v;
69173  sqlite3_vtab *pVtab;
69174  const sqlite3_module *pModule;
69175#endif /* local variables moved into u.bm */
69176
69177  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69178  u.bm.pC = p->apCsr[pOp->p1];
69179  assert( u.bm.pC!=0 );
69180  assert( u.bm.pC->pseudoTableReg==0 );
69181  if( u.bm.pC->nullRow ){
69182    pOut->flags = MEM_Null;
69183    break;
69184  }else if( u.bm.pC->deferredMoveto ){
69185    u.bm.v = u.bm.pC->movetoTarget;
69186#ifndef SQLITE_OMIT_VIRTUALTABLE
69187  }else if( u.bm.pC->pVtabCursor ){
69188    u.bm.pVtab = u.bm.pC->pVtabCursor->pVtab;
69189    u.bm.pModule = u.bm.pVtab->pModule;
69190    assert( u.bm.pModule->xRowid );
69191    rc = u.bm.pModule->xRowid(u.bm.pC->pVtabCursor, &u.bm.v);
69192    importVtabErrMsg(p, u.bm.pVtab);
69193#endif /* SQLITE_OMIT_VIRTUALTABLE */
69194  }else{
69195    assert( u.bm.pC->pCursor!=0 );
69196    rc = sqlite3VdbeCursorMoveto(u.bm.pC);
69197    if( rc ) goto abort_due_to_error;
69198    if( u.bm.pC->rowidIsValid ){
69199      u.bm.v = u.bm.pC->lastRowid;
69200    }else{
69201      rc = sqlite3BtreeKeySize(u.bm.pC->pCursor, &u.bm.v);
69202      assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
69203    }
69204  }
69205  pOut->u.i = u.bm.v;
69206  break;
69207}
69208
69209/* Opcode: NullRow P1 * * * *
69210**
69211** Move the cursor P1 to a null row.  Any OP_Column operations
69212** that occur while the cursor is on the null row will always
69213** write a NULL.
69214*/
69215case OP_NullRow: {
69216#if 0  /* local variables moved into u.bn */
69217  VdbeCursor *pC;
69218#endif /* local variables moved into u.bn */
69219
69220  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69221  u.bn.pC = p->apCsr[pOp->p1];
69222  assert( u.bn.pC!=0 );
69223  u.bn.pC->nullRow = 1;
69224  u.bn.pC->rowidIsValid = 0;
69225  assert( u.bn.pC->pCursor || u.bn.pC->pVtabCursor );
69226  if( u.bn.pC->pCursor ){
69227    sqlite3BtreeClearCursor(u.bn.pC->pCursor);
69228  }
69229  break;
69230}
69231
69232/* Opcode: Last P1 P2 * * *
69233**
69234** The next use of the Rowid or Column or Next instruction for P1
69235** will refer to the last entry in the database table or index.
69236** If the table or index is empty and P2>0, then jump immediately to P2.
69237** If P2 is 0 or if the table or index is not empty, fall through
69238** to the following instruction.
69239*/
69240case OP_Last: {        /* jump */
69241#if 0  /* local variables moved into u.bo */
69242  VdbeCursor *pC;
69243  BtCursor *pCrsr;
69244  int res;
69245#endif /* local variables moved into u.bo */
69246
69247  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69248  u.bo.pC = p->apCsr[pOp->p1];
69249  assert( u.bo.pC!=0 );
69250  u.bo.pCrsr = u.bo.pC->pCursor;
69251  u.bo.res = 0;
69252  if( ALWAYS(u.bo.pCrsr!=0) ){
69253    rc = sqlite3BtreeLast(u.bo.pCrsr, &u.bo.res);
69254  }
69255  u.bo.pC->nullRow = (u8)u.bo.res;
69256  u.bo.pC->deferredMoveto = 0;
69257  u.bo.pC->rowidIsValid = 0;
69258  u.bo.pC->cacheStatus = CACHE_STALE;
69259  if( pOp->p2>0 && u.bo.res ){
69260    pc = pOp->p2 - 1;
69261  }
69262  break;
69263}
69264
69265
69266/* Opcode: Sort P1 P2 * * *
69267**
69268** This opcode does exactly the same thing as OP_Rewind except that
69269** it increments an undocumented global variable used for testing.
69270**
69271** Sorting is accomplished by writing records into a sorting index,
69272** then rewinding that index and playing it back from beginning to
69273** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
69274** rewinding so that the global variable will be incremented and
69275** regression tests can determine whether or not the optimizer is
69276** correctly optimizing out sorts.
69277*/
69278case OP_SorterSort:    /* jump */
69279#ifdef SQLITE_OMIT_MERGE_SORT
69280  pOp->opcode = OP_Sort;
69281#endif
69282case OP_Sort: {        /* jump */
69283#ifdef SQLITE_TEST
69284  sqlite3_sort_count++;
69285  sqlite3_search_count--;
69286#endif
69287  p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
69288  /* Fall through into OP_Rewind */
69289}
69290/* Opcode: Rewind P1 P2 * * *
69291**
69292** The next use of the Rowid or Column or Next instruction for P1
69293** will refer to the first entry in the database table or index.
69294** If the table or index is empty and P2>0, then jump immediately to P2.
69295** If P2 is 0 or if the table or index is not empty, fall through
69296** to the following instruction.
69297*/
69298case OP_Rewind: {        /* jump */
69299#if 0  /* local variables moved into u.bp */
69300  VdbeCursor *pC;
69301  BtCursor *pCrsr;
69302  int res;
69303#endif /* local variables moved into u.bp */
69304
69305  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69306  u.bp.pC = p->apCsr[pOp->p1];
69307  assert( u.bp.pC!=0 );
69308  assert( u.bp.pC->isSorter==(pOp->opcode==OP_SorterSort) );
69309  u.bp.res = 1;
69310  if( isSorter(u.bp.pC) ){
69311    rc = sqlite3VdbeSorterRewind(db, u.bp.pC, &u.bp.res);
69312  }else{
69313    u.bp.pCrsr = u.bp.pC->pCursor;
69314    assert( u.bp.pCrsr );
69315    rc = sqlite3BtreeFirst(u.bp.pCrsr, &u.bp.res);
69316    u.bp.pC->atFirst = u.bp.res==0 ?1:0;
69317    u.bp.pC->deferredMoveto = 0;
69318    u.bp.pC->cacheStatus = CACHE_STALE;
69319    u.bp.pC->rowidIsValid = 0;
69320  }
69321  u.bp.pC->nullRow = (u8)u.bp.res;
69322  assert( pOp->p2>0 && pOp->p2<p->nOp );
69323  if( u.bp.res ){
69324    pc = pOp->p2 - 1;
69325  }
69326  break;
69327}
69328
69329/* Opcode: Next P1 P2 * P4 P5
69330**
69331** Advance cursor P1 so that it points to the next key/data pair in its
69332** table or index.  If there are no more key/value pairs then fall through
69333** to the following instruction.  But if the cursor advance was successful,
69334** jump immediately to P2.
69335**
69336** The P1 cursor must be for a real table, not a pseudo-table.
69337**
69338** P4 is always of type P4_ADVANCE. The function pointer points to
69339** sqlite3BtreeNext().
69340**
69341** If P5 is positive and the jump is taken, then event counter
69342** number P5-1 in the prepared statement is incremented.
69343**
69344** See also: Prev
69345*/
69346/* Opcode: Prev P1 P2 * * P5
69347**
69348** Back up cursor P1 so that it points to the previous key/data pair in its
69349** table or index.  If there is no previous key/value pairs then fall through
69350** to the following instruction.  But if the cursor backup was successful,
69351** jump immediately to P2.
69352**
69353** The P1 cursor must be for a real table, not a pseudo-table.
69354**
69355** P4 is always of type P4_ADVANCE. The function pointer points to
69356** sqlite3BtreePrevious().
69357**
69358** If P5 is positive and the jump is taken, then event counter
69359** number P5-1 in the prepared statement is incremented.
69360*/
69361case OP_SorterNext:    /* jump */
69362#ifdef SQLITE_OMIT_MERGE_SORT
69363  pOp->opcode = OP_Next;
69364#endif
69365case OP_Prev:          /* jump */
69366case OP_Next: {        /* jump */
69367#if 0  /* local variables moved into u.bq */
69368  VdbeCursor *pC;
69369  int res;
69370#endif /* local variables moved into u.bq */
69371
69372  CHECK_FOR_INTERRUPT;
69373  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69374  assert( pOp->p5<=ArraySize(p->aCounter) );
69375  u.bq.pC = p->apCsr[pOp->p1];
69376  if( u.bq.pC==0 ){
69377    break;  /* See ticket #2273 */
69378  }
69379  assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterNext) );
69380  if( isSorter(u.bq.pC) ){
69381    assert( pOp->opcode==OP_SorterNext );
69382    rc = sqlite3VdbeSorterNext(db, u.bq.pC, &u.bq.res);
69383  }else{
69384    u.bq.res = 1;
69385    assert( u.bq.pC->deferredMoveto==0 );
69386    assert( u.bq.pC->pCursor );
69387    assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
69388    assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
69389    rc = pOp->p4.xAdvance(u.bq.pC->pCursor, &u.bq.res);
69390  }
69391  u.bq.pC->nullRow = (u8)u.bq.res;
69392  u.bq.pC->cacheStatus = CACHE_STALE;
69393  if( u.bq.res==0 ){
69394    pc = pOp->p2 - 1;
69395    if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
69396#ifdef SQLITE_TEST
69397    sqlite3_search_count++;
69398#endif
69399  }
69400  u.bq.pC->rowidIsValid = 0;
69401  break;
69402}
69403
69404/* Opcode: IdxInsert P1 P2 P3 * P5
69405**
69406** Register P2 holds an SQL index key made using the
69407** MakeRecord instructions.  This opcode writes that key
69408** into the index P1.  Data for the entry is nil.
69409**
69410** P3 is a flag that provides a hint to the b-tree layer that this
69411** insert is likely to be an append.
69412**
69413** This instruction only works for indices.  The equivalent instruction
69414** for tables is OP_Insert.
69415*/
69416case OP_SorterInsert:       /* in2 */
69417#ifdef SQLITE_OMIT_MERGE_SORT
69418  pOp->opcode = OP_IdxInsert;
69419#endif
69420case OP_IdxInsert: {        /* in2 */
69421#if 0  /* local variables moved into u.br */
69422  VdbeCursor *pC;
69423  BtCursor *pCrsr;
69424  int nKey;
69425  const char *zKey;
69426#endif /* local variables moved into u.br */
69427
69428  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69429  u.br.pC = p->apCsr[pOp->p1];
69430  assert( u.br.pC!=0 );
69431  assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
69432  pIn2 = &aMem[pOp->p2];
69433  assert( pIn2->flags & MEM_Blob );
69434  u.br.pCrsr = u.br.pC->pCursor;
69435  if( ALWAYS(u.br.pCrsr!=0) ){
69436    assert( u.br.pC->isTable==0 );
69437    rc = ExpandBlob(pIn2);
69438    if( rc==SQLITE_OK ){
69439      if( isSorter(u.br.pC) ){
69440        rc = sqlite3VdbeSorterWrite(db, u.br.pC, pIn2);
69441      }else{
69442        u.br.nKey = pIn2->n;
69443        u.br.zKey = pIn2->z;
69444        rc = sqlite3BtreeInsert(u.br.pCrsr, u.br.zKey, u.br.nKey, "", 0, 0, pOp->p3,
69445            ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.br.pC->seekResult : 0)
69446            );
69447        assert( u.br.pC->deferredMoveto==0 );
69448        u.br.pC->cacheStatus = CACHE_STALE;
69449      }
69450    }
69451  }
69452  break;
69453}
69454
69455/* Opcode: IdxDelete P1 P2 P3 * *
69456**
69457** The content of P3 registers starting at register P2 form
69458** an unpacked index key. This opcode removes that entry from the
69459** index opened by cursor P1.
69460*/
69461case OP_IdxDelete: {
69462#if 0  /* local variables moved into u.bs */
69463  VdbeCursor *pC;
69464  BtCursor *pCrsr;
69465  int res;
69466  UnpackedRecord r;
69467#endif /* local variables moved into u.bs */
69468
69469  assert( pOp->p3>0 );
69470  assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
69471  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69472  u.bs.pC = p->apCsr[pOp->p1];
69473  assert( u.bs.pC!=0 );
69474  u.bs.pCrsr = u.bs.pC->pCursor;
69475  if( ALWAYS(u.bs.pCrsr!=0) ){
69476    u.bs.r.pKeyInfo = u.bs.pC->pKeyInfo;
69477    u.bs.r.nField = (u16)pOp->p3;
69478    u.bs.r.flags = 0;
69479    u.bs.r.aMem = &aMem[pOp->p2];
69480#ifdef SQLITE_DEBUG
69481    { int i; for(i=0; i<u.bs.r.nField; i++) assert( memIsValid(&u.bs.r.aMem[i]) ); }
69482#endif
69483    rc = sqlite3BtreeMovetoUnpacked(u.bs.pCrsr, &u.bs.r, 0, 0, &u.bs.res);
69484    if( rc==SQLITE_OK && u.bs.res==0 ){
69485      rc = sqlite3BtreeDelete(u.bs.pCrsr);
69486    }
69487    assert( u.bs.pC->deferredMoveto==0 );
69488    u.bs.pC->cacheStatus = CACHE_STALE;
69489  }
69490  break;
69491}
69492
69493/* Opcode: IdxRowid P1 P2 * * *
69494**
69495** Write into register P2 an integer which is the last entry in the record at
69496** the end of the index key pointed to by cursor P1.  This integer should be
69497** the rowid of the table entry to which this index entry points.
69498**
69499** See also: Rowid, MakeRecord.
69500*/
69501case OP_IdxRowid: {              /* out2-prerelease */
69502#if 0  /* local variables moved into u.bt */
69503  BtCursor *pCrsr;
69504  VdbeCursor *pC;
69505  i64 rowid;
69506#endif /* local variables moved into u.bt */
69507
69508  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69509  u.bt.pC = p->apCsr[pOp->p1];
69510  assert( u.bt.pC!=0 );
69511  u.bt.pCrsr = u.bt.pC->pCursor;
69512  pOut->flags = MEM_Null;
69513  if( ALWAYS(u.bt.pCrsr!=0) ){
69514    rc = sqlite3VdbeCursorMoveto(u.bt.pC);
69515    if( NEVER(rc) ) goto abort_due_to_error;
69516    assert( u.bt.pC->deferredMoveto==0 );
69517    assert( u.bt.pC->isTable==0 );
69518    if( !u.bt.pC->nullRow ){
69519      rc = sqlite3VdbeIdxRowid(db, u.bt.pCrsr, &u.bt.rowid);
69520      if( rc!=SQLITE_OK ){
69521        goto abort_due_to_error;
69522      }
69523      pOut->u.i = u.bt.rowid;
69524      pOut->flags = MEM_Int;
69525    }
69526  }
69527  break;
69528}
69529
69530/* Opcode: IdxGE P1 P2 P3 P4 P5
69531**
69532** The P4 register values beginning with P3 form an unpacked index
69533** key that omits the ROWID.  Compare this key value against the index
69534** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
69535**
69536** If the P1 index entry is greater than or equal to the key value
69537** then jump to P2.  Otherwise fall through to the next instruction.
69538**
69539** If P5 is non-zero then the key value is increased by an epsilon
69540** prior to the comparison.  This make the opcode work like IdxGT except
69541** that if the key from register P3 is a prefix of the key in the cursor,
69542** the result is false whereas it would be true with IdxGT.
69543*/
69544/* Opcode: IdxLT P1 P2 P3 P4 P5
69545**
69546** The P4 register values beginning with P3 form an unpacked index
69547** key that omits the ROWID.  Compare this key value against the index
69548** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
69549**
69550** If the P1 index entry is less than the key value then jump to P2.
69551** Otherwise fall through to the next instruction.
69552**
69553** If P5 is non-zero then the key value is increased by an epsilon prior
69554** to the comparison.  This makes the opcode work like IdxLE.
69555*/
69556case OP_IdxLT:          /* jump */
69557case OP_IdxGE: {        /* jump */
69558#if 0  /* local variables moved into u.bu */
69559  VdbeCursor *pC;
69560  int res;
69561  UnpackedRecord r;
69562#endif /* local variables moved into u.bu */
69563
69564  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69565  u.bu.pC = p->apCsr[pOp->p1];
69566  assert( u.bu.pC!=0 );
69567  assert( u.bu.pC->isOrdered );
69568  if( ALWAYS(u.bu.pC->pCursor!=0) ){
69569    assert( u.bu.pC->deferredMoveto==0 );
69570    assert( pOp->p5==0 || pOp->p5==1 );
69571    assert( pOp->p4type==P4_INT32 );
69572    u.bu.r.pKeyInfo = u.bu.pC->pKeyInfo;
69573    u.bu.r.nField = (u16)pOp->p4.i;
69574    if( pOp->p5 ){
69575      u.bu.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
69576    }else{
69577      u.bu.r.flags = UNPACKED_PREFIX_MATCH;
69578    }
69579    u.bu.r.aMem = &aMem[pOp->p3];
69580#ifdef SQLITE_DEBUG
69581    { int i; for(i=0; i<u.bu.r.nField; i++) assert( memIsValid(&u.bu.r.aMem[i]) ); }
69582#endif
69583    rc = sqlite3VdbeIdxKeyCompare(u.bu.pC, &u.bu.r, &u.bu.res);
69584    if( pOp->opcode==OP_IdxLT ){
69585      u.bu.res = -u.bu.res;
69586    }else{
69587      assert( pOp->opcode==OP_IdxGE );
69588      u.bu.res++;
69589    }
69590    if( u.bu.res>0 ){
69591      pc = pOp->p2 - 1 ;
69592    }
69593  }
69594  break;
69595}
69596
69597/* Opcode: Destroy P1 P2 P3 * *
69598**
69599** Delete an entire database table or index whose root page in the database
69600** file is given by P1.
69601**
69602** The table being destroyed is in the main database file if P3==0.  If
69603** P3==1 then the table to be clear is in the auxiliary database file
69604** that is used to store tables create using CREATE TEMPORARY TABLE.
69605**
69606** If AUTOVACUUM is enabled then it is possible that another root page
69607** might be moved into the newly deleted root page in order to keep all
69608** root pages contiguous at the beginning of the database.  The former
69609** value of the root page that moved - its value before the move occurred -
69610** is stored in register P2.  If no page
69611** movement was required (because the table being dropped was already
69612** the last one in the database) then a zero is stored in register P2.
69613** If AUTOVACUUM is disabled then a zero is stored in register P2.
69614**
69615** See also: Clear
69616*/
69617case OP_Destroy: {     /* out2-prerelease */
69618#if 0  /* local variables moved into u.bv */
69619  int iMoved;
69620  int iCnt;
69621  Vdbe *pVdbe;
69622  int iDb;
69623#endif /* local variables moved into u.bv */
69624#ifndef SQLITE_OMIT_VIRTUALTABLE
69625  u.bv.iCnt = 0;
69626  for(u.bv.pVdbe=db->pVdbe; u.bv.pVdbe; u.bv.pVdbe = u.bv.pVdbe->pNext){
69627    if( u.bv.pVdbe->magic==VDBE_MAGIC_RUN && u.bv.pVdbe->inVtabMethod<2 && u.bv.pVdbe->pc>=0 ){
69628      u.bv.iCnt++;
69629    }
69630  }
69631#else
69632  u.bv.iCnt = db->activeVdbeCnt;
69633#endif
69634  pOut->flags = MEM_Null;
69635  if( u.bv.iCnt>1 ){
69636    rc = SQLITE_LOCKED;
69637    p->errorAction = OE_Abort;
69638  }else{
69639    u.bv.iDb = pOp->p3;
69640    assert( u.bv.iCnt==1 );
69641    assert( (p->btreeMask & (((yDbMask)1)<<u.bv.iDb))!=0 );
69642    rc = sqlite3BtreeDropTable(db->aDb[u.bv.iDb].pBt, pOp->p1, &u.bv.iMoved);
69643    pOut->flags = MEM_Int;
69644    pOut->u.i = u.bv.iMoved;
69645#ifndef SQLITE_OMIT_AUTOVACUUM
69646    if( rc==SQLITE_OK && u.bv.iMoved!=0 ){
69647      sqlite3RootPageMoved(db, u.bv.iDb, u.bv.iMoved, pOp->p1);
69648      /* All OP_Destroy operations occur on the same btree */
69649      assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bv.iDb+1 );
69650      resetSchemaOnFault = u.bv.iDb+1;
69651    }
69652#endif
69653  }
69654  break;
69655}
69656
69657/* Opcode: Clear P1 P2 P3
69658**
69659** Delete all contents of the database table or index whose root page
69660** in the database file is given by P1.  But, unlike Destroy, do not
69661** remove the table or index from the database file.
69662**
69663** The table being clear is in the main database file if P2==0.  If
69664** P2==1 then the table to be clear is in the auxiliary database file
69665** that is used to store tables create using CREATE TEMPORARY TABLE.
69666**
69667** If the P3 value is non-zero, then the table referred to must be an
69668** intkey table (an SQL table, not an index). In this case the row change
69669** count is incremented by the number of rows in the table being cleared.
69670** If P3 is greater than zero, then the value stored in register P3 is
69671** also incremented by the number of rows in the table being cleared.
69672**
69673** See also: Destroy
69674*/
69675case OP_Clear: {
69676#if 0  /* local variables moved into u.bw */
69677  int nChange;
69678#endif /* local variables moved into u.bw */
69679
69680  u.bw.nChange = 0;
69681  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
69682  rc = sqlite3BtreeClearTable(
69683      db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bw.nChange : 0)
69684  );
69685  if( pOp->p3 ){
69686    p->nChange += u.bw.nChange;
69687    if( pOp->p3>0 ){
69688      assert( memIsValid(&aMem[pOp->p3]) );
69689      memAboutToChange(p, &aMem[pOp->p3]);
69690      aMem[pOp->p3].u.i += u.bw.nChange;
69691    }
69692  }
69693  break;
69694}
69695
69696/* Opcode: CreateTable P1 P2 * * *
69697**
69698** Allocate a new table in the main database file if P1==0 or in the
69699** auxiliary database file if P1==1 or in an attached database if
69700** P1>1.  Write the root page number of the new table into
69701** register P2
69702**
69703** The difference between a table and an index is this:  A table must
69704** have a 4-byte integer key and can have arbitrary data.  An index
69705** has an arbitrary key but no data.
69706**
69707** See also: CreateIndex
69708*/
69709/* Opcode: CreateIndex P1 P2 * * *
69710**
69711** Allocate a new index in the main database file if P1==0 or in the
69712** auxiliary database file if P1==1 or in an attached database if
69713** P1>1.  Write the root page number of the new table into
69714** register P2.
69715**
69716** See documentation on OP_CreateTable for additional information.
69717*/
69718case OP_CreateIndex:            /* out2-prerelease */
69719case OP_CreateTable: {          /* out2-prerelease */
69720#if 0  /* local variables moved into u.bx */
69721  int pgno;
69722  int flags;
69723  Db *pDb;
69724#endif /* local variables moved into u.bx */
69725
69726  u.bx.pgno = 0;
69727  assert( pOp->p1>=0 && pOp->p1<db->nDb );
69728  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
69729  u.bx.pDb = &db->aDb[pOp->p1];
69730  assert( u.bx.pDb->pBt!=0 );
69731  if( pOp->opcode==OP_CreateTable ){
69732    /* u.bx.flags = BTREE_INTKEY; */
69733    u.bx.flags = BTREE_INTKEY;
69734  }else{
69735    u.bx.flags = BTREE_BLOBKEY;
69736  }
69737  rc = sqlite3BtreeCreateTable(u.bx.pDb->pBt, &u.bx.pgno, u.bx.flags);
69738  pOut->u.i = u.bx.pgno;
69739  break;
69740}
69741
69742/* Opcode: ParseSchema P1 * * P4 *
69743**
69744** Read and parse all entries from the SQLITE_MASTER table of database P1
69745** that match the WHERE clause P4.
69746**
69747** This opcode invokes the parser to create a new virtual machine,
69748** then runs the new virtual machine.  It is thus a re-entrant opcode.
69749*/
69750case OP_ParseSchema: {
69751#if 0  /* local variables moved into u.by */
69752  int iDb;
69753  const char *zMaster;
69754  char *zSql;
69755  InitData initData;
69756#endif /* local variables moved into u.by */
69757
69758  /* Any prepared statement that invokes this opcode will hold mutexes
69759  ** on every btree.  This is a prerequisite for invoking
69760  ** sqlite3InitCallback().
69761  */
69762#ifdef SQLITE_DEBUG
69763  for(u.by.iDb=0; u.by.iDb<db->nDb; u.by.iDb++){
69764    assert( u.by.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.by.iDb].pBt) );
69765  }
69766#endif
69767
69768  u.by.iDb = pOp->p1;
69769  assert( u.by.iDb>=0 && u.by.iDb<db->nDb );
69770  assert( DbHasProperty(db, u.by.iDb, DB_SchemaLoaded) );
69771  /* Used to be a conditional */ {
69772    u.by.zMaster = SCHEMA_TABLE(u.by.iDb);
69773    u.by.initData.db = db;
69774    u.by.initData.iDb = pOp->p1;
69775    u.by.initData.pzErrMsg = &p->zErrMsg;
69776    u.by.zSql = sqlite3MPrintf(db,
69777       "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
69778       db->aDb[u.by.iDb].zName, u.by.zMaster, pOp->p4.z);
69779    if( u.by.zSql==0 ){
69780      rc = SQLITE_NOMEM;
69781    }else{
69782      assert( db->init.busy==0 );
69783      db->init.busy = 1;
69784      u.by.initData.rc = SQLITE_OK;
69785      assert( !db->mallocFailed );
69786      rc = sqlite3_exec(db, u.by.zSql, sqlite3InitCallback, &u.by.initData, 0);
69787      if( rc==SQLITE_OK ) rc = u.by.initData.rc;
69788      sqlite3DbFree(db, u.by.zSql);
69789      db->init.busy = 0;
69790    }
69791  }
69792  if( rc ) sqlite3ResetInternalSchema(db, -1);
69793  if( rc==SQLITE_NOMEM ){
69794    goto no_mem;
69795  }
69796  break;
69797}
69798
69799#if !defined(SQLITE_OMIT_ANALYZE)
69800/* Opcode: LoadAnalysis P1 * * * *
69801**
69802** Read the sqlite_stat1 table for database P1 and load the content
69803** of that table into the internal index hash table.  This will cause
69804** the analysis to be used when preparing all subsequent queries.
69805*/
69806case OP_LoadAnalysis: {
69807  assert( pOp->p1>=0 && pOp->p1<db->nDb );
69808  rc = sqlite3AnalysisLoad(db, pOp->p1);
69809  break;
69810}
69811#endif /* !defined(SQLITE_OMIT_ANALYZE) */
69812
69813/* Opcode: DropTable P1 * * P4 *
69814**
69815** Remove the internal (in-memory) data structures that describe
69816** the table named P4 in database P1.  This is called after a table
69817** is dropped in order to keep the internal representation of the
69818** schema consistent with what is on disk.
69819*/
69820case OP_DropTable: {
69821  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
69822  break;
69823}
69824
69825/* Opcode: DropIndex P1 * * P4 *
69826**
69827** Remove the internal (in-memory) data structures that describe
69828** the index named P4 in database P1.  This is called after an index
69829** is dropped in order to keep the internal representation of the
69830** schema consistent with what is on disk.
69831*/
69832case OP_DropIndex: {
69833  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
69834  break;
69835}
69836
69837/* Opcode: DropTrigger P1 * * P4 *
69838**
69839** Remove the internal (in-memory) data structures that describe
69840** the trigger named P4 in database P1.  This is called after a trigger
69841** is dropped in order to keep the internal representation of the
69842** schema consistent with what is on disk.
69843*/
69844case OP_DropTrigger: {
69845  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
69846  break;
69847}
69848
69849
69850#ifndef SQLITE_OMIT_INTEGRITY_CHECK
69851/* Opcode: IntegrityCk P1 P2 P3 * P5
69852**
69853** Do an analysis of the currently open database.  Store in
69854** register P1 the text of an error message describing any problems.
69855** If no problems are found, store a NULL in register P1.
69856**
69857** The register P3 contains the maximum number of allowed errors.
69858** At most reg(P3) errors will be reported.
69859** In other words, the analysis stops as soon as reg(P1) errors are
69860** seen.  Reg(P1) is updated with the number of errors remaining.
69861**
69862** The root page numbers of all tables in the database are integer
69863** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
69864** total.
69865**
69866** If P5 is not zero, the check is done on the auxiliary database
69867** file, not the main database file.
69868**
69869** This opcode is used to implement the integrity_check pragma.
69870*/
69871case OP_IntegrityCk: {
69872#if 0  /* local variables moved into u.bz */
69873  int nRoot;      /* Number of tables to check.  (Number of root pages.) */
69874  int *aRoot;     /* Array of rootpage numbers for tables to be checked */
69875  int j;          /* Loop counter */
69876  int nErr;       /* Number of errors reported */
69877  char *z;        /* Text of the error report */
69878  Mem *pnErr;     /* Register keeping track of errors remaining */
69879#endif /* local variables moved into u.bz */
69880
69881  u.bz.nRoot = pOp->p2;
69882  assert( u.bz.nRoot>0 );
69883  u.bz.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bz.nRoot+1) );
69884  if( u.bz.aRoot==0 ) goto no_mem;
69885  assert( pOp->p3>0 && pOp->p3<=p->nMem );
69886  u.bz.pnErr = &aMem[pOp->p3];
69887  assert( (u.bz.pnErr->flags & MEM_Int)!=0 );
69888  assert( (u.bz.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
69889  pIn1 = &aMem[pOp->p1];
69890  for(u.bz.j=0; u.bz.j<u.bz.nRoot; u.bz.j++){
69891    u.bz.aRoot[u.bz.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bz.j]);
69892  }
69893  u.bz.aRoot[u.bz.j] = 0;
69894  assert( pOp->p5<db->nDb );
69895  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
69896  u.bz.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bz.aRoot, u.bz.nRoot,
69897                                 (int)u.bz.pnErr->u.i, &u.bz.nErr);
69898  sqlite3DbFree(db, u.bz.aRoot);
69899  u.bz.pnErr->u.i -= u.bz.nErr;
69900  sqlite3VdbeMemSetNull(pIn1);
69901  if( u.bz.nErr==0 ){
69902    assert( u.bz.z==0 );
69903  }else if( u.bz.z==0 ){
69904    goto no_mem;
69905  }else{
69906    sqlite3VdbeMemSetStr(pIn1, u.bz.z, -1, SQLITE_UTF8, sqlite3_free);
69907  }
69908  UPDATE_MAX_BLOBSIZE(pIn1);
69909  sqlite3VdbeChangeEncoding(pIn1, encoding);
69910  break;
69911}
69912#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
69913
69914/* Opcode: RowSetAdd P1 P2 * * *
69915**
69916** Insert the integer value held by register P2 into a boolean index
69917** held in register P1.
69918**
69919** An assertion fails if P2 is not an integer.
69920*/
69921case OP_RowSetAdd: {       /* in1, in2 */
69922  pIn1 = &aMem[pOp->p1];
69923  pIn2 = &aMem[pOp->p2];
69924  assert( (pIn2->flags & MEM_Int)!=0 );
69925  if( (pIn1->flags & MEM_RowSet)==0 ){
69926    sqlite3VdbeMemSetRowSet(pIn1);
69927    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69928  }
69929  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
69930  break;
69931}
69932
69933/* Opcode: RowSetRead P1 P2 P3 * *
69934**
69935** Extract the smallest value from boolean index P1 and put that value into
69936** register P3.  Or, if boolean index P1 is initially empty, leave P3
69937** unchanged and jump to instruction P2.
69938*/
69939case OP_RowSetRead: {       /* jump, in1, out3 */
69940#if 0  /* local variables moved into u.ca */
69941  i64 val;
69942#endif /* local variables moved into u.ca */
69943  CHECK_FOR_INTERRUPT;
69944  pIn1 = &aMem[pOp->p1];
69945  if( (pIn1->flags & MEM_RowSet)==0
69946   || sqlite3RowSetNext(pIn1->u.pRowSet, &u.ca.val)==0
69947  ){
69948    /* The boolean index is empty */
69949    sqlite3VdbeMemSetNull(pIn1);
69950    pc = pOp->p2 - 1;
69951  }else{
69952    /* A value was pulled from the index */
69953    sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.ca.val);
69954  }
69955  break;
69956}
69957
69958/* Opcode: RowSetTest P1 P2 P3 P4
69959**
69960** Register P3 is assumed to hold a 64-bit integer value. If register P1
69961** contains a RowSet object and that RowSet object contains
69962** the value held in P3, jump to register P2. Otherwise, insert the
69963** integer in P3 into the RowSet and continue on to the
69964** next opcode.
69965**
69966** The RowSet object is optimized for the case where successive sets
69967** of integers, where each set contains no duplicates. Each set
69968** of values is identified by a unique P4 value. The first set
69969** must have P4==0, the final set P4=-1.  P4 must be either -1 or
69970** non-negative.  For non-negative values of P4 only the lower 4
69971** bits are significant.
69972**
69973** This allows optimizations: (a) when P4==0 there is no need to test
69974** the rowset object for P3, as it is guaranteed not to contain it,
69975** (b) when P4==-1 there is no need to insert the value, as it will
69976** never be tested for, and (c) when a value that is part of set X is
69977** inserted, there is no need to search to see if the same value was
69978** previously inserted as part of set X (only if it was previously
69979** inserted as part of some other set).
69980*/
69981case OP_RowSetTest: {                     /* jump, in1, in3 */
69982#if 0  /* local variables moved into u.cb */
69983  int iSet;
69984  int exists;
69985#endif /* local variables moved into u.cb */
69986
69987  pIn1 = &aMem[pOp->p1];
69988  pIn3 = &aMem[pOp->p3];
69989  u.cb.iSet = pOp->p4.i;
69990  assert( pIn3->flags&MEM_Int );
69991
69992  /* If there is anything other than a rowset object in memory cell P1,
69993  ** delete it now and initialize P1 with an empty rowset
69994  */
69995  if( (pIn1->flags & MEM_RowSet)==0 ){
69996    sqlite3VdbeMemSetRowSet(pIn1);
69997    if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
69998  }
69999
70000  assert( pOp->p4type==P4_INT32 );
70001  assert( u.cb.iSet==-1 || u.cb.iSet>=0 );
70002  if( u.cb.iSet ){
70003    u.cb.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
70004                               (u8)(u.cb.iSet>=0 ? u.cb.iSet & 0xf : 0xff),
70005                               pIn3->u.i);
70006    if( u.cb.exists ){
70007      pc = pOp->p2 - 1;
70008      break;
70009    }
70010  }
70011  if( u.cb.iSet>=0 ){
70012    sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
70013  }
70014  break;
70015}
70016
70017
70018#ifndef SQLITE_OMIT_TRIGGER
70019
70020/* Opcode: Program P1 P2 P3 P4 *
70021**
70022** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
70023**
70024** P1 contains the address of the memory cell that contains the first memory
70025** cell in an array of values used as arguments to the sub-program. P2
70026** contains the address to jump to if the sub-program throws an IGNORE
70027** exception using the RAISE() function. Register P3 contains the address
70028** of a memory cell in this (the parent) VM that is used to allocate the
70029** memory required by the sub-vdbe at runtime.
70030**
70031** P4 is a pointer to the VM containing the trigger program.
70032*/
70033case OP_Program: {        /* jump */
70034#if 0  /* local variables moved into u.cc */
70035  int nMem;               /* Number of memory registers for sub-program */
70036  int nByte;              /* Bytes of runtime space required for sub-program */
70037  Mem *pRt;               /* Register to allocate runtime space */
70038  Mem *pMem;              /* Used to iterate through memory cells */
70039  Mem *pEnd;              /* Last memory cell in new array */
70040  VdbeFrame *pFrame;      /* New vdbe frame to execute in */
70041  SubProgram *pProgram;   /* Sub-program to execute */
70042  void *t;                /* Token identifying trigger */
70043#endif /* local variables moved into u.cc */
70044
70045  u.cc.pProgram = pOp->p4.pProgram;
70046  u.cc.pRt = &aMem[pOp->p3];
70047  assert( u.cc.pProgram->nOp>0 );
70048
70049  /* If the p5 flag is clear, then recursive invocation of triggers is
70050  ** disabled for backwards compatibility (p5 is set if this sub-program
70051  ** is really a trigger, not a foreign key action, and the flag set
70052  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
70053  **
70054  ** It is recursive invocation of triggers, at the SQL level, that is
70055  ** disabled. In some cases a single trigger may generate more than one
70056  ** SubProgram (if the trigger may be executed with more than one different
70057  ** ON CONFLICT algorithm). SubProgram structures associated with a
70058  ** single trigger all have the same value for the SubProgram.token
70059  ** variable.  */
70060  if( pOp->p5 ){
70061    u.cc.t = u.cc.pProgram->token;
70062    for(u.cc.pFrame=p->pFrame; u.cc.pFrame && u.cc.pFrame->token!=u.cc.t; u.cc.pFrame=u.cc.pFrame->pParent);
70063    if( u.cc.pFrame ) break;
70064  }
70065
70066  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
70067    rc = SQLITE_ERROR;
70068    sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
70069    break;
70070  }
70071
70072  /* Register u.cc.pRt is used to store the memory required to save the state
70073  ** of the current program, and the memory required at runtime to execute
70074  ** the trigger program. If this trigger has been fired before, then u.cc.pRt
70075  ** is already allocated. Otherwise, it must be initialized.  */
70076  if( (u.cc.pRt->flags&MEM_Frame)==0 ){
70077    /* SubProgram.nMem is set to the number of memory cells used by the
70078    ** program stored in SubProgram.aOp. As well as these, one memory
70079    ** cell is required for each cursor used by the program. Set local
70080    ** variable u.cc.nMem (and later, VdbeFrame.nChildMem) to this value.
70081    */
70082    u.cc.nMem = u.cc.pProgram->nMem + u.cc.pProgram->nCsr;
70083    u.cc.nByte = ROUND8(sizeof(VdbeFrame))
70084              + u.cc.nMem * sizeof(Mem)
70085              + u.cc.pProgram->nCsr * sizeof(VdbeCursor *)
70086              + u.cc.pProgram->nOnce * sizeof(u8);
70087    u.cc.pFrame = sqlite3DbMallocZero(db, u.cc.nByte);
70088    if( !u.cc.pFrame ){
70089      goto no_mem;
70090    }
70091    sqlite3VdbeMemRelease(u.cc.pRt);
70092    u.cc.pRt->flags = MEM_Frame;
70093    u.cc.pRt->u.pFrame = u.cc.pFrame;
70094
70095    u.cc.pFrame->v = p;
70096    u.cc.pFrame->nChildMem = u.cc.nMem;
70097    u.cc.pFrame->nChildCsr = u.cc.pProgram->nCsr;
70098    u.cc.pFrame->pc = pc;
70099    u.cc.pFrame->aMem = p->aMem;
70100    u.cc.pFrame->nMem = p->nMem;
70101    u.cc.pFrame->apCsr = p->apCsr;
70102    u.cc.pFrame->nCursor = p->nCursor;
70103    u.cc.pFrame->aOp = p->aOp;
70104    u.cc.pFrame->nOp = p->nOp;
70105    u.cc.pFrame->token = u.cc.pProgram->token;
70106    u.cc.pFrame->aOnceFlag = p->aOnceFlag;
70107    u.cc.pFrame->nOnceFlag = p->nOnceFlag;
70108
70109    u.cc.pEnd = &VdbeFrameMem(u.cc.pFrame)[u.cc.pFrame->nChildMem];
70110    for(u.cc.pMem=VdbeFrameMem(u.cc.pFrame); u.cc.pMem!=u.cc.pEnd; u.cc.pMem++){
70111      u.cc.pMem->flags = MEM_Invalid;
70112      u.cc.pMem->db = db;
70113    }
70114  }else{
70115    u.cc.pFrame = u.cc.pRt->u.pFrame;
70116    assert( u.cc.pProgram->nMem+u.cc.pProgram->nCsr==u.cc.pFrame->nChildMem );
70117    assert( u.cc.pProgram->nCsr==u.cc.pFrame->nChildCsr );
70118    assert( pc==u.cc.pFrame->pc );
70119  }
70120
70121  p->nFrame++;
70122  u.cc.pFrame->pParent = p->pFrame;
70123  u.cc.pFrame->lastRowid = lastRowid;
70124  u.cc.pFrame->nChange = p->nChange;
70125  p->nChange = 0;
70126  p->pFrame = u.cc.pFrame;
70127  p->aMem = aMem = &VdbeFrameMem(u.cc.pFrame)[-1];
70128  p->nMem = u.cc.pFrame->nChildMem;
70129  p->nCursor = (u16)u.cc.pFrame->nChildCsr;
70130  p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
70131  p->aOp = aOp = u.cc.pProgram->aOp;
70132  p->nOp = u.cc.pProgram->nOp;
70133  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
70134  p->nOnceFlag = u.cc.pProgram->nOnce;
70135  pc = -1;
70136  memset(p->aOnceFlag, 0, p->nOnceFlag);
70137
70138  break;
70139}
70140
70141/* Opcode: Param P1 P2 * * *
70142**
70143** This opcode is only ever present in sub-programs called via the
70144** OP_Program instruction. Copy a value currently stored in a memory
70145** cell of the calling (parent) frame to cell P2 in the current frames
70146** address space. This is used by trigger programs to access the new.*
70147** and old.* values.
70148**
70149** The address of the cell in the parent frame is determined by adding
70150** the value of the P1 argument to the value of the P1 argument to the
70151** calling OP_Program instruction.
70152*/
70153case OP_Param: {           /* out2-prerelease */
70154#if 0  /* local variables moved into u.cd */
70155  VdbeFrame *pFrame;
70156  Mem *pIn;
70157#endif /* local variables moved into u.cd */
70158  u.cd.pFrame = p->pFrame;
70159  u.cd.pIn = &u.cd.pFrame->aMem[pOp->p1 + u.cd.pFrame->aOp[u.cd.pFrame->pc].p1];
70160  sqlite3VdbeMemShallowCopy(pOut, u.cd.pIn, MEM_Ephem);
70161  break;
70162}
70163
70164#endif /* #ifndef SQLITE_OMIT_TRIGGER */
70165
70166#ifndef SQLITE_OMIT_FOREIGN_KEY
70167/* Opcode: FkCounter P1 P2 * * *
70168**
70169** Increment a "constraint counter" by P2 (P2 may be negative or positive).
70170** If P1 is non-zero, the database constraint counter is incremented
70171** (deferred foreign key constraints). Otherwise, if P1 is zero, the
70172** statement counter is incremented (immediate foreign key constraints).
70173*/
70174case OP_FkCounter: {
70175  if( pOp->p1 ){
70176    db->nDeferredCons += pOp->p2;
70177  }else{
70178    p->nFkConstraint += pOp->p2;
70179  }
70180  break;
70181}
70182
70183/* Opcode: FkIfZero P1 P2 * * *
70184**
70185** This opcode tests if a foreign key constraint-counter is currently zero.
70186** If so, jump to instruction P2. Otherwise, fall through to the next
70187** instruction.
70188**
70189** If P1 is non-zero, then the jump is taken if the database constraint-counter
70190** is zero (the one that counts deferred constraint violations). If P1 is
70191** zero, the jump is taken if the statement constraint-counter is zero
70192** (immediate foreign key constraint violations).
70193*/
70194case OP_FkIfZero: {         /* jump */
70195  if( pOp->p1 ){
70196    if( db->nDeferredCons==0 ) pc = pOp->p2-1;
70197  }else{
70198    if( p->nFkConstraint==0 ) pc = pOp->p2-1;
70199  }
70200  break;
70201}
70202#endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
70203
70204#ifndef SQLITE_OMIT_AUTOINCREMENT
70205/* Opcode: MemMax P1 P2 * * *
70206**
70207** P1 is a register in the root frame of this VM (the root frame is
70208** different from the current frame if this instruction is being executed
70209** within a sub-program). Set the value of register P1 to the maximum of
70210** its current value and the value in register P2.
70211**
70212** This instruction throws an error if the memory cell is not initially
70213** an integer.
70214*/
70215case OP_MemMax: {        /* in2 */
70216#if 0  /* local variables moved into u.ce */
70217  Mem *pIn1;
70218  VdbeFrame *pFrame;
70219#endif /* local variables moved into u.ce */
70220  if( p->pFrame ){
70221    for(u.ce.pFrame=p->pFrame; u.ce.pFrame->pParent; u.ce.pFrame=u.ce.pFrame->pParent);
70222    u.ce.pIn1 = &u.ce.pFrame->aMem[pOp->p1];
70223  }else{
70224    u.ce.pIn1 = &aMem[pOp->p1];
70225  }
70226  assert( memIsValid(u.ce.pIn1) );
70227  sqlite3VdbeMemIntegerify(u.ce.pIn1);
70228  pIn2 = &aMem[pOp->p2];
70229  sqlite3VdbeMemIntegerify(pIn2);
70230  if( u.ce.pIn1->u.i<pIn2->u.i){
70231    u.ce.pIn1->u.i = pIn2->u.i;
70232  }
70233  break;
70234}
70235#endif /* SQLITE_OMIT_AUTOINCREMENT */
70236
70237/* Opcode: IfPos P1 P2 * * *
70238**
70239** If the value of register P1 is 1 or greater, jump to P2.
70240**
70241** It is illegal to use this instruction on a register that does
70242** not contain an integer.  An assertion fault will result if you try.
70243*/
70244case OP_IfPos: {        /* jump, in1 */
70245  pIn1 = &aMem[pOp->p1];
70246  assert( pIn1->flags&MEM_Int );
70247  if( pIn1->u.i>0 ){
70248     pc = pOp->p2 - 1;
70249  }
70250  break;
70251}
70252
70253/* Opcode: IfNeg P1 P2 * * *
70254**
70255** If the value of register P1 is less than zero, jump to P2.
70256**
70257** It is illegal to use this instruction on a register that does
70258** not contain an integer.  An assertion fault will result if you try.
70259*/
70260case OP_IfNeg: {        /* jump, in1 */
70261  pIn1 = &aMem[pOp->p1];
70262  assert( pIn1->flags&MEM_Int );
70263  if( pIn1->u.i<0 ){
70264     pc = pOp->p2 - 1;
70265  }
70266  break;
70267}
70268
70269/* Opcode: IfZero P1 P2 P3 * *
70270**
70271** The register P1 must contain an integer.  Add literal P3 to the
70272** value in register P1.  If the result is exactly 0, jump to P2.
70273**
70274** It is illegal to use this instruction on a register that does
70275** not contain an integer.  An assertion fault will result if you try.
70276*/
70277case OP_IfZero: {        /* jump, in1 */
70278  pIn1 = &aMem[pOp->p1];
70279  assert( pIn1->flags&MEM_Int );
70280  pIn1->u.i += pOp->p3;
70281  if( pIn1->u.i==0 ){
70282     pc = pOp->p2 - 1;
70283  }
70284  break;
70285}
70286
70287/* Opcode: AggStep * P2 P3 P4 P5
70288**
70289** Execute the step function for an aggregate.  The
70290** function has P5 arguments.   P4 is a pointer to the FuncDef
70291** structure that specifies the function.  Use register
70292** P3 as the accumulator.
70293**
70294** The P5 arguments are taken from register P2 and its
70295** successors.
70296*/
70297case OP_AggStep: {
70298#if 0  /* local variables moved into u.cf */
70299  int n;
70300  int i;
70301  Mem *pMem;
70302  Mem *pRec;
70303  sqlite3_context ctx;
70304  sqlite3_value **apVal;
70305#endif /* local variables moved into u.cf */
70306
70307  u.cf.n = pOp->p5;
70308  assert( u.cf.n>=0 );
70309  u.cf.pRec = &aMem[pOp->p2];
70310  u.cf.apVal = p->apArg;
70311  assert( u.cf.apVal || u.cf.n==0 );
70312  for(u.cf.i=0; u.cf.i<u.cf.n; u.cf.i++, u.cf.pRec++){
70313    assert( memIsValid(u.cf.pRec) );
70314    u.cf.apVal[u.cf.i] = u.cf.pRec;
70315    memAboutToChange(p, u.cf.pRec);
70316    sqlite3VdbeMemStoreType(u.cf.pRec);
70317  }
70318  u.cf.ctx.pFunc = pOp->p4.pFunc;
70319  assert( pOp->p3>0 && pOp->p3<=p->nMem );
70320  u.cf.ctx.pMem = u.cf.pMem = &aMem[pOp->p3];
70321  u.cf.pMem->n++;
70322  u.cf.ctx.s.flags = MEM_Null;
70323  u.cf.ctx.s.z = 0;
70324  u.cf.ctx.s.zMalloc = 0;
70325  u.cf.ctx.s.xDel = 0;
70326  u.cf.ctx.s.db = db;
70327  u.cf.ctx.isError = 0;
70328  u.cf.ctx.pColl = 0;
70329  u.cf.ctx.skipFlag = 0;
70330  if( u.cf.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
70331    assert( pOp>p->aOp );
70332    assert( pOp[-1].p4type==P4_COLLSEQ );
70333    assert( pOp[-1].opcode==OP_CollSeq );
70334    u.cf.ctx.pColl = pOp[-1].p4.pColl;
70335  }
70336  (u.cf.ctx.pFunc->xStep)(&u.cf.ctx, u.cf.n, u.cf.apVal); /* IMP: R-24505-23230 */
70337  if( u.cf.ctx.isError ){
70338    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cf.ctx.s));
70339    rc = u.cf.ctx.isError;
70340  }
70341  if( u.cf.ctx.skipFlag ){
70342    assert( pOp[-1].opcode==OP_CollSeq );
70343    u.cf.i = pOp[-1].p1;
70344    if( u.cf.i ) sqlite3VdbeMemSetInt64(&aMem[u.cf.i], 1);
70345  }
70346
70347  sqlite3VdbeMemRelease(&u.cf.ctx.s);
70348
70349  break;
70350}
70351
70352/* Opcode: AggFinal P1 P2 * P4 *
70353**
70354** Execute the finalizer function for an aggregate.  P1 is
70355** the memory location that is the accumulator for the aggregate.
70356**
70357** P2 is the number of arguments that the step function takes and
70358** P4 is a pointer to the FuncDef for this function.  The P2
70359** argument is not used by this opcode.  It is only there to disambiguate
70360** functions that can take varying numbers of arguments.  The
70361** P4 argument is only needed for the degenerate case where
70362** the step function was not previously called.
70363*/
70364case OP_AggFinal: {
70365#if 0  /* local variables moved into u.cg */
70366  Mem *pMem;
70367#endif /* local variables moved into u.cg */
70368  assert( pOp->p1>0 && pOp->p1<=p->nMem );
70369  u.cg.pMem = &aMem[pOp->p1];
70370  assert( (u.cg.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
70371  rc = sqlite3VdbeMemFinalize(u.cg.pMem, pOp->p4.pFunc);
70372  if( rc ){
70373    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cg.pMem));
70374  }
70375  sqlite3VdbeChangeEncoding(u.cg.pMem, encoding);
70376  UPDATE_MAX_BLOBSIZE(u.cg.pMem);
70377  if( sqlite3VdbeMemTooBig(u.cg.pMem) ){
70378    goto too_big;
70379  }
70380  break;
70381}
70382
70383#ifndef SQLITE_OMIT_WAL
70384/* Opcode: Checkpoint P1 P2 P3 * *
70385**
70386** Checkpoint database P1. This is a no-op if P1 is not currently in
70387** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
70388** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
70389** SQLITE_BUSY or not, respectively.  Write the number of pages in the
70390** WAL after the checkpoint into mem[P3+1] and the number of pages
70391** in the WAL that have been checkpointed after the checkpoint
70392** completes into mem[P3+2].  However on an error, mem[P3+1] and
70393** mem[P3+2] are initialized to -1.
70394*/
70395case OP_Checkpoint: {
70396#if 0  /* local variables moved into u.ch */
70397  int i;                          /* Loop counter */
70398  int aRes[3];                    /* Results */
70399  Mem *pMem;                      /* Write results here */
70400#endif /* local variables moved into u.ch */
70401
70402  u.ch.aRes[0] = 0;
70403  u.ch.aRes[1] = u.ch.aRes[2] = -1;
70404  assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
70405       || pOp->p2==SQLITE_CHECKPOINT_FULL
70406       || pOp->p2==SQLITE_CHECKPOINT_RESTART
70407  );
70408  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ch.aRes[1], &u.ch.aRes[2]);
70409  if( rc==SQLITE_BUSY ){
70410    rc = SQLITE_OK;
70411    u.ch.aRes[0] = 1;
70412  }
70413  for(u.ch.i=0, u.ch.pMem = &aMem[pOp->p3]; u.ch.i<3; u.ch.i++, u.ch.pMem++){
70414    sqlite3VdbeMemSetInt64(u.ch.pMem, (i64)u.ch.aRes[u.ch.i]);
70415  }
70416  break;
70417};
70418#endif
70419
70420#ifndef SQLITE_OMIT_PRAGMA
70421/* Opcode: JournalMode P1 P2 P3 * P5
70422**
70423** Change the journal mode of database P1 to P3. P3 must be one of the
70424** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
70425** modes (delete, truncate, persist, off and memory), this is a simple
70426** operation. No IO is required.
70427**
70428** If changing into or out of WAL mode the procedure is more complicated.
70429**
70430** Write a string containing the final journal-mode to register P2.
70431*/
70432case OP_JournalMode: {    /* out2-prerelease */
70433#if 0  /* local variables moved into u.ci */
70434  Btree *pBt;                     /* Btree to change journal mode of */
70435  Pager *pPager;                  /* Pager associated with pBt */
70436  int eNew;                       /* New journal mode */
70437  int eOld;                       /* The old journal mode */
70438  const char *zFilename;          /* Name of database file for pPager */
70439#endif /* local variables moved into u.ci */
70440
70441  u.ci.eNew = pOp->p3;
70442  assert( u.ci.eNew==PAGER_JOURNALMODE_DELETE
70443       || u.ci.eNew==PAGER_JOURNALMODE_TRUNCATE
70444       || u.ci.eNew==PAGER_JOURNALMODE_PERSIST
70445       || u.ci.eNew==PAGER_JOURNALMODE_OFF
70446       || u.ci.eNew==PAGER_JOURNALMODE_MEMORY
70447       || u.ci.eNew==PAGER_JOURNALMODE_WAL
70448       || u.ci.eNew==PAGER_JOURNALMODE_QUERY
70449  );
70450  assert( pOp->p1>=0 && pOp->p1<db->nDb );
70451
70452  u.ci.pBt = db->aDb[pOp->p1].pBt;
70453  u.ci.pPager = sqlite3BtreePager(u.ci.pBt);
70454  u.ci.eOld = sqlite3PagerGetJournalMode(u.ci.pPager);
70455  if( u.ci.eNew==PAGER_JOURNALMODE_QUERY ) u.ci.eNew = u.ci.eOld;
70456  if( !sqlite3PagerOkToChangeJournalMode(u.ci.pPager) ) u.ci.eNew = u.ci.eOld;
70457
70458#ifndef SQLITE_OMIT_WAL
70459  u.ci.zFilename = sqlite3PagerFilename(u.ci.pPager);
70460
70461  /* Do not allow a transition to journal_mode=WAL for a database
70462  ** in temporary storage or if the VFS does not support shared memory
70463  */
70464  if( u.ci.eNew==PAGER_JOURNALMODE_WAL
70465   && (sqlite3Strlen30(u.ci.zFilename)==0           /* Temp file */
70466       || !sqlite3PagerWalSupported(u.ci.pPager))   /* No shared-memory support */
70467  ){
70468    u.ci.eNew = u.ci.eOld;
70469  }
70470
70471  if( (u.ci.eNew!=u.ci.eOld)
70472   && (u.ci.eOld==PAGER_JOURNALMODE_WAL || u.ci.eNew==PAGER_JOURNALMODE_WAL)
70473  ){
70474    if( !db->autoCommit || db->activeVdbeCnt>1 ){
70475      rc = SQLITE_ERROR;
70476      sqlite3SetString(&p->zErrMsg, db,
70477          "cannot change %s wal mode from within a transaction",
70478          (u.ci.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
70479      );
70480      break;
70481    }else{
70482
70483      if( u.ci.eOld==PAGER_JOURNALMODE_WAL ){
70484        /* If leaving WAL mode, close the log file. If successful, the call
70485        ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
70486        ** file. An EXCLUSIVE lock may still be held on the database file
70487        ** after a successful return.
70488        */
70489        rc = sqlite3PagerCloseWal(u.ci.pPager);
70490        if( rc==SQLITE_OK ){
70491          sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
70492        }
70493      }else if( u.ci.eOld==PAGER_JOURNALMODE_MEMORY ){
70494        /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
70495        ** as an intermediate */
70496        sqlite3PagerSetJournalMode(u.ci.pPager, PAGER_JOURNALMODE_OFF);
70497      }
70498
70499      /* Open a transaction on the database file. Regardless of the journal
70500      ** mode, this transaction always uses a rollback journal.
70501      */
70502      assert( sqlite3BtreeIsInTrans(u.ci.pBt)==0 );
70503      if( rc==SQLITE_OK ){
70504        rc = sqlite3BtreeSetVersion(u.ci.pBt, (u.ci.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
70505      }
70506    }
70507  }
70508#endif /* ifndef SQLITE_OMIT_WAL */
70509
70510  if( rc ){
70511    u.ci.eNew = u.ci.eOld;
70512  }
70513  u.ci.eNew = sqlite3PagerSetJournalMode(u.ci.pPager, u.ci.eNew);
70514
70515  pOut = &aMem[pOp->p2];
70516  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
70517  pOut->z = (char *)sqlite3JournalModename(u.ci.eNew);
70518  pOut->n = sqlite3Strlen30(pOut->z);
70519  pOut->enc = SQLITE_UTF8;
70520  sqlite3VdbeChangeEncoding(pOut, encoding);
70521  break;
70522};
70523#endif /* SQLITE_OMIT_PRAGMA */
70524
70525#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
70526/* Opcode: Vacuum * * * * *
70527**
70528** Vacuum the entire database.  This opcode will cause other virtual
70529** machines to be created and run.  It may not be called from within
70530** a transaction.
70531*/
70532case OP_Vacuum: {
70533  rc = sqlite3RunVacuum(&p->zErrMsg, db);
70534  break;
70535}
70536#endif
70537
70538#if !defined(SQLITE_OMIT_AUTOVACUUM)
70539/* Opcode: IncrVacuum P1 P2 * * *
70540**
70541** Perform a single step of the incremental vacuum procedure on
70542** the P1 database. If the vacuum has finished, jump to instruction
70543** P2. Otherwise, fall through to the next instruction.
70544*/
70545case OP_IncrVacuum: {        /* jump */
70546#if 0  /* local variables moved into u.cj */
70547  Btree *pBt;
70548#endif /* local variables moved into u.cj */
70549
70550  assert( pOp->p1>=0 && pOp->p1<db->nDb );
70551  assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70552  u.cj.pBt = db->aDb[pOp->p1].pBt;
70553  rc = sqlite3BtreeIncrVacuum(u.cj.pBt);
70554  if( rc==SQLITE_DONE ){
70555    pc = pOp->p2 - 1;
70556    rc = SQLITE_OK;
70557  }
70558  break;
70559}
70560#endif
70561
70562/* Opcode: Expire P1 * * * *
70563**
70564** Cause precompiled statements to become expired. An expired statement
70565** fails with an error code of SQLITE_SCHEMA if it is ever executed
70566** (via sqlite3_step()).
70567**
70568** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
70569** then only the currently executing statement is affected.
70570*/
70571case OP_Expire: {
70572  if( !pOp->p1 ){
70573    sqlite3ExpirePreparedStatements(db);
70574  }else{
70575    p->expired = 1;
70576  }
70577  break;
70578}
70579
70580#ifndef SQLITE_OMIT_SHARED_CACHE
70581/* Opcode: TableLock P1 P2 P3 P4 *
70582**
70583** Obtain a lock on a particular table. This instruction is only used when
70584** the shared-cache feature is enabled.
70585**
70586** P1 is the index of the database in sqlite3.aDb[] of the database
70587** on which the lock is acquired.  A readlock is obtained if P3==0 or
70588** a write lock if P3==1.
70589**
70590** P2 contains the root-page of the table to lock.
70591**
70592** P4 contains a pointer to the name of the table being locked. This is only
70593** used to generate an error message if the lock cannot be obtained.
70594*/
70595case OP_TableLock: {
70596  u8 isWriteLock = (u8)pOp->p3;
70597  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
70598    int p1 = pOp->p1;
70599    assert( p1>=0 && p1<db->nDb );
70600    assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
70601    assert( isWriteLock==0 || isWriteLock==1 );
70602    rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
70603    if( (rc&0xFF)==SQLITE_LOCKED ){
70604      const char *z = pOp->p4.z;
70605      sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
70606    }
70607  }
70608  break;
70609}
70610#endif /* SQLITE_OMIT_SHARED_CACHE */
70611
70612#ifndef SQLITE_OMIT_VIRTUALTABLE
70613/* Opcode: VBegin * * * P4 *
70614**
70615** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
70616** xBegin method for that table.
70617**
70618** Also, whether or not P4 is set, check that this is not being called from
70619** within a callback to a virtual table xSync() method. If it is, the error
70620** code will be set to SQLITE_LOCKED.
70621*/
70622case OP_VBegin: {
70623#if 0  /* local variables moved into u.ck */
70624  VTable *pVTab;
70625#endif /* local variables moved into u.ck */
70626  u.ck.pVTab = pOp->p4.pVtab;
70627  rc = sqlite3VtabBegin(db, u.ck.pVTab);
70628  if( u.ck.pVTab ) importVtabErrMsg(p, u.ck.pVTab->pVtab);
70629  break;
70630}
70631#endif /* SQLITE_OMIT_VIRTUALTABLE */
70632
70633#ifndef SQLITE_OMIT_VIRTUALTABLE
70634/* Opcode: VCreate P1 * * P4 *
70635**
70636** P4 is the name of a virtual table in database P1. Call the xCreate method
70637** for that table.
70638*/
70639case OP_VCreate: {
70640  rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
70641  break;
70642}
70643#endif /* SQLITE_OMIT_VIRTUALTABLE */
70644
70645#ifndef SQLITE_OMIT_VIRTUALTABLE
70646/* Opcode: VDestroy P1 * * P4 *
70647**
70648** P4 is the name of a virtual table in database P1.  Call the xDestroy method
70649** of that table.
70650*/
70651case OP_VDestroy: {
70652  p->inVtabMethod = 2;
70653  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
70654  p->inVtabMethod = 0;
70655  break;
70656}
70657#endif /* SQLITE_OMIT_VIRTUALTABLE */
70658
70659#ifndef SQLITE_OMIT_VIRTUALTABLE
70660/* Opcode: VOpen P1 * * P4 *
70661**
70662** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70663** P1 is a cursor number.  This opcode opens a cursor to the virtual
70664** table and stores that cursor in P1.
70665*/
70666case OP_VOpen: {
70667#if 0  /* local variables moved into u.cl */
70668  VdbeCursor *pCur;
70669  sqlite3_vtab_cursor *pVtabCursor;
70670  sqlite3_vtab *pVtab;
70671  sqlite3_module *pModule;
70672#endif /* local variables moved into u.cl */
70673
70674  u.cl.pCur = 0;
70675  u.cl.pVtabCursor = 0;
70676  u.cl.pVtab = pOp->p4.pVtab->pVtab;
70677  u.cl.pModule = (sqlite3_module *)u.cl.pVtab->pModule;
70678  assert(u.cl.pVtab && u.cl.pModule);
70679  rc = u.cl.pModule->xOpen(u.cl.pVtab, &u.cl.pVtabCursor);
70680  importVtabErrMsg(p, u.cl.pVtab);
70681  if( SQLITE_OK==rc ){
70682    /* Initialize sqlite3_vtab_cursor base class */
70683    u.cl.pVtabCursor->pVtab = u.cl.pVtab;
70684
70685    /* Initialise vdbe cursor object */
70686    u.cl.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
70687    if( u.cl.pCur ){
70688      u.cl.pCur->pVtabCursor = u.cl.pVtabCursor;
70689      u.cl.pCur->pModule = u.cl.pVtabCursor->pVtab->pModule;
70690    }else{
70691      db->mallocFailed = 1;
70692      u.cl.pModule->xClose(u.cl.pVtabCursor);
70693    }
70694  }
70695  break;
70696}
70697#endif /* SQLITE_OMIT_VIRTUALTABLE */
70698
70699#ifndef SQLITE_OMIT_VIRTUALTABLE
70700/* Opcode: VFilter P1 P2 P3 P4 *
70701**
70702** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
70703** the filtered result set is empty.
70704**
70705** P4 is either NULL or a string that was generated by the xBestIndex
70706** method of the module.  The interpretation of the P4 string is left
70707** to the module implementation.
70708**
70709** This opcode invokes the xFilter method on the virtual table specified
70710** by P1.  The integer query plan parameter to xFilter is stored in register
70711** P3. Register P3+1 stores the argc parameter to be passed to the
70712** xFilter method. Registers P3+2..P3+1+argc are the argc
70713** additional parameters which are passed to
70714** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
70715**
70716** A jump is made to P2 if the result set after filtering would be empty.
70717*/
70718case OP_VFilter: {   /* jump */
70719#if 0  /* local variables moved into u.cm */
70720  int nArg;
70721  int iQuery;
70722  const sqlite3_module *pModule;
70723  Mem *pQuery;
70724  Mem *pArgc;
70725  sqlite3_vtab_cursor *pVtabCursor;
70726  sqlite3_vtab *pVtab;
70727  VdbeCursor *pCur;
70728  int res;
70729  int i;
70730  Mem **apArg;
70731#endif /* local variables moved into u.cm */
70732
70733  u.cm.pQuery = &aMem[pOp->p3];
70734  u.cm.pArgc = &u.cm.pQuery[1];
70735  u.cm.pCur = p->apCsr[pOp->p1];
70736  assert( memIsValid(u.cm.pQuery) );
70737  REGISTER_TRACE(pOp->p3, u.cm.pQuery);
70738  assert( u.cm.pCur->pVtabCursor );
70739  u.cm.pVtabCursor = u.cm.pCur->pVtabCursor;
70740  u.cm.pVtab = u.cm.pVtabCursor->pVtab;
70741  u.cm.pModule = u.cm.pVtab->pModule;
70742
70743  /* Grab the index number and argc parameters */
70744  assert( (u.cm.pQuery->flags&MEM_Int)!=0 && u.cm.pArgc->flags==MEM_Int );
70745  u.cm.nArg = (int)u.cm.pArgc->u.i;
70746  u.cm.iQuery = (int)u.cm.pQuery->u.i;
70747
70748  /* Invoke the xFilter method */
70749  {
70750    u.cm.res = 0;
70751    u.cm.apArg = p->apArg;
70752    for(u.cm.i = 0; u.cm.i<u.cm.nArg; u.cm.i++){
70753      u.cm.apArg[u.cm.i] = &u.cm.pArgc[u.cm.i+1];
70754      sqlite3VdbeMemStoreType(u.cm.apArg[u.cm.i]);
70755    }
70756
70757    p->inVtabMethod = 1;
70758    rc = u.cm.pModule->xFilter(u.cm.pVtabCursor, u.cm.iQuery, pOp->p4.z, u.cm.nArg, u.cm.apArg);
70759    p->inVtabMethod = 0;
70760    importVtabErrMsg(p, u.cm.pVtab);
70761    if( rc==SQLITE_OK ){
70762      u.cm.res = u.cm.pModule->xEof(u.cm.pVtabCursor);
70763    }
70764
70765    if( u.cm.res ){
70766      pc = pOp->p2 - 1;
70767    }
70768  }
70769  u.cm.pCur->nullRow = 0;
70770
70771  break;
70772}
70773#endif /* SQLITE_OMIT_VIRTUALTABLE */
70774
70775#ifndef SQLITE_OMIT_VIRTUALTABLE
70776/* Opcode: VColumn P1 P2 P3 * *
70777**
70778** Store the value of the P2-th column of
70779** the row of the virtual-table that the
70780** P1 cursor is pointing to into register P3.
70781*/
70782case OP_VColumn: {
70783#if 0  /* local variables moved into u.cn */
70784  sqlite3_vtab *pVtab;
70785  const sqlite3_module *pModule;
70786  Mem *pDest;
70787  sqlite3_context sContext;
70788#endif /* local variables moved into u.cn */
70789
70790  VdbeCursor *pCur = p->apCsr[pOp->p1];
70791  assert( pCur->pVtabCursor );
70792  assert( pOp->p3>0 && pOp->p3<=p->nMem );
70793  u.cn.pDest = &aMem[pOp->p3];
70794  memAboutToChange(p, u.cn.pDest);
70795  if( pCur->nullRow ){
70796    sqlite3VdbeMemSetNull(u.cn.pDest);
70797    break;
70798  }
70799  u.cn.pVtab = pCur->pVtabCursor->pVtab;
70800  u.cn.pModule = u.cn.pVtab->pModule;
70801  assert( u.cn.pModule->xColumn );
70802  memset(&u.cn.sContext, 0, sizeof(u.cn.sContext));
70803
70804  /* The output cell may already have a buffer allocated. Move
70805  ** the current contents to u.cn.sContext.s so in case the user-function
70806  ** can use the already allocated buffer instead of allocating a
70807  ** new one.
70808  */
70809  sqlite3VdbeMemMove(&u.cn.sContext.s, u.cn.pDest);
70810  MemSetTypeFlag(&u.cn.sContext.s, MEM_Null);
70811
70812  rc = u.cn.pModule->xColumn(pCur->pVtabCursor, &u.cn.sContext, pOp->p2);
70813  importVtabErrMsg(p, u.cn.pVtab);
70814  if( u.cn.sContext.isError ){
70815    rc = u.cn.sContext.isError;
70816  }
70817
70818  /* Copy the result of the function to the P3 register. We
70819  ** do this regardless of whether or not an error occurred to ensure any
70820  ** dynamic allocation in u.cn.sContext.s (a Mem struct) is  released.
70821  */
70822  sqlite3VdbeChangeEncoding(&u.cn.sContext.s, encoding);
70823  sqlite3VdbeMemMove(u.cn.pDest, &u.cn.sContext.s);
70824  REGISTER_TRACE(pOp->p3, u.cn.pDest);
70825  UPDATE_MAX_BLOBSIZE(u.cn.pDest);
70826
70827  if( sqlite3VdbeMemTooBig(u.cn.pDest) ){
70828    goto too_big;
70829  }
70830  break;
70831}
70832#endif /* SQLITE_OMIT_VIRTUALTABLE */
70833
70834#ifndef SQLITE_OMIT_VIRTUALTABLE
70835/* Opcode: VNext P1 P2 * * *
70836**
70837** Advance virtual table P1 to the next row in its result set and
70838** jump to instruction P2.  Or, if the virtual table has reached
70839** the end of its result set, then fall through to the next instruction.
70840*/
70841case OP_VNext: {   /* jump */
70842#if 0  /* local variables moved into u.co */
70843  sqlite3_vtab *pVtab;
70844  const sqlite3_module *pModule;
70845  int res;
70846  VdbeCursor *pCur;
70847#endif /* local variables moved into u.co */
70848
70849  u.co.res = 0;
70850  u.co.pCur = p->apCsr[pOp->p1];
70851  assert( u.co.pCur->pVtabCursor );
70852  if( u.co.pCur->nullRow ){
70853    break;
70854  }
70855  u.co.pVtab = u.co.pCur->pVtabCursor->pVtab;
70856  u.co.pModule = u.co.pVtab->pModule;
70857  assert( u.co.pModule->xNext );
70858
70859  /* Invoke the xNext() method of the module. There is no way for the
70860  ** underlying implementation to return an error if one occurs during
70861  ** xNext(). Instead, if an error occurs, true is returned (indicating that
70862  ** data is available) and the error code returned when xColumn or
70863  ** some other method is next invoked on the save virtual table cursor.
70864  */
70865  p->inVtabMethod = 1;
70866  rc = u.co.pModule->xNext(u.co.pCur->pVtabCursor);
70867  p->inVtabMethod = 0;
70868  importVtabErrMsg(p, u.co.pVtab);
70869  if( rc==SQLITE_OK ){
70870    u.co.res = u.co.pModule->xEof(u.co.pCur->pVtabCursor);
70871  }
70872
70873  if( !u.co.res ){
70874    /* If there is data, jump to P2 */
70875    pc = pOp->p2 - 1;
70876  }
70877  break;
70878}
70879#endif /* SQLITE_OMIT_VIRTUALTABLE */
70880
70881#ifndef SQLITE_OMIT_VIRTUALTABLE
70882/* Opcode: VRename P1 * * P4 *
70883**
70884** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70885** This opcode invokes the corresponding xRename method. The value
70886** in register P1 is passed as the zName argument to the xRename method.
70887*/
70888case OP_VRename: {
70889#if 0  /* local variables moved into u.cp */
70890  sqlite3_vtab *pVtab;
70891  Mem *pName;
70892#endif /* local variables moved into u.cp */
70893
70894  u.cp.pVtab = pOp->p4.pVtab->pVtab;
70895  u.cp.pName = &aMem[pOp->p1];
70896  assert( u.cp.pVtab->pModule->xRename );
70897  assert( memIsValid(u.cp.pName) );
70898  REGISTER_TRACE(pOp->p1, u.cp.pName);
70899  assert( u.cp.pName->flags & MEM_Str );
70900  testcase( u.cp.pName->enc==SQLITE_UTF8 );
70901  testcase( u.cp.pName->enc==SQLITE_UTF16BE );
70902  testcase( u.cp.pName->enc==SQLITE_UTF16LE );
70903  rc = sqlite3VdbeChangeEncoding(u.cp.pName, SQLITE_UTF8);
70904  if( rc==SQLITE_OK ){
70905    rc = u.cp.pVtab->pModule->xRename(u.cp.pVtab, u.cp.pName->z);
70906    importVtabErrMsg(p, u.cp.pVtab);
70907    p->expired = 0;
70908  }
70909  break;
70910}
70911#endif
70912
70913#ifndef SQLITE_OMIT_VIRTUALTABLE
70914/* Opcode: VUpdate P1 P2 P3 P4 *
70915**
70916** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
70917** This opcode invokes the corresponding xUpdate method. P2 values
70918** are contiguous memory cells starting at P3 to pass to the xUpdate
70919** invocation. The value in register (P3+P2-1) corresponds to the
70920** p2th element of the argv array passed to xUpdate.
70921**
70922** The xUpdate method will do a DELETE or an INSERT or both.
70923** The argv[0] element (which corresponds to memory cell P3)
70924** is the rowid of a row to delete.  If argv[0] is NULL then no
70925** deletion occurs.  The argv[1] element is the rowid of the new
70926** row.  This can be NULL to have the virtual table select the new
70927** rowid for itself.  The subsequent elements in the array are
70928** the values of columns in the new row.
70929**
70930** If P2==1 then no insert is performed.  argv[0] is the rowid of
70931** a row to delete.
70932**
70933** P1 is a boolean flag. If it is set to true and the xUpdate call
70934** is successful, then the value returned by sqlite3_last_insert_rowid()
70935** is set to the value of the rowid for the row just inserted.
70936*/
70937case OP_VUpdate: {
70938#if 0  /* local variables moved into u.cq */
70939  sqlite3_vtab *pVtab;
70940  sqlite3_module *pModule;
70941  int nArg;
70942  int i;
70943  sqlite_int64 rowid;
70944  Mem **apArg;
70945  Mem *pX;
70946#endif /* local variables moved into u.cq */
70947
70948  assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
70949       || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
70950  );
70951  u.cq.pVtab = pOp->p4.pVtab->pVtab;
70952  u.cq.pModule = (sqlite3_module *)u.cq.pVtab->pModule;
70953  u.cq.nArg = pOp->p2;
70954  assert( pOp->p4type==P4_VTAB );
70955  if( ALWAYS(u.cq.pModule->xUpdate) ){
70956    u8 vtabOnConflict = db->vtabOnConflict;
70957    u.cq.apArg = p->apArg;
70958    u.cq.pX = &aMem[pOp->p3];
70959    for(u.cq.i=0; u.cq.i<u.cq.nArg; u.cq.i++){
70960      assert( memIsValid(u.cq.pX) );
70961      memAboutToChange(p, u.cq.pX);
70962      sqlite3VdbeMemStoreType(u.cq.pX);
70963      u.cq.apArg[u.cq.i] = u.cq.pX;
70964      u.cq.pX++;
70965    }
70966    db->vtabOnConflict = pOp->p5;
70967    rc = u.cq.pModule->xUpdate(u.cq.pVtab, u.cq.nArg, u.cq.apArg, &u.cq.rowid);
70968    db->vtabOnConflict = vtabOnConflict;
70969    importVtabErrMsg(p, u.cq.pVtab);
70970    if( rc==SQLITE_OK && pOp->p1 ){
70971      assert( u.cq.nArg>1 && u.cq.apArg[0] && (u.cq.apArg[0]->flags&MEM_Null) );
70972      db->lastRowid = lastRowid = u.cq.rowid;
70973    }
70974    if( rc==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
70975      if( pOp->p5==OE_Ignore ){
70976        rc = SQLITE_OK;
70977      }else{
70978        p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
70979      }
70980    }else{
70981      p->nChange++;
70982    }
70983  }
70984  break;
70985}
70986#endif /* SQLITE_OMIT_VIRTUALTABLE */
70987
70988#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
70989/* Opcode: Pagecount P1 P2 * * *
70990**
70991** Write the current number of pages in database P1 to memory cell P2.
70992*/
70993case OP_Pagecount: {            /* out2-prerelease */
70994  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
70995  break;
70996}
70997#endif
70998
70999
71000#ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71001/* Opcode: MaxPgcnt P1 P2 P3 * *
71002**
71003** Try to set the maximum page count for database P1 to the value in P3.
71004** Do not let the maximum page count fall below the current page count and
71005** do not change the maximum page count value if P3==0.
71006**
71007** Store the maximum page count after the change in register P2.
71008*/
71009case OP_MaxPgcnt: {            /* out2-prerelease */
71010  unsigned int newMax;
71011  Btree *pBt;
71012
71013  pBt = db->aDb[pOp->p1].pBt;
71014  newMax = 0;
71015  if( pOp->p3 ){
71016    newMax = sqlite3BtreeLastPage(pBt);
71017    if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
71018  }
71019  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
71020  break;
71021}
71022#endif
71023
71024
71025#ifndef SQLITE_OMIT_TRACE
71026/* Opcode: Trace * * * P4 *
71027**
71028** If tracing is enabled (by the sqlite3_trace()) interface, then
71029** the UTF-8 string contained in P4 is emitted on the trace callback.
71030*/
71031case OP_Trace: {
71032#if 0  /* local variables moved into u.cr */
71033  char *zTrace;
71034  char *z;
71035#endif /* local variables moved into u.cr */
71036
71037  if( db->xTrace && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0 ){
71038    u.cr.z = sqlite3VdbeExpandSql(p, u.cr.zTrace);
71039    db->xTrace(db->pTraceArg, u.cr.z);
71040    sqlite3DbFree(db, u.cr.z);
71041  }
71042#ifdef SQLITE_DEBUG
71043  if( (db->flags & SQLITE_SqlTrace)!=0
71044   && (u.cr.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71045  ){
71046    sqlite3DebugPrintf("SQL-trace: %s\n", u.cr.zTrace);
71047  }
71048#endif /* SQLITE_DEBUG */
71049  break;
71050}
71051#endif
71052
71053
71054/* Opcode: Noop * * * * *
71055**
71056** Do nothing.  This instruction is often useful as a jump
71057** destination.
71058*/
71059/*
71060** The magic Explain opcode are only inserted when explain==2 (which
71061** is to say when the EXPLAIN QUERY PLAN syntax is used.)
71062** This opcode records information from the optimizer.  It is the
71063** the same as a no-op.  This opcodesnever appears in a real VM program.
71064*/
71065default: {          /* This is really OP_Noop and OP_Explain */
71066  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
71067  break;
71068}
71069
71070/*****************************************************************************
71071** The cases of the switch statement above this line should all be indented
71072** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
71073** readability.  From this point on down, the normal indentation rules are
71074** restored.
71075*****************************************************************************/
71076    }
71077
71078#ifdef VDBE_PROFILE
71079    {
71080      u64 elapsed = sqlite3Hwtime() - start;
71081      pOp->cycles += elapsed;
71082      pOp->cnt++;
71083#if 0
71084        fprintf(stdout, "%10llu ", elapsed);
71085        sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
71086#endif
71087    }
71088#endif
71089
71090    /* The following code adds nothing to the actual functionality
71091    ** of the program.  It is only here for testing and debugging.
71092    ** On the other hand, it does burn CPU cycles every time through
71093    ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
71094    */
71095#ifndef NDEBUG
71096    assert( pc>=-1 && pc<p->nOp );
71097
71098#ifdef SQLITE_DEBUG
71099    if( p->trace ){
71100      if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
71101      if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
71102        registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
71103      }
71104      if( pOp->opflags & OPFLG_OUT3 ){
71105        registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
71106      }
71107    }
71108#endif  /* SQLITE_DEBUG */
71109#endif  /* NDEBUG */
71110  }  /* The end of the for(;;) loop the loops through opcodes */
71111
71112  /* If we reach this point, it means that execution is finished with
71113  ** an error of some kind.
71114  */
71115vdbe_error_halt:
71116  assert( rc );
71117  p->rc = rc;
71118  testcase( sqlite3GlobalConfig.xLog!=0 );
71119  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
71120                   pc, p->zSql, p->zErrMsg);
71121  sqlite3VdbeHalt(p);
71122  if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
71123  rc = SQLITE_ERROR;
71124  if( resetSchemaOnFault>0 ){
71125    sqlite3ResetInternalSchema(db, resetSchemaOnFault-1);
71126  }
71127
71128  /* This is the only way out of this procedure.  We have to
71129  ** release the mutexes on btrees that were acquired at the
71130  ** top. */
71131vdbe_return:
71132  db->lastRowid = lastRowid;
71133  sqlite3VdbeLeave(p);
71134  return rc;
71135
71136  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
71137  ** is encountered.
71138  */
71139too_big:
71140  sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
71141  rc = SQLITE_TOOBIG;
71142  goto vdbe_error_halt;
71143
71144  /* Jump to here if a malloc() fails.
71145  */
71146no_mem:
71147  db->mallocFailed = 1;
71148  sqlite3SetString(&p->zErrMsg, db, "out of memory");
71149  rc = SQLITE_NOMEM;
71150  goto vdbe_error_halt;
71151
71152  /* Jump to here for any other kind of fatal error.  The "rc" variable
71153  ** should hold the error number.
71154  */
71155abort_due_to_error:
71156  assert( p->zErrMsg==0 );
71157  if( db->mallocFailed ) rc = SQLITE_NOMEM;
71158  if( rc!=SQLITE_IOERR_NOMEM ){
71159    sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71160  }
71161  goto vdbe_error_halt;
71162
71163  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
71164  ** flag.
71165  */
71166abort_due_to_interrupt:
71167  assert( db->u1.isInterrupted );
71168  rc = SQLITE_INTERRUPT;
71169  p->rc = rc;
71170  sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71171  goto vdbe_error_halt;
71172}
71173
71174/************** End of vdbe.c ************************************************/
71175/************** Begin file vdbeblob.c ****************************************/
71176/*
71177** 2007 May 1
71178**
71179** The author disclaims copyright to this source code.  In place of
71180** a legal notice, here is a blessing:
71181**
71182**    May you do good and not evil.
71183**    May you find forgiveness for yourself and forgive others.
71184**    May you share freely, never taking more than you give.
71185**
71186*************************************************************************
71187**
71188** This file contains code used to implement incremental BLOB I/O.
71189*/
71190
71191
71192#ifndef SQLITE_OMIT_INCRBLOB
71193
71194/*
71195** Valid sqlite3_blob* handles point to Incrblob structures.
71196*/
71197typedef struct Incrblob Incrblob;
71198struct Incrblob {
71199  int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
71200  int nByte;              /* Size of open blob, in bytes */
71201  int iOffset;            /* Byte offset of blob in cursor data */
71202  int iCol;               /* Table column this handle is open on */
71203  BtCursor *pCsr;         /* Cursor pointing at blob row */
71204  sqlite3_stmt *pStmt;    /* Statement holding cursor open */
71205  sqlite3 *db;            /* The associated database */
71206};
71207
71208
71209/*
71210** This function is used by both blob_open() and blob_reopen(). It seeks
71211** the b-tree cursor associated with blob handle p to point to row iRow.
71212** If successful, SQLITE_OK is returned and subsequent calls to
71213** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
71214**
71215** If an error occurs, or if the specified row does not exist or does not
71216** contain a value of type TEXT or BLOB in the column nominated when the
71217** blob handle was opened, then an error code is returned and *pzErr may
71218** be set to point to a buffer containing an error message. It is the
71219** responsibility of the caller to free the error message buffer using
71220** sqlite3DbFree().
71221**
71222** If an error does occur, then the b-tree cursor is closed. All subsequent
71223** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
71224** immediately return SQLITE_ABORT.
71225*/
71226static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
71227  int rc;                         /* Error code */
71228  char *zErr = 0;                 /* Error message */
71229  Vdbe *v = (Vdbe *)p->pStmt;
71230
71231  /* Set the value of the SQL statements only variable to integer iRow.
71232  ** This is done directly instead of using sqlite3_bind_int64() to avoid
71233  ** triggering asserts related to mutexes.
71234  */
71235  assert( v->aVar[0].flags&MEM_Int );
71236  v->aVar[0].u.i = iRow;
71237
71238  rc = sqlite3_step(p->pStmt);
71239  if( rc==SQLITE_ROW ){
71240    u32 type = v->apCsr[0]->aType[p->iCol];
71241    if( type<12 ){
71242      zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
71243          type==0?"null": type==7?"real": "integer"
71244      );
71245      rc = SQLITE_ERROR;
71246      sqlite3_finalize(p->pStmt);
71247      p->pStmt = 0;
71248    }else{
71249      p->iOffset = v->apCsr[0]->aOffset[p->iCol];
71250      p->nByte = sqlite3VdbeSerialTypeLen(type);
71251      p->pCsr =  v->apCsr[0]->pCursor;
71252      sqlite3BtreeEnterCursor(p->pCsr);
71253      sqlite3BtreeCacheOverflow(p->pCsr);
71254      sqlite3BtreeLeaveCursor(p->pCsr);
71255    }
71256  }
71257
71258  if( rc==SQLITE_ROW ){
71259    rc = SQLITE_OK;
71260  }else if( p->pStmt ){
71261    rc = sqlite3_finalize(p->pStmt);
71262    p->pStmt = 0;
71263    if( rc==SQLITE_OK ){
71264      zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
71265      rc = SQLITE_ERROR;
71266    }else{
71267      zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
71268    }
71269  }
71270
71271  assert( rc!=SQLITE_OK || zErr==0 );
71272  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
71273
71274  *pzErr = zErr;
71275  return rc;
71276}
71277
71278/*
71279** Open a blob handle.
71280*/
71281SQLITE_API int sqlite3_blob_open(
71282  sqlite3* db,            /* The database connection */
71283  const char *zDb,        /* The attached database containing the blob */
71284  const char *zTable,     /* The table containing the blob */
71285  const char *zColumn,    /* The column containing the blob */
71286  sqlite_int64 iRow,      /* The row containing the glob */
71287  int flags,              /* True -> read/write access, false -> read-only */
71288  sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
71289){
71290  int nAttempt = 0;
71291  int iCol;               /* Index of zColumn in row-record */
71292
71293  /* This VDBE program seeks a btree cursor to the identified
71294  ** db/table/row entry. The reason for using a vdbe program instead
71295  ** of writing code to use the b-tree layer directly is that the
71296  ** vdbe program will take advantage of the various transaction,
71297  ** locking and error handling infrastructure built into the vdbe.
71298  **
71299  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
71300  ** Code external to the Vdbe then "borrows" the b-tree cursor and
71301  ** uses it to implement the blob_read(), blob_write() and
71302  ** blob_bytes() functions.
71303  **
71304  ** The sqlite3_blob_close() function finalizes the vdbe program,
71305  ** which closes the b-tree cursor and (possibly) commits the
71306  ** transaction.
71307  */
71308  static const VdbeOpList openBlob[] = {
71309    {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
71310    {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
71311    {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
71312
71313    /* One of the following two instructions is replaced by an OP_Noop. */
71314    {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
71315    {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
71316
71317    {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
71318    {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
71319    {OP_Column, 0, 0, 1},          /* 7  */
71320    {OP_ResultRow, 1, 0, 0},       /* 8  */
71321    {OP_Goto, 0, 5, 0},            /* 9  */
71322    {OP_Close, 0, 0, 0},           /* 10 */
71323    {OP_Halt, 0, 0, 0},            /* 11 */
71324  };
71325
71326  int rc = SQLITE_OK;
71327  char *zErr = 0;
71328  Table *pTab;
71329  Parse *pParse = 0;
71330  Incrblob *pBlob = 0;
71331
71332  flags = !!flags;                /* flags = (flags ? 1 : 0); */
71333  *ppBlob = 0;
71334
71335  sqlite3_mutex_enter(db->mutex);
71336
71337  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
71338  if( !pBlob ) goto blob_open_out;
71339  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
71340  if( !pParse ) goto blob_open_out;
71341
71342  do {
71343    memset(pParse, 0, sizeof(Parse));
71344    pParse->db = db;
71345    sqlite3DbFree(db, zErr);
71346    zErr = 0;
71347
71348    sqlite3BtreeEnterAll(db);
71349    pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
71350    if( pTab && IsVirtual(pTab) ){
71351      pTab = 0;
71352      sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
71353    }
71354#ifndef SQLITE_OMIT_VIEW
71355    if( pTab && pTab->pSelect ){
71356      pTab = 0;
71357      sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
71358    }
71359#endif
71360    if( !pTab ){
71361      if( pParse->zErrMsg ){
71362        sqlite3DbFree(db, zErr);
71363        zErr = pParse->zErrMsg;
71364        pParse->zErrMsg = 0;
71365      }
71366      rc = SQLITE_ERROR;
71367      sqlite3BtreeLeaveAll(db);
71368      goto blob_open_out;
71369    }
71370
71371    /* Now search pTab for the exact column. */
71372    for(iCol=0; iCol<pTab->nCol; iCol++) {
71373      if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
71374        break;
71375      }
71376    }
71377    if( iCol==pTab->nCol ){
71378      sqlite3DbFree(db, zErr);
71379      zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
71380      rc = SQLITE_ERROR;
71381      sqlite3BtreeLeaveAll(db);
71382      goto blob_open_out;
71383    }
71384
71385    /* If the value is being opened for writing, check that the
71386    ** column is not indexed, and that it is not part of a foreign key.
71387    ** It is against the rules to open a column to which either of these
71388    ** descriptions applies for writing.  */
71389    if( flags ){
71390      const char *zFault = 0;
71391      Index *pIdx;
71392#ifndef SQLITE_OMIT_FOREIGN_KEY
71393      if( db->flags&SQLITE_ForeignKeys ){
71394        /* Check that the column is not part of an FK child key definition. It
71395        ** is not necessary to check if it is part of a parent key, as parent
71396        ** key columns must be indexed. The check below will pick up this
71397        ** case.  */
71398        FKey *pFKey;
71399        for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
71400          int j;
71401          for(j=0; j<pFKey->nCol; j++){
71402            if( pFKey->aCol[j].iFrom==iCol ){
71403              zFault = "foreign key";
71404            }
71405          }
71406        }
71407      }
71408#endif
71409      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71410        int j;
71411        for(j=0; j<pIdx->nColumn; j++){
71412          if( pIdx->aiColumn[j]==iCol ){
71413            zFault = "indexed";
71414          }
71415        }
71416      }
71417      if( zFault ){
71418        sqlite3DbFree(db, zErr);
71419        zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
71420        rc = SQLITE_ERROR;
71421        sqlite3BtreeLeaveAll(db);
71422        goto blob_open_out;
71423      }
71424    }
71425
71426    pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
71427    assert( pBlob->pStmt || db->mallocFailed );
71428    if( pBlob->pStmt ){
71429      Vdbe *v = (Vdbe *)pBlob->pStmt;
71430      int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71431
71432      sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
71433
71434
71435      /* Configure the OP_Transaction */
71436      sqlite3VdbeChangeP1(v, 0, iDb);
71437      sqlite3VdbeChangeP2(v, 0, flags);
71438
71439      /* Configure the OP_VerifyCookie */
71440      sqlite3VdbeChangeP1(v, 1, iDb);
71441      sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
71442      sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
71443
71444      /* Make sure a mutex is held on the table to be accessed */
71445      sqlite3VdbeUsesBtree(v, iDb);
71446
71447      /* Configure the OP_TableLock instruction */
71448#ifdef SQLITE_OMIT_SHARED_CACHE
71449      sqlite3VdbeChangeToNoop(v, 2);
71450#else
71451      sqlite3VdbeChangeP1(v, 2, iDb);
71452      sqlite3VdbeChangeP2(v, 2, pTab->tnum);
71453      sqlite3VdbeChangeP3(v, 2, flags);
71454      sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
71455#endif
71456
71457      /* Remove either the OP_OpenWrite or OpenRead. Set the P2
71458      ** parameter of the other to pTab->tnum.  */
71459      sqlite3VdbeChangeToNoop(v, 4 - flags);
71460      sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
71461      sqlite3VdbeChangeP3(v, 3 + flags, iDb);
71462
71463      /* Configure the number of columns. Configure the cursor to
71464      ** think that the table has one more column than it really
71465      ** does. An OP_Column to retrieve this imaginary column will
71466      ** always return an SQL NULL. This is useful because it means
71467      ** we can invoke OP_Column to fill in the vdbe cursors type
71468      ** and offset cache without causing any IO.
71469      */
71470      sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
71471      sqlite3VdbeChangeP2(v, 7, pTab->nCol);
71472      if( !db->mallocFailed ){
71473        pParse->nVar = 1;
71474        pParse->nMem = 1;
71475        pParse->nTab = 1;
71476        sqlite3VdbeMakeReady(v, pParse);
71477      }
71478    }
71479
71480    pBlob->flags = flags;
71481    pBlob->iCol = iCol;
71482    pBlob->db = db;
71483    sqlite3BtreeLeaveAll(db);
71484    if( db->mallocFailed ){
71485      goto blob_open_out;
71486    }
71487    sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
71488    rc = blobSeekToRow(pBlob, iRow, &zErr);
71489  } while( (++nAttempt)<5 && rc==SQLITE_SCHEMA );
71490
71491blob_open_out:
71492  if( rc==SQLITE_OK && db->mallocFailed==0 ){
71493    *ppBlob = (sqlite3_blob *)pBlob;
71494  }else{
71495    if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
71496    sqlite3DbFree(db, pBlob);
71497  }
71498  sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
71499  sqlite3DbFree(db, zErr);
71500  sqlite3StackFree(db, pParse);
71501  rc = sqlite3ApiExit(db, rc);
71502  sqlite3_mutex_leave(db->mutex);
71503  return rc;
71504}
71505
71506/*
71507** Close a blob handle that was previously created using
71508** sqlite3_blob_open().
71509*/
71510SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
71511  Incrblob *p = (Incrblob *)pBlob;
71512  int rc;
71513  sqlite3 *db;
71514
71515  if( p ){
71516    db = p->db;
71517    sqlite3_mutex_enter(db->mutex);
71518    rc = sqlite3_finalize(p->pStmt);
71519    sqlite3DbFree(db, p);
71520    sqlite3_mutex_leave(db->mutex);
71521  }else{
71522    rc = SQLITE_OK;
71523  }
71524  return rc;
71525}
71526
71527/*
71528** Perform a read or write operation on a blob
71529*/
71530static int blobReadWrite(
71531  sqlite3_blob *pBlob,
71532  void *z,
71533  int n,
71534  int iOffset,
71535  int (*xCall)(BtCursor*, u32, u32, void*)
71536){
71537  int rc;
71538  Incrblob *p = (Incrblob *)pBlob;
71539  Vdbe *v;
71540  sqlite3 *db;
71541
71542  if( p==0 ) return SQLITE_MISUSE_BKPT;
71543  db = p->db;
71544  sqlite3_mutex_enter(db->mutex);
71545  v = (Vdbe*)p->pStmt;
71546
71547  if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
71548    /* Request is out of range. Return a transient error. */
71549    rc = SQLITE_ERROR;
71550    sqlite3Error(db, SQLITE_ERROR, 0);
71551  }else if( v==0 ){
71552    /* If there is no statement handle, then the blob-handle has
71553    ** already been invalidated. Return SQLITE_ABORT in this case.
71554    */
71555    rc = SQLITE_ABORT;
71556  }else{
71557    /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
71558    ** returned, clean-up the statement handle.
71559    */
71560    assert( db == v->db );
71561    sqlite3BtreeEnterCursor(p->pCsr);
71562    rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
71563    sqlite3BtreeLeaveCursor(p->pCsr);
71564    if( rc==SQLITE_ABORT ){
71565      sqlite3VdbeFinalize(v);
71566      p->pStmt = 0;
71567    }else{
71568      db->errCode = rc;
71569      v->rc = rc;
71570    }
71571  }
71572  rc = sqlite3ApiExit(db, rc);
71573  sqlite3_mutex_leave(db->mutex);
71574  return rc;
71575}
71576
71577/*
71578** Read data from a blob handle.
71579*/
71580SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
71581  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
71582}
71583
71584/*
71585** Write data to a blob handle.
71586*/
71587SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
71588  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
71589}
71590
71591/*
71592** Query a blob handle for the size of the data.
71593**
71594** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
71595** so no mutex is required for access.
71596*/
71597SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
71598  Incrblob *p = (Incrblob *)pBlob;
71599  return (p && p->pStmt) ? p->nByte : 0;
71600}
71601
71602/*
71603** Move an existing blob handle to point to a different row of the same
71604** database table.
71605**
71606** If an error occurs, or if the specified row does not exist or does not
71607** contain a blob or text value, then an error code is returned and the
71608** database handle error code and message set. If this happens, then all
71609** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
71610** immediately return SQLITE_ABORT.
71611*/
71612SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
71613  int rc;
71614  Incrblob *p = (Incrblob *)pBlob;
71615  sqlite3 *db;
71616
71617  if( p==0 ) return SQLITE_MISUSE_BKPT;
71618  db = p->db;
71619  sqlite3_mutex_enter(db->mutex);
71620
71621  if( p->pStmt==0 ){
71622    /* If there is no statement handle, then the blob-handle has
71623    ** already been invalidated. Return SQLITE_ABORT in this case.
71624    */
71625    rc = SQLITE_ABORT;
71626  }else{
71627    char *zErr;
71628    rc = blobSeekToRow(p, iRow, &zErr);
71629    if( rc!=SQLITE_OK ){
71630      sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
71631      sqlite3DbFree(db, zErr);
71632    }
71633    assert( rc!=SQLITE_SCHEMA );
71634  }
71635
71636  rc = sqlite3ApiExit(db, rc);
71637  assert( rc==SQLITE_OK || p->pStmt==0 );
71638  sqlite3_mutex_leave(db->mutex);
71639  return rc;
71640}
71641
71642#endif /* #ifndef SQLITE_OMIT_INCRBLOB */
71643
71644/************** End of vdbeblob.c ********************************************/
71645/************** Begin file vdbesort.c ****************************************/
71646/*
71647** 2011 July 9
71648**
71649** The author disclaims copyright to this source code.  In place of
71650** a legal notice, here is a blessing:
71651**
71652**    May you do good and not evil.
71653**    May you find forgiveness for yourself and forgive others.
71654**    May you share freely, never taking more than you give.
71655**
71656*************************************************************************
71657** This file contains code for the VdbeSorter object, used in concert with
71658** a VdbeCursor to sort large numbers of keys (as may be required, for
71659** example, by CREATE INDEX statements on tables too large to fit in main
71660** memory).
71661*/
71662
71663
71664#ifndef SQLITE_OMIT_MERGE_SORT
71665
71666typedef struct VdbeSorterIter VdbeSorterIter;
71667typedef struct SorterRecord SorterRecord;
71668
71669/*
71670** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
71671**
71672** As keys are added to the sorter, they are written to disk in a series
71673** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
71674** the same as the cache-size allowed for temporary databases. In order
71675** to allow the caller to extract keys from the sorter in sorted order,
71676** all PMAs currently stored on disk must be merged together. This comment
71677** describes the data structure used to do so. The structure supports
71678** merging any number of arrays in a single pass with no redundant comparison
71679** operations.
71680**
71681** The aIter[] array contains an iterator for each of the PMAs being merged.
71682** An aIter[] iterator either points to a valid key or else is at EOF. For
71683** the purposes of the paragraphs below, we assume that the array is actually
71684** N elements in size, where N is the smallest power of 2 greater to or equal
71685** to the number of iterators being merged. The extra aIter[] elements are
71686** treated as if they are empty (always at EOF).
71687**
71688** The aTree[] array is also N elements in size. The value of N is stored in
71689** the VdbeSorter.nTree variable.
71690**
71691** The final (N/2) elements of aTree[] contain the results of comparing
71692** pairs of iterator keys together. Element i contains the result of
71693** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
71694** aTree element is set to the index of it.
71695**
71696** For the purposes of this comparison, EOF is considered greater than any
71697** other key value. If the keys are equal (only possible with two EOF
71698** values), it doesn't matter which index is stored.
71699**
71700** The (N/4) elements of aTree[] that preceed the final (N/2) described
71701** above contains the index of the smallest of each block of 4 iterators.
71702** And so on. So that aTree[1] contains the index of the iterator that
71703** currently points to the smallest key value. aTree[0] is unused.
71704**
71705** Example:
71706**
71707**     aIter[0] -> Banana
71708**     aIter[1] -> Feijoa
71709**     aIter[2] -> Elderberry
71710**     aIter[3] -> Currant
71711**     aIter[4] -> Grapefruit
71712**     aIter[5] -> Apple
71713**     aIter[6] -> Durian
71714**     aIter[7] -> EOF
71715**
71716**     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
71717**
71718** The current element is "Apple" (the value of the key indicated by
71719** iterator 5). When the Next() operation is invoked, iterator 5 will
71720** be advanced to the next key in its segment. Say the next key is
71721** "Eggplant":
71722**
71723**     aIter[5] -> Eggplant
71724**
71725** The contents of aTree[] are updated first by comparing the new iterator
71726** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
71727** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
71728** The value of iterator 6 - "Durian" - is now smaller than that of iterator
71729** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
71730** so the value written into element 1 of the array is 0. As follows:
71731**
71732**     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
71733**
71734** In other words, each time we advance to the next sorter element, log2(N)
71735** key comparison operations are required, where N is the number of segments
71736** being merged (rounded up to the next power of 2).
71737*/
71738struct VdbeSorter {
71739  i64 iWriteOff;                  /* Current write offset within file pTemp1 */
71740  i64 iReadOff;                   /* Current read offset within file pTemp1 */
71741  int nInMemory;                  /* Current size of pRecord list as PMA */
71742  int nTree;                      /* Used size of aTree/aIter (power of 2) */
71743  int nPMA;                       /* Number of PMAs stored in pTemp1 */
71744  int mnPmaSize;                  /* Minimum PMA size, in bytes */
71745  int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
71746  VdbeSorterIter *aIter;          /* Array of iterators to merge */
71747  int *aTree;                     /* Current state of incremental merge */
71748  sqlite3_file *pTemp1;           /* PMA file 1 */
71749  SorterRecord *pRecord;          /* Head of in-memory record list */
71750  UnpackedRecord *pUnpacked;      /* Used to unpack keys */
71751};
71752
71753/*
71754** The following type is an iterator for a PMA. It caches the current key in
71755** variables nKey/aKey. If the iterator is at EOF, pFile==0.
71756*/
71757struct VdbeSorterIter {
71758  i64 iReadOff;                   /* Current read offset */
71759  i64 iEof;                       /* 1 byte past EOF for this iterator */
71760  int nAlloc;                     /* Bytes of space at aAlloc */
71761  int nKey;                       /* Number of bytes in key */
71762  sqlite3_file *pFile;            /* File iterator is reading from */
71763  u8 *aAlloc;                     /* Allocated space */
71764  u8 *aKey;                       /* Pointer to current key */
71765};
71766
71767/*
71768** A structure to store a single record. All in-memory records are connected
71769** together into a linked list headed at VdbeSorter.pRecord using the
71770** SorterRecord.pNext pointer.
71771*/
71772struct SorterRecord {
71773  void *pVal;
71774  int nVal;
71775  SorterRecord *pNext;
71776};
71777
71778/* Minimum allowable value for the VdbeSorter.nWorking variable */
71779#define SORTER_MIN_WORKING 10
71780
71781/* Maximum number of segments to merge in a single pass. */
71782#define SORTER_MAX_MERGE_COUNT 16
71783
71784/*
71785** Free all memory belonging to the VdbeSorterIter object passed as the second
71786** argument. All structure fields are set to zero before returning.
71787*/
71788static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
71789  sqlite3DbFree(db, pIter->aAlloc);
71790  memset(pIter, 0, sizeof(VdbeSorterIter));
71791}
71792
71793/*
71794** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
71795** no error occurs, or an SQLite error code if one does.
71796*/
71797static int vdbeSorterIterNext(
71798  sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
71799  VdbeSorterIter *pIter           /* Iterator to advance */
71800){
71801  int rc;                         /* Return Code */
71802  int nRead;                      /* Number of bytes read */
71803  int nRec = 0;                   /* Size of record in bytes */
71804  int iOff = 0;                   /* Size of serialized size varint in bytes */
71805
71806  assert( pIter->iEof>=pIter->iReadOff );
71807  if( pIter->iEof-pIter->iReadOff>5 ){
71808    nRead = 5;
71809  }else{
71810    nRead = (int)(pIter->iEof - pIter->iReadOff);
71811  }
71812  if( nRead<=0 ){
71813    /* This is an EOF condition */
71814    vdbeSorterIterZero(db, pIter);
71815    return SQLITE_OK;
71816  }
71817
71818  rc = sqlite3OsRead(pIter->pFile, pIter->aAlloc, nRead, pIter->iReadOff);
71819  if( rc==SQLITE_OK ){
71820    iOff = getVarint32(pIter->aAlloc, nRec);
71821    if( (iOff+nRec)>nRead ){
71822      int nRead2;                   /* Number of extra bytes to read */
71823      if( (iOff+nRec)>pIter->nAlloc ){
71824        int nNew = pIter->nAlloc*2;
71825        while( (iOff+nRec)>nNew ) nNew = nNew*2;
71826        pIter->aAlloc = sqlite3DbReallocOrFree(db, pIter->aAlloc, nNew);
71827        if( !pIter->aAlloc ) return SQLITE_NOMEM;
71828        pIter->nAlloc = nNew;
71829      }
71830
71831      nRead2 = iOff + nRec - nRead;
71832      rc = sqlite3OsRead(
71833          pIter->pFile, &pIter->aAlloc[nRead], nRead2, pIter->iReadOff+nRead
71834      );
71835    }
71836  }
71837
71838  assert( rc!=SQLITE_OK || nRec>0 );
71839  pIter->iReadOff += iOff+nRec;
71840  pIter->nKey = nRec;
71841  pIter->aKey = &pIter->aAlloc[iOff];
71842  return rc;
71843}
71844
71845/*
71846** Write a single varint, value iVal, to file-descriptor pFile. Return
71847** SQLITE_OK if successful, or an SQLite error code if some error occurs.
71848**
71849** The value of *piOffset when this function is called is used as the byte
71850** offset in file pFile to write to. Before returning, *piOffset is
71851** incremented by the number of bytes written.
71852*/
71853static int vdbeSorterWriteVarint(
71854  sqlite3_file *pFile,            /* File to write to */
71855  i64 iVal,                       /* Value to write as a varint */
71856  i64 *piOffset                   /* IN/OUT: Write offset in file pFile */
71857){
71858  u8 aVarint[9];                  /* Buffer large enough for a varint */
71859  int nVarint;                    /* Number of used bytes in varint */
71860  int rc;                         /* Result of write() call */
71861
71862  nVarint = sqlite3PutVarint(aVarint, iVal);
71863  rc = sqlite3OsWrite(pFile, aVarint, nVarint, *piOffset);
71864  *piOffset += nVarint;
71865
71866  return rc;
71867}
71868
71869/*
71870** Read a single varint from file-descriptor pFile. Return SQLITE_OK if
71871** successful, or an SQLite error code if some error occurs.
71872**
71873** The value of *piOffset when this function is called is used as the
71874** byte offset in file pFile from whence to read the varint. If successful
71875** (i.e. if no IO error occurs), then *piOffset is set to the offset of
71876** the first byte past the end of the varint before returning. *piVal is
71877** set to the integer value read. If an error occurs, the final values of
71878** both *piOffset and *piVal are undefined.
71879*/
71880static int vdbeSorterReadVarint(
71881  sqlite3_file *pFile,            /* File to read from */
71882  i64 *piOffset,                  /* IN/OUT: Read offset in pFile */
71883  i64 *piVal                      /* OUT: Value read from file */
71884){
71885  u8 aVarint[9];                  /* Buffer large enough for a varint */
71886  i64 iOff = *piOffset;           /* Offset in file to read from */
71887  int rc;                         /* Return code */
71888
71889  rc = sqlite3OsRead(pFile, aVarint, 9, iOff);
71890  if( rc==SQLITE_OK ){
71891    *piOffset += getVarint(aVarint, (u64 *)piVal);
71892  }
71893
71894  return rc;
71895}
71896
71897/*
71898** Initialize iterator pIter to scan through the PMA stored in file pFile
71899** starting at offset iStart and ending at offset iEof-1. This function
71900** leaves the iterator pointing to the first key in the PMA (or EOF if the
71901** PMA is empty).
71902*/
71903static int vdbeSorterIterInit(
71904  sqlite3 *db,                    /* Database handle */
71905  VdbeSorter *pSorter,            /* Sorter object */
71906  i64 iStart,                     /* Start offset in pFile */
71907  VdbeSorterIter *pIter,          /* Iterator to populate */
71908  i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
71909){
71910  int rc;
71911
71912  assert( pSorter->iWriteOff>iStart );
71913  assert( pIter->aAlloc==0 );
71914  pIter->pFile = pSorter->pTemp1;
71915  pIter->iReadOff = iStart;
71916  pIter->nAlloc = 128;
71917  pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
71918  if( !pIter->aAlloc ){
71919    rc = SQLITE_NOMEM;
71920  }else{
71921    i64 nByte;                         /* Total size of PMA in bytes */
71922    rc = vdbeSorterReadVarint(pSorter->pTemp1, &pIter->iReadOff, &nByte);
71923    *pnByte += nByte;
71924    pIter->iEof = pIter->iReadOff + nByte;
71925  }
71926  if( rc==SQLITE_OK ){
71927    rc = vdbeSorterIterNext(db, pIter);
71928  }
71929  return rc;
71930}
71931
71932
71933/*
71934** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
71935** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
71936** used by the comparison. If an error occurs, return an SQLite error code.
71937** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
71938** value, depending on whether key1 is smaller, equal to or larger than key2.
71939**
71940** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
71941** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
71942** is true and key1 contains even a single NULL value, it is considered to
71943** be less than key2. Even if key2 also contains NULL values.
71944**
71945** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
71946** has been allocated and contains an unpacked record that is used as key2.
71947*/
71948static void vdbeSorterCompare(
71949  VdbeCursor *pCsr,               /* Cursor object (for pKeyInfo) */
71950  int bOmitRowid,                 /* Ignore rowid field at end of keys */
71951  void *pKey1, int nKey1,         /* Left side of comparison */
71952  void *pKey2, int nKey2,         /* Right side of comparison */
71953  int *pRes                       /* OUT: Result of comparison */
71954){
71955  KeyInfo *pKeyInfo = pCsr->pKeyInfo;
71956  VdbeSorter *pSorter = pCsr->pSorter;
71957  UnpackedRecord *r2 = pSorter->pUnpacked;
71958  int i;
71959
71960  if( pKey2 ){
71961    sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
71962  }
71963
71964  if( bOmitRowid ){
71965    r2->nField = pKeyInfo->nField;
71966    assert( r2->nField>0 );
71967    for(i=0; i<r2->nField; i++){
71968      if( r2->aMem[i].flags & MEM_Null ){
71969        *pRes = -1;
71970        return;
71971      }
71972    }
71973    r2->flags |= UNPACKED_PREFIX_MATCH;
71974  }
71975
71976  *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
71977}
71978
71979/*
71980** This function is called to compare two iterator keys when merging
71981** multiple b-tree segments. Parameter iOut is the index of the aTree[]
71982** value to recalculate.
71983*/
71984static int vdbeSorterDoCompare(VdbeCursor *pCsr, int iOut){
71985  VdbeSorter *pSorter = pCsr->pSorter;
71986  int i1;
71987  int i2;
71988  int iRes;
71989  VdbeSorterIter *p1;
71990  VdbeSorterIter *p2;
71991
71992  assert( iOut<pSorter->nTree && iOut>0 );
71993
71994  if( iOut>=(pSorter->nTree/2) ){
71995    i1 = (iOut - pSorter->nTree/2) * 2;
71996    i2 = i1 + 1;
71997  }else{
71998    i1 = pSorter->aTree[iOut*2];
71999    i2 = pSorter->aTree[iOut*2+1];
72000  }
72001
72002  p1 = &pSorter->aIter[i1];
72003  p2 = &pSorter->aIter[i2];
72004
72005  if( p1->pFile==0 ){
72006    iRes = i2;
72007  }else if( p2->pFile==0 ){
72008    iRes = i1;
72009  }else{
72010    int res;
72011    assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
72012    vdbeSorterCompare(
72013        pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
72014    );
72015    if( res<=0 ){
72016      iRes = i1;
72017    }else{
72018      iRes = i2;
72019    }
72020  }
72021
72022  pSorter->aTree[iOut] = iRes;
72023  return SQLITE_OK;
72024}
72025
72026/*
72027** Initialize the temporary index cursor just opened as a sorter cursor.
72028*/
72029SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
72030  int pgsz;                       /* Page size of main database */
72031  int mxCache;                    /* Cache size */
72032  VdbeSorter *pSorter;            /* The new sorter */
72033  char *d;                        /* Dummy */
72034
72035  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
72036  pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
72037  if( pSorter==0 ){
72038    return SQLITE_NOMEM;
72039  }
72040
72041  pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
72042  if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
72043  assert( pSorter->pUnpacked==(UnpackedRecord *)d );
72044
72045  if( !sqlite3TempInMemory(db) ){
72046    pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72047    pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
72048    mxCache = db->aDb[0].pSchema->cache_size;
72049    if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
72050    pSorter->mxPmaSize = mxCache * pgsz;
72051  }
72052
72053  return SQLITE_OK;
72054}
72055
72056/*
72057** Free the list of sorted records starting at pRecord.
72058*/
72059static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
72060  SorterRecord *p;
72061  SorterRecord *pNext;
72062  for(p=pRecord; p; p=pNext){
72063    pNext = p->pNext;
72064    sqlite3DbFree(db, p);
72065  }
72066}
72067
72068/*
72069** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
72070*/
72071SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
72072  VdbeSorter *pSorter = pCsr->pSorter;
72073  if( pSorter ){
72074    if( pSorter->aIter ){
72075      int i;
72076      for(i=0; i<pSorter->nTree; i++){
72077        vdbeSorterIterZero(db, &pSorter->aIter[i]);
72078      }
72079      sqlite3DbFree(db, pSorter->aIter);
72080    }
72081    if( pSorter->pTemp1 ){
72082      sqlite3OsCloseFree(pSorter->pTemp1);
72083    }
72084    vdbeSorterRecordFree(db, pSorter->pRecord);
72085    sqlite3DbFree(db, pSorter->pUnpacked);
72086    sqlite3DbFree(db, pSorter);
72087    pCsr->pSorter = 0;
72088  }
72089}
72090
72091/*
72092** Allocate space for a file-handle and open a temporary file. If successful,
72093** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
72094** Otherwise, set *ppFile to 0 and return an SQLite error code.
72095*/
72096static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
72097  int dummy;
72098  return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
72099      SQLITE_OPEN_TEMP_JOURNAL |
72100      SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
72101      SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
72102  );
72103}
72104
72105/*
72106** Merge the two sorted lists p1 and p2 into a single list.
72107** Set *ppOut to the head of the new list.
72108*/
72109static void vdbeSorterMerge(
72110  VdbeCursor *pCsr,               /* For pKeyInfo */
72111  SorterRecord *p1,               /* First list to merge */
72112  SorterRecord *p2,               /* Second list to merge */
72113  SorterRecord **ppOut            /* OUT: Head of merged list */
72114){
72115  SorterRecord *pFinal = 0;
72116  SorterRecord **pp = &pFinal;
72117  void *pVal2 = p2 ? p2->pVal : 0;
72118
72119  while( p1 && p2 ){
72120    int res;
72121    vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
72122    if( res<=0 ){
72123      *pp = p1;
72124      pp = &p1->pNext;
72125      p1 = p1->pNext;
72126      pVal2 = 0;
72127    }else{
72128      *pp = p2;
72129       pp = &p2->pNext;
72130      p2 = p2->pNext;
72131      if( p2==0 ) break;
72132      pVal2 = p2->pVal;
72133    }
72134  }
72135  *pp = p1 ? p1 : p2;
72136  *ppOut = pFinal;
72137}
72138
72139/*
72140** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
72141** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
72142** occurs.
72143*/
72144static int vdbeSorterSort(VdbeCursor *pCsr){
72145  int i;
72146  SorterRecord **aSlot;
72147  SorterRecord *p;
72148  VdbeSorter *pSorter = pCsr->pSorter;
72149
72150  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
72151  if( !aSlot ){
72152    return SQLITE_NOMEM;
72153  }
72154
72155  p = pSorter->pRecord;
72156  while( p ){
72157    SorterRecord *pNext = p->pNext;
72158    p->pNext = 0;
72159    for(i=0; aSlot[i]; i++){
72160      vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72161      aSlot[i] = 0;
72162    }
72163    aSlot[i] = p;
72164    p = pNext;
72165  }
72166
72167  p = 0;
72168  for(i=0; i<64; i++){
72169    vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72170  }
72171  pSorter->pRecord = p;
72172
72173  sqlite3_free(aSlot);
72174  return SQLITE_OK;
72175}
72176
72177
72178/*
72179** Write the current contents of the in-memory linked-list to a PMA. Return
72180** SQLITE_OK if successful, or an SQLite error code otherwise.
72181**
72182** The format of a PMA is:
72183**
72184**     * A varint. This varint contains the total number of bytes of content
72185**       in the PMA (not including the varint itself).
72186**
72187**     * One or more records packed end-to-end in order of ascending keys.
72188**       Each record consists of a varint followed by a blob of data (the
72189**       key). The varint is the number of bytes in the blob of data.
72190*/
72191static int vdbeSorterListToPMA(sqlite3 *db, VdbeCursor *pCsr){
72192  int rc = SQLITE_OK;             /* Return code */
72193  VdbeSorter *pSorter = pCsr->pSorter;
72194
72195  if( pSorter->nInMemory==0 ){
72196    assert( pSorter->pRecord==0 );
72197    return rc;
72198  }
72199
72200  rc = vdbeSorterSort(pCsr);
72201
72202  /* If the first temporary PMA file has not been opened, open it now. */
72203  if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
72204    rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
72205    assert( rc!=SQLITE_OK || pSorter->pTemp1 );
72206    assert( pSorter->iWriteOff==0 );
72207    assert( pSorter->nPMA==0 );
72208  }
72209
72210  if( rc==SQLITE_OK ){
72211    i64 iOff = pSorter->iWriteOff;
72212    SorterRecord *p;
72213    SorterRecord *pNext = 0;
72214    static const char eightZeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
72215
72216    pSorter->nPMA++;
72217    rc = vdbeSorterWriteVarint(pSorter->pTemp1, pSorter->nInMemory, &iOff);
72218    for(p=pSorter->pRecord; rc==SQLITE_OK && p; p=pNext){
72219      pNext = p->pNext;
72220      rc = vdbeSorterWriteVarint(pSorter->pTemp1, p->nVal, &iOff);
72221
72222      if( rc==SQLITE_OK ){
72223        rc = sqlite3OsWrite(pSorter->pTemp1, p->pVal, p->nVal, iOff);
72224        iOff += p->nVal;
72225      }
72226
72227      sqlite3DbFree(db, p);
72228    }
72229
72230    /* This assert verifies that unless an error has occurred, the size of
72231    ** the PMA on disk is the same as the expected size stored in
72232    ** pSorter->nInMemory. */
72233    assert( rc!=SQLITE_OK || pSorter->nInMemory==(
72234          iOff-pSorter->iWriteOff-sqlite3VarintLen(pSorter->nInMemory)
72235    ));
72236
72237    pSorter->iWriteOff = iOff;
72238    if( rc==SQLITE_OK ){
72239      /* Terminate each file with 8 extra bytes so that from any offset
72240      ** in the file we can always read 9 bytes without a SHORT_READ error */
72241      rc = sqlite3OsWrite(pSorter->pTemp1, eightZeros, 8, iOff);
72242    }
72243    pSorter->pRecord = p;
72244  }
72245
72246  return rc;
72247}
72248
72249/*
72250** Add a record to the sorter.
72251*/
72252SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
72253  sqlite3 *db,                    /* Database handle */
72254  VdbeCursor *pCsr,               /* Sorter cursor */
72255  Mem *pVal                       /* Memory cell containing record */
72256){
72257  VdbeSorter *pSorter = pCsr->pSorter;
72258  int rc = SQLITE_OK;             /* Return Code */
72259  SorterRecord *pNew;             /* New list element */
72260
72261  assert( pSorter );
72262  pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
72263
72264  pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
72265  if( pNew==0 ){
72266    rc = SQLITE_NOMEM;
72267  }else{
72268    pNew->pVal = (void *)&pNew[1];
72269    memcpy(pNew->pVal, pVal->z, pVal->n);
72270    pNew->nVal = pVal->n;
72271    pNew->pNext = pSorter->pRecord;
72272    pSorter->pRecord = pNew;
72273  }
72274
72275  /* See if the contents of the sorter should now be written out. They
72276  ** are written out when either of the following are true:
72277  **
72278  **   * The total memory allocated for the in-memory list is greater
72279  **     than (page-size * cache-size), or
72280  **
72281  **   * The total memory allocated for the in-memory list is greater
72282  **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
72283  */
72284  if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
72285        (pSorter->nInMemory>pSorter->mxPmaSize)
72286     || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
72287  )){
72288    rc = vdbeSorterListToPMA(db, pCsr);
72289    pSorter->nInMemory = 0;
72290  }
72291
72292  return rc;
72293}
72294
72295/*
72296** Helper function for sqlite3VdbeSorterRewind().
72297*/
72298static int vdbeSorterInitMerge(
72299  sqlite3 *db,                    /* Database handle */
72300  VdbeCursor *pCsr,               /* Cursor handle for this sorter */
72301  i64 *pnByte                     /* Sum of bytes in all opened PMAs */
72302){
72303  VdbeSorter *pSorter = pCsr->pSorter;
72304  int rc = SQLITE_OK;             /* Return code */
72305  int i;                          /* Used to iterator through aIter[] */
72306  i64 nByte = 0;                  /* Total bytes in all opened PMAs */
72307
72308  /* Initialize the iterators. */
72309  for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
72310    VdbeSorterIter *pIter = &pSorter->aIter[i];
72311    rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
72312    pSorter->iReadOff = pIter->iEof;
72313    assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
72314    if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
72315  }
72316
72317  /* Initialize the aTree[] array. */
72318  for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
72319    rc = vdbeSorterDoCompare(pCsr, i);
72320  }
72321
72322  *pnByte = nByte;
72323  return rc;
72324}
72325
72326/*
72327** Once the sorter has been populated, this function is called to prepare
72328** for iterating through its contents in sorted order.
72329*/
72330SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
72331  VdbeSorter *pSorter = pCsr->pSorter;
72332  int rc;                         /* Return code */
72333  sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
72334  i64 iWrite2 = 0;                /* Write offset for pTemp2 */
72335  int nIter;                      /* Number of iterators used */
72336  int nByte;                      /* Bytes of space required for aIter/aTree */
72337  int N = 2;                      /* Power of 2 >= nIter */
72338
72339  assert( pSorter );
72340
72341  /* If no data has been written to disk, then do not do so now. Instead,
72342  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
72343  ** from the in-memory list.  */
72344  if( pSorter->nPMA==0 ){
72345    *pbEof = !pSorter->pRecord;
72346    assert( pSorter->aTree==0 );
72347    return vdbeSorterSort(pCsr);
72348  }
72349
72350  /* Write the current b-tree to a PMA. Close the b-tree cursor. */
72351  rc = vdbeSorterListToPMA(db, pCsr);
72352  if( rc!=SQLITE_OK ) return rc;
72353
72354  /* Allocate space for aIter[] and aTree[]. */
72355  nIter = pSorter->nPMA;
72356  if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
72357  assert( nIter>0 );
72358  while( N<nIter ) N += N;
72359  nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
72360  pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
72361  if( !pSorter->aIter ) return SQLITE_NOMEM;
72362  pSorter->aTree = (int *)&pSorter->aIter[N];
72363  pSorter->nTree = N;
72364
72365  do {
72366    int iNew;                     /* Index of new, merged, PMA */
72367
72368    for(iNew=0;
72369        rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
72370        iNew++
72371    ){
72372      i64 nWrite;                 /* Number of bytes in new PMA */
72373
72374      /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
72375      ** initialize an iterator for each of them and break out of the loop.
72376      ** These iterators will be incrementally merged as the VDBE layer calls
72377      ** sqlite3VdbeSorterNext().
72378      **
72379      ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
72380      ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
72381      ** are merged into a single PMA that is written to file pTemp2.
72382      */
72383      rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
72384      assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
72385      if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
72386        break;
72387      }
72388
72389      /* Open the second temp file, if it is not already open. */
72390      if( pTemp2==0 ){
72391        assert( iWrite2==0 );
72392        rc = vdbeSorterOpenTempFile(db, &pTemp2);
72393      }
72394
72395      if( rc==SQLITE_OK ){
72396        rc = vdbeSorterWriteVarint(pTemp2, nWrite, &iWrite2);
72397      }
72398
72399      if( rc==SQLITE_OK ){
72400        int bEof = 0;
72401        while( rc==SQLITE_OK && bEof==0 ){
72402          int nToWrite;
72403          VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
72404          assert( pIter->pFile );
72405          nToWrite = pIter->nKey + sqlite3VarintLen(pIter->nKey);
72406          rc = sqlite3OsWrite(pTemp2, pIter->aAlloc, nToWrite, iWrite2);
72407          iWrite2 += nToWrite;
72408          if( rc==SQLITE_OK ){
72409            rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
72410          }
72411        }
72412      }
72413    }
72414
72415    if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
72416      break;
72417    }else{
72418      sqlite3_file *pTmp = pSorter->pTemp1;
72419      pSorter->nPMA = iNew;
72420      pSorter->pTemp1 = pTemp2;
72421      pTemp2 = pTmp;
72422      pSorter->iWriteOff = iWrite2;
72423      pSorter->iReadOff = 0;
72424      iWrite2 = 0;
72425    }
72426  }while( rc==SQLITE_OK );
72427
72428  if( pTemp2 ){
72429    sqlite3OsCloseFree(pTemp2);
72430  }
72431  *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
72432  return rc;
72433}
72434
72435/*
72436** Advance to the next element in the sorter.
72437*/
72438SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, VdbeCursor *pCsr, int *pbEof){
72439  VdbeSorter *pSorter = pCsr->pSorter;
72440  int rc;                         /* Return code */
72441
72442  if( pSorter->aTree ){
72443    int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
72444    int i;                        /* Index of aTree[] to recalculate */
72445
72446    rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
72447    for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
72448      rc = vdbeSorterDoCompare(pCsr, i);
72449    }
72450
72451    *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
72452  }else{
72453    SorterRecord *pFree = pSorter->pRecord;
72454    pSorter->pRecord = pFree->pNext;
72455    pFree->pNext = 0;
72456    vdbeSorterRecordFree(db, pFree);
72457    *pbEof = !pSorter->pRecord;
72458    rc = SQLITE_OK;
72459  }
72460  return rc;
72461}
72462
72463/*
72464** Return a pointer to a buffer owned by the sorter that contains the
72465** current key.
72466*/
72467static void *vdbeSorterRowkey(
72468  VdbeSorter *pSorter,            /* Sorter object */
72469  int *pnKey                      /* OUT: Size of current key in bytes */
72470){
72471  void *pKey;
72472  if( pSorter->aTree ){
72473    VdbeSorterIter *pIter;
72474    pIter = &pSorter->aIter[ pSorter->aTree[1] ];
72475    *pnKey = pIter->nKey;
72476    pKey = pIter->aKey;
72477  }else{
72478    *pnKey = pSorter->pRecord->nVal;
72479    pKey = pSorter->pRecord->pVal;
72480  }
72481  return pKey;
72482}
72483
72484/*
72485** Copy the current sorter key into the memory cell pOut.
72486*/
72487SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(VdbeCursor *pCsr, Mem *pOut){
72488  VdbeSorter *pSorter = pCsr->pSorter;
72489  void *pKey; int nKey;           /* Sorter key to copy into pOut */
72490
72491  pKey = vdbeSorterRowkey(pSorter, &nKey);
72492  if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
72493    return SQLITE_NOMEM;
72494  }
72495  pOut->n = nKey;
72496  MemSetTypeFlag(pOut, MEM_Blob);
72497  memcpy(pOut->z, pKey, nKey);
72498
72499  return SQLITE_OK;
72500}
72501
72502/*
72503** Compare the key in memory cell pVal with the key that the sorter cursor
72504** passed as the first argument currently points to. For the purposes of
72505** the comparison, ignore the rowid field at the end of each record.
72506**
72507** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
72508** Otherwise, set *pRes to a negative, zero or positive value if the
72509** key in pVal is smaller than, equal to or larger than the current sorter
72510** key.
72511*/
72512SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
72513  VdbeCursor *pCsr,               /* Sorter cursor */
72514  Mem *pVal,                      /* Value to compare to current sorter key */
72515  int *pRes                       /* OUT: Result of comparison */
72516){
72517  VdbeSorter *pSorter = pCsr->pSorter;
72518  void *pKey; int nKey;           /* Sorter key to compare pVal with */
72519
72520  pKey = vdbeSorterRowkey(pSorter, &nKey);
72521  vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
72522  return SQLITE_OK;
72523}
72524
72525#endif /* #ifndef SQLITE_OMIT_MERGE_SORT */
72526
72527/************** End of vdbesort.c ********************************************/
72528/************** Begin file journal.c *****************************************/
72529/*
72530** 2007 August 22
72531**
72532** The author disclaims copyright to this source code.  In place of
72533** a legal notice, here is a blessing:
72534**
72535**    May you do good and not evil.
72536**    May you find forgiveness for yourself and forgive others.
72537**    May you share freely, never taking more than you give.
72538**
72539*************************************************************************
72540**
72541** This file implements a special kind of sqlite3_file object used
72542** by SQLite to create journal files if the atomic-write optimization
72543** is enabled.
72544**
72545** The distinctive characteristic of this sqlite3_file is that the
72546** actual on disk file is created lazily. When the file is created,
72547** the caller specifies a buffer size for an in-memory buffer to
72548** be used to service read() and write() requests. The actual file
72549** on disk is not created or populated until either:
72550**
72551**   1) The in-memory representation grows too large for the allocated
72552**      buffer, or
72553**   2) The sqlite3JournalCreate() function is called.
72554*/
72555#ifdef SQLITE_ENABLE_ATOMIC_WRITE
72556
72557
72558/*
72559** A JournalFile object is a subclass of sqlite3_file used by
72560** as an open file handle for journal files.
72561*/
72562struct JournalFile {
72563  sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
72564  int nBuf;                       /* Size of zBuf[] in bytes */
72565  char *zBuf;                     /* Space to buffer journal writes */
72566  int iSize;                      /* Amount of zBuf[] currently used */
72567  int flags;                      /* xOpen flags */
72568  sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
72569  sqlite3_file *pReal;            /* The "real" underlying file descriptor */
72570  const char *zJournal;           /* Name of the journal file */
72571};
72572typedef struct JournalFile JournalFile;
72573
72574/*
72575** If it does not already exists, create and populate the on-disk file
72576** for JournalFile p.
72577*/
72578static int createFile(JournalFile *p){
72579  int rc = SQLITE_OK;
72580  if( !p->pReal ){
72581    sqlite3_file *pReal = (sqlite3_file *)&p[1];
72582    rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
72583    if( rc==SQLITE_OK ){
72584      p->pReal = pReal;
72585      if( p->iSize>0 ){
72586        assert(p->iSize<=p->nBuf);
72587        rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
72588      }
72589    }
72590  }
72591  return rc;
72592}
72593
72594/*
72595** Close the file.
72596*/
72597static int jrnlClose(sqlite3_file *pJfd){
72598  JournalFile *p = (JournalFile *)pJfd;
72599  if( p->pReal ){
72600    sqlite3OsClose(p->pReal);
72601  }
72602  sqlite3_free(p->zBuf);
72603  return SQLITE_OK;
72604}
72605
72606/*
72607** Read data from the file.
72608*/
72609static int jrnlRead(
72610  sqlite3_file *pJfd,    /* The journal file from which to read */
72611  void *zBuf,            /* Put the results here */
72612  int iAmt,              /* Number of bytes to read */
72613  sqlite_int64 iOfst     /* Begin reading at this offset */
72614){
72615  int rc = SQLITE_OK;
72616  JournalFile *p = (JournalFile *)pJfd;
72617  if( p->pReal ){
72618    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
72619  }else if( (iAmt+iOfst)>p->iSize ){
72620    rc = SQLITE_IOERR_SHORT_READ;
72621  }else{
72622    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
72623  }
72624  return rc;
72625}
72626
72627/*
72628** Write data to the file.
72629*/
72630static int jrnlWrite(
72631  sqlite3_file *pJfd,    /* The journal file into which to write */
72632  const void *zBuf,      /* Take data to be written from here */
72633  int iAmt,              /* Number of bytes to write */
72634  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
72635){
72636  int rc = SQLITE_OK;
72637  JournalFile *p = (JournalFile *)pJfd;
72638  if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
72639    rc = createFile(p);
72640  }
72641  if( rc==SQLITE_OK ){
72642    if( p->pReal ){
72643      rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
72644    }else{
72645      memcpy(&p->zBuf[iOfst], zBuf, iAmt);
72646      if( p->iSize<(iOfst+iAmt) ){
72647        p->iSize = (iOfst+iAmt);
72648      }
72649    }
72650  }
72651  return rc;
72652}
72653
72654/*
72655** Truncate the file.
72656*/
72657static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
72658  int rc = SQLITE_OK;
72659  JournalFile *p = (JournalFile *)pJfd;
72660  if( p->pReal ){
72661    rc = sqlite3OsTruncate(p->pReal, size);
72662  }else if( size<p->iSize ){
72663    p->iSize = size;
72664  }
72665  return rc;
72666}
72667
72668/*
72669** Sync the file.
72670*/
72671static int jrnlSync(sqlite3_file *pJfd, int flags){
72672  int rc;
72673  JournalFile *p = (JournalFile *)pJfd;
72674  if( p->pReal ){
72675    rc = sqlite3OsSync(p->pReal, flags);
72676  }else{
72677    rc = SQLITE_OK;
72678  }
72679  return rc;
72680}
72681
72682/*
72683** Query the size of the file in bytes.
72684*/
72685static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
72686  int rc = SQLITE_OK;
72687  JournalFile *p = (JournalFile *)pJfd;
72688  if( p->pReal ){
72689    rc = sqlite3OsFileSize(p->pReal, pSize);
72690  }else{
72691    *pSize = (sqlite_int64) p->iSize;
72692  }
72693  return rc;
72694}
72695
72696/*
72697** Table of methods for JournalFile sqlite3_file object.
72698*/
72699static struct sqlite3_io_methods JournalFileMethods = {
72700  1,             /* iVersion */
72701  jrnlClose,     /* xClose */
72702  jrnlRead,      /* xRead */
72703  jrnlWrite,     /* xWrite */
72704  jrnlTruncate,  /* xTruncate */
72705  jrnlSync,      /* xSync */
72706  jrnlFileSize,  /* xFileSize */
72707  0,             /* xLock */
72708  0,             /* xUnlock */
72709  0,             /* xCheckReservedLock */
72710  0,             /* xFileControl */
72711  0,             /* xSectorSize */
72712  0,             /* xDeviceCharacteristics */
72713  0,             /* xShmMap */
72714  0,             /* xShmLock */
72715  0,             /* xShmBarrier */
72716  0              /* xShmUnmap */
72717};
72718
72719/*
72720** Open a journal file.
72721*/
72722SQLITE_PRIVATE int sqlite3JournalOpen(
72723  sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
72724  const char *zName,         /* Name of the journal file */
72725  sqlite3_file *pJfd,        /* Preallocated, blank file handle */
72726  int flags,                 /* Opening flags */
72727  int nBuf                   /* Bytes buffered before opening the file */
72728){
72729  JournalFile *p = (JournalFile *)pJfd;
72730  memset(p, 0, sqlite3JournalSize(pVfs));
72731  if( nBuf>0 ){
72732    p->zBuf = sqlite3MallocZero(nBuf);
72733    if( !p->zBuf ){
72734      return SQLITE_NOMEM;
72735    }
72736  }else{
72737    return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
72738  }
72739  p->pMethod = &JournalFileMethods;
72740  p->nBuf = nBuf;
72741  p->flags = flags;
72742  p->zJournal = zName;
72743  p->pVfs = pVfs;
72744  return SQLITE_OK;
72745}
72746
72747/*
72748** If the argument p points to a JournalFile structure, and the underlying
72749** file has not yet been created, create it now.
72750*/
72751SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
72752  if( p->pMethods!=&JournalFileMethods ){
72753    return SQLITE_OK;
72754  }
72755  return createFile((JournalFile *)p);
72756}
72757
72758/*
72759** Return the number of bytes required to store a JournalFile that uses vfs
72760** pVfs to create the underlying on-disk files.
72761*/
72762SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
72763  return (pVfs->szOsFile+sizeof(JournalFile));
72764}
72765#endif
72766
72767/************** End of journal.c *********************************************/
72768/************** Begin file memjournal.c **************************************/
72769/*
72770** 2008 October 7
72771**
72772** The author disclaims copyright to this source code.  In place of
72773** a legal notice, here is a blessing:
72774**
72775**    May you do good and not evil.
72776**    May you find forgiveness for yourself and forgive others.
72777**    May you share freely, never taking more than you give.
72778**
72779*************************************************************************
72780**
72781** This file contains code use to implement an in-memory rollback journal.
72782** The in-memory rollback journal is used to journal transactions for
72783** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
72784*/
72785
72786/* Forward references to internal structures */
72787typedef struct MemJournal MemJournal;
72788typedef struct FilePoint FilePoint;
72789typedef struct FileChunk FileChunk;
72790
72791/* Space to hold the rollback journal is allocated in increments of
72792** this many bytes.
72793**
72794** The size chosen is a little less than a power of two.  That way,
72795** the FileChunk object will have a size that almost exactly fills
72796** a power-of-two allocation.  This mimimizes wasted space in power-of-two
72797** memory allocators.
72798*/
72799#define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
72800
72801/* Macro to find the minimum of two numeric values.
72802*/
72803#ifndef MIN
72804# define MIN(x,y) ((x)<(y)?(x):(y))
72805#endif
72806
72807/*
72808** The rollback journal is composed of a linked list of these structures.
72809*/
72810struct FileChunk {
72811  FileChunk *pNext;               /* Next chunk in the journal */
72812  u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
72813};
72814
72815/*
72816** An instance of this object serves as a cursor into the rollback journal.
72817** The cursor can be either for reading or writing.
72818*/
72819struct FilePoint {
72820  sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
72821  FileChunk *pChunk;              /* Specific chunk into which cursor points */
72822};
72823
72824/*
72825** This subclass is a subclass of sqlite3_file.  Each open memory-journal
72826** is an instance of this class.
72827*/
72828struct MemJournal {
72829  sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
72830  FileChunk *pFirst;              /* Head of in-memory chunk-list */
72831  FilePoint endpoint;             /* Pointer to the end of the file */
72832  FilePoint readpoint;            /* Pointer to the end of the last xRead() */
72833};
72834
72835/*
72836** Read data from the in-memory journal file.  This is the implementation
72837** of the sqlite3_vfs.xRead method.
72838*/
72839static int memjrnlRead(
72840  sqlite3_file *pJfd,    /* The journal file from which to read */
72841  void *zBuf,            /* Put the results here */
72842  int iAmt,              /* Number of bytes to read */
72843  sqlite_int64 iOfst     /* Begin reading at this offset */
72844){
72845  MemJournal *p = (MemJournal *)pJfd;
72846  u8 *zOut = zBuf;
72847  int nRead = iAmt;
72848  int iChunkOffset;
72849  FileChunk *pChunk;
72850
72851  /* SQLite never tries to read past the end of a rollback journal file */
72852  assert( iOfst+iAmt<=p->endpoint.iOffset );
72853
72854  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
72855    sqlite3_int64 iOff = 0;
72856    for(pChunk=p->pFirst;
72857        ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
72858        pChunk=pChunk->pNext
72859    ){
72860      iOff += JOURNAL_CHUNKSIZE;
72861    }
72862  }else{
72863    pChunk = p->readpoint.pChunk;
72864  }
72865
72866  iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
72867  do {
72868    int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
72869    int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
72870    memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
72871    zOut += nCopy;
72872    nRead -= iSpace;
72873    iChunkOffset = 0;
72874  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
72875  p->readpoint.iOffset = iOfst+iAmt;
72876  p->readpoint.pChunk = pChunk;
72877
72878  return SQLITE_OK;
72879}
72880
72881/*
72882** Write data to the file.
72883*/
72884static int memjrnlWrite(
72885  sqlite3_file *pJfd,    /* The journal file into which to write */
72886  const void *zBuf,      /* Take data to be written from here */
72887  int iAmt,              /* Number of bytes to write */
72888  sqlite_int64 iOfst     /* Begin writing at this offset into the file */
72889){
72890  MemJournal *p = (MemJournal *)pJfd;
72891  int nWrite = iAmt;
72892  u8 *zWrite = (u8 *)zBuf;
72893
72894  /* An in-memory journal file should only ever be appended to. Random
72895  ** access writes are not required by sqlite.
72896  */
72897  assert( iOfst==p->endpoint.iOffset );
72898  UNUSED_PARAMETER(iOfst);
72899
72900  while( nWrite>0 ){
72901    FileChunk *pChunk = p->endpoint.pChunk;
72902    int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
72903    int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
72904
72905    if( iChunkOffset==0 ){
72906      /* New chunk is required to extend the file. */
72907      FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
72908      if( !pNew ){
72909        return SQLITE_IOERR_NOMEM;
72910      }
72911      pNew->pNext = 0;
72912      if( pChunk ){
72913        assert( p->pFirst );
72914        pChunk->pNext = pNew;
72915      }else{
72916        assert( !p->pFirst );
72917        p->pFirst = pNew;
72918      }
72919      p->endpoint.pChunk = pNew;
72920    }
72921
72922    memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
72923    zWrite += iSpace;
72924    nWrite -= iSpace;
72925    p->endpoint.iOffset += iSpace;
72926  }
72927
72928  return SQLITE_OK;
72929}
72930
72931/*
72932** Truncate the file.
72933*/
72934static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
72935  MemJournal *p = (MemJournal *)pJfd;
72936  FileChunk *pChunk;
72937  assert(size==0);
72938  UNUSED_PARAMETER(size);
72939  pChunk = p->pFirst;
72940  while( pChunk ){
72941    FileChunk *pTmp = pChunk;
72942    pChunk = pChunk->pNext;
72943    sqlite3_free(pTmp);
72944  }
72945  sqlite3MemJournalOpen(pJfd);
72946  return SQLITE_OK;
72947}
72948
72949/*
72950** Close the file.
72951*/
72952static int memjrnlClose(sqlite3_file *pJfd){
72953  memjrnlTruncate(pJfd, 0);
72954  return SQLITE_OK;
72955}
72956
72957
72958/*
72959** Sync the file.
72960**
72961** Syncing an in-memory journal is a no-op.  And, in fact, this routine
72962** is never called in a working implementation.  This implementation
72963** exists purely as a contingency, in case some malfunction in some other
72964** part of SQLite causes Sync to be called by mistake.
72965*/
72966static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
72967  UNUSED_PARAMETER2(NotUsed, NotUsed2);
72968  return SQLITE_OK;
72969}
72970
72971/*
72972** Query the size of the file in bytes.
72973*/
72974static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
72975  MemJournal *p = (MemJournal *)pJfd;
72976  *pSize = (sqlite_int64) p->endpoint.iOffset;
72977  return SQLITE_OK;
72978}
72979
72980/*
72981** Table of methods for MemJournal sqlite3_file object.
72982*/
72983static const struct sqlite3_io_methods MemJournalMethods = {
72984  1,                /* iVersion */
72985  memjrnlClose,     /* xClose */
72986  memjrnlRead,      /* xRead */
72987  memjrnlWrite,     /* xWrite */
72988  memjrnlTruncate,  /* xTruncate */
72989  memjrnlSync,      /* xSync */
72990  memjrnlFileSize,  /* xFileSize */
72991  0,                /* xLock */
72992  0,                /* xUnlock */
72993  0,                /* xCheckReservedLock */
72994  0,                /* xFileControl */
72995  0,                /* xSectorSize */
72996  0,                /* xDeviceCharacteristics */
72997  0,                /* xShmMap */
72998  0,                /* xShmLock */
72999  0,                /* xShmBarrier */
73000  0                 /* xShmUnlock */
73001};
73002
73003/*
73004** Open a journal file.
73005*/
73006SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
73007  MemJournal *p = (MemJournal *)pJfd;
73008  assert( EIGHT_BYTE_ALIGNMENT(p) );
73009  memset(p, 0, sqlite3MemJournalSize());
73010  p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
73011}
73012
73013/*
73014** Return true if the file-handle passed as an argument is
73015** an in-memory journal
73016*/
73017SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
73018  return pJfd->pMethods==&MemJournalMethods;
73019}
73020
73021/*
73022** Return the number of bytes required to store a MemJournal file descriptor.
73023*/
73024SQLITE_PRIVATE int sqlite3MemJournalSize(void){
73025  return sizeof(MemJournal);
73026}
73027
73028/************** End of memjournal.c ******************************************/
73029/************** Begin file walker.c ******************************************/
73030/*
73031** 2008 August 16
73032**
73033** The author disclaims copyright to this source code.  In place of
73034** a legal notice, here is a blessing:
73035**
73036**    May you do good and not evil.
73037**    May you find forgiveness for yourself and forgive others.
73038**    May you share freely, never taking more than you give.
73039**
73040*************************************************************************
73041** This file contains routines used for walking the parser tree for
73042** an SQL statement.
73043*/
73044/* #include <stdlib.h> */
73045/* #include <string.h> */
73046
73047
73048/*
73049** Walk an expression tree.  Invoke the callback once for each node
73050** of the expression, while decending.  (In other words, the callback
73051** is invoked before visiting children.)
73052**
73053** The return value from the callback should be one of the WRC_*
73054** constants to specify how to proceed with the walk.
73055**
73056**    WRC_Continue      Continue descending down the tree.
73057**
73058**    WRC_Prune         Do not descend into child nodes.  But allow
73059**                      the walk to continue with sibling nodes.
73060**
73061**    WRC_Abort         Do no more callbacks.  Unwind the stack and
73062**                      return the top-level walk call.
73063**
73064** The return value from this routine is WRC_Abort to abandon the tree walk
73065** and WRC_Continue to continue.
73066*/
73067SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
73068  int rc;
73069  if( pExpr==0 ) return WRC_Continue;
73070  testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
73071  testcase( ExprHasProperty(pExpr, EP_Reduced) );
73072  rc = pWalker->xExprCallback(pWalker, pExpr);
73073  if( rc==WRC_Continue
73074              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
73075    if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
73076    if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
73077    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73078      if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
73079    }else{
73080      if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
73081    }
73082  }
73083  return rc & WRC_Abort;
73084}
73085
73086/*
73087** Call sqlite3WalkExpr() for every expression in list p or until
73088** an abort request is seen.
73089*/
73090SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
73091  int i;
73092  struct ExprList_item *pItem;
73093  if( p ){
73094    for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
73095      if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
73096    }
73097  }
73098  return WRC_Continue;
73099}
73100
73101/*
73102** Walk all expressions associated with SELECT statement p.  Do
73103** not invoke the SELECT callback on p, but do (of course) invoke
73104** any expr callbacks and SELECT callbacks that come from subqueries.
73105** Return WRC_Abort or WRC_Continue.
73106*/
73107SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
73108  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
73109  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
73110  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
73111  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
73112  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
73113  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
73114  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
73115  return WRC_Continue;
73116}
73117
73118/*
73119** Walk the parse trees associated with all subqueries in the
73120** FROM clause of SELECT statement p.  Do not invoke the select
73121** callback on p, but do invoke it on each FROM clause subquery
73122** and on any subqueries further down in the tree.  Return
73123** WRC_Abort or WRC_Continue;
73124*/
73125SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
73126  SrcList *pSrc;
73127  int i;
73128  struct SrcList_item *pItem;
73129
73130  pSrc = p->pSrc;
73131  if( ALWAYS(pSrc) ){
73132    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
73133      if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
73134        return WRC_Abort;
73135      }
73136    }
73137  }
73138  return WRC_Continue;
73139}
73140
73141/*
73142** Call sqlite3WalkExpr() for every expression in Select statement p.
73143** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
73144** on the compound select chain, p->pPrior.
73145**
73146** Return WRC_Continue under normal conditions.  Return WRC_Abort if
73147** there is an abort request.
73148**
73149** If the Walker does not have an xSelectCallback() then this routine
73150** is a no-op returning WRC_Continue.
73151*/
73152SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
73153  int rc;
73154  if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
73155  rc = WRC_Continue;
73156  while( p  ){
73157    rc = pWalker->xSelectCallback(pWalker, p);
73158    if( rc ) break;
73159    if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
73160    if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
73161    p = p->pPrior;
73162  }
73163  return rc & WRC_Abort;
73164}
73165
73166/************** End of walker.c **********************************************/
73167/************** Begin file resolve.c *****************************************/
73168/*
73169** 2008 August 18
73170**
73171** The author disclaims copyright to this source code.  In place of
73172** a legal notice, here is a blessing:
73173**
73174**    May you do good and not evil.
73175**    May you find forgiveness for yourself and forgive others.
73176**    May you share freely, never taking more than you give.
73177**
73178*************************************************************************
73179**
73180** This file contains routines used for walking the parser tree and
73181** resolve all identifiers by associating them with a particular
73182** table and column.
73183*/
73184/* #include <stdlib.h> */
73185/* #include <string.h> */
73186
73187/*
73188** Turn the pExpr expression into an alias for the iCol-th column of the
73189** result set in pEList.
73190**
73191** If the result set column is a simple column reference, then this routine
73192** makes an exact copy.  But for any other kind of expression, this
73193** routine make a copy of the result set column as the argument to the
73194** TK_AS operator.  The TK_AS operator causes the expression to be
73195** evaluated just once and then reused for each alias.
73196**
73197** The reason for suppressing the TK_AS term when the expression is a simple
73198** column reference is so that the column reference will be recognized as
73199** usable by indices within the WHERE clause processing logic.
73200**
73201** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
73202** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
73203**
73204**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
73205**
73206** Is equivalent to:
73207**
73208**     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
73209**
73210** The result of random()%5 in the GROUP BY clause is probably different
73211** from the result in the result-set.  We might fix this someday.  Or
73212** then again, we might not...
73213*/
73214static void resolveAlias(
73215  Parse *pParse,         /* Parsing context */
73216  ExprList *pEList,      /* A result set */
73217  int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
73218  Expr *pExpr,           /* Transform this into an alias to the result set */
73219  const char *zType      /* "GROUP" or "ORDER" or "" */
73220){
73221  Expr *pOrig;           /* The iCol-th column of the result set */
73222  Expr *pDup;            /* Copy of pOrig */
73223  sqlite3 *db;           /* The database connection */
73224
73225  assert( iCol>=0 && iCol<pEList->nExpr );
73226  pOrig = pEList->a[iCol].pExpr;
73227  assert( pOrig!=0 );
73228  assert( pOrig->flags & EP_Resolved );
73229  db = pParse->db;
73230  if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
73231    pDup = sqlite3ExprDup(db, pOrig, 0);
73232    pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
73233    if( pDup==0 ) return;
73234    if( pEList->a[iCol].iAlias==0 ){
73235      pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
73236    }
73237    pDup->iTable = pEList->a[iCol].iAlias;
73238  }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
73239    pDup = sqlite3ExprDup(db, pOrig, 0);
73240    if( pDup==0 ) return;
73241  }else{
73242    char *zToken = pOrig->u.zToken;
73243    assert( zToken!=0 );
73244    pOrig->u.zToken = 0;
73245    pDup = sqlite3ExprDup(db, pOrig, 0);
73246    pOrig->u.zToken = zToken;
73247    if( pDup==0 ) return;
73248    assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
73249    pDup->flags2 |= EP2_MallocedToken;
73250    pDup->u.zToken = sqlite3DbStrDup(db, zToken);
73251  }
73252  if( pExpr->flags & EP_ExpCollate ){
73253    pDup->pColl = pExpr->pColl;
73254    pDup->flags |= EP_ExpCollate;
73255  }
73256
73257  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
73258  ** prevents ExprDelete() from deleting the Expr structure itself,
73259  ** allowing it to be repopulated by the memcpy() on the following line.
73260  */
73261  ExprSetProperty(pExpr, EP_Static);
73262  sqlite3ExprDelete(db, pExpr);
73263  memcpy(pExpr, pDup, sizeof(*pExpr));
73264  sqlite3DbFree(db, pDup);
73265}
73266
73267
73268/*
73269** Return TRUE if the name zCol occurs anywhere in the USING clause.
73270**
73271** Return FALSE if the USING clause is NULL or if it does not contain
73272** zCol.
73273*/
73274static int nameInUsingClause(IdList *pUsing, const char *zCol){
73275  if( pUsing ){
73276    int k;
73277    for(k=0; k<pUsing->nId; k++){
73278      if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
73279    }
73280  }
73281  return 0;
73282}
73283
73284
73285/*
73286** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
73287** that name in the set of source tables in pSrcList and make the pExpr
73288** expression node refer back to that source column.  The following changes
73289** are made to pExpr:
73290**
73291**    pExpr->iDb           Set the index in db->aDb[] of the database X
73292**                         (even if X is implied).
73293**    pExpr->iTable        Set to the cursor number for the table obtained
73294**                         from pSrcList.
73295**    pExpr->pTab          Points to the Table structure of X.Y (even if
73296**                         X and/or Y are implied.)
73297**    pExpr->iColumn       Set to the column number within the table.
73298**    pExpr->op            Set to TK_COLUMN.
73299**    pExpr->pLeft         Any expression this points to is deleted
73300**    pExpr->pRight        Any expression this points to is deleted.
73301**
73302** The zDb variable is the name of the database (the "X").  This value may be
73303** NULL meaning that name is of the form Y.Z or Z.  Any available database
73304** can be used.  The zTable variable is the name of the table (the "Y").  This
73305** value can be NULL if zDb is also NULL.  If zTable is NULL it
73306** means that the form of the name is Z and that columns from any table
73307** can be used.
73308**
73309** If the name cannot be resolved unambiguously, leave an error message
73310** in pParse and return WRC_Abort.  Return WRC_Prune on success.
73311*/
73312static int lookupName(
73313  Parse *pParse,       /* The parsing context */
73314  const char *zDb,     /* Name of the database containing table, or NULL */
73315  const char *zTab,    /* Name of table containing column, or NULL */
73316  const char *zCol,    /* Name of the column. */
73317  NameContext *pNC,    /* The name context used to resolve the name */
73318  Expr *pExpr          /* Make this EXPR node point to the selected column */
73319){
73320  int i, j;            /* Loop counters */
73321  int cnt = 0;                      /* Number of matching column names */
73322  int cntTab = 0;                   /* Number of matching table names */
73323  sqlite3 *db = pParse->db;         /* The database connection */
73324  struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
73325  struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
73326  NameContext *pTopNC = pNC;        /* First namecontext in the list */
73327  Schema *pSchema = 0;              /* Schema of the expression */
73328  int isTrigger = 0;
73329
73330  assert( pNC );     /* the name context cannot be NULL. */
73331  assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
73332  assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
73333
73334  /* Initialize the node to no-match */
73335  pExpr->iTable = -1;
73336  pExpr->pTab = 0;
73337  ExprSetIrreducible(pExpr);
73338
73339  /* Start at the inner-most context and move outward until a match is found */
73340  while( pNC && cnt==0 ){
73341    ExprList *pEList;
73342    SrcList *pSrcList = pNC->pSrcList;
73343
73344    if( pSrcList ){
73345      for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
73346        Table *pTab;
73347        int iDb;
73348        Column *pCol;
73349
73350        pTab = pItem->pTab;
73351        assert( pTab!=0 && pTab->zName!=0 );
73352        iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
73353        assert( pTab->nCol>0 );
73354        if( zTab ){
73355          if( pItem->zAlias ){
73356            char *zTabName = pItem->zAlias;
73357            if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
73358          }else{
73359            char *zTabName = pTab->zName;
73360            if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
73361              continue;
73362            }
73363            if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
73364              continue;
73365            }
73366          }
73367        }
73368        if( 0==(cntTab++) ){
73369          pExpr->iTable = pItem->iCursor;
73370          pExpr->pTab = pTab;
73371          pSchema = pTab->pSchema;
73372          pMatch = pItem;
73373        }
73374        for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
73375          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
73376            /* If there has been exactly one prior match and this match
73377            ** is for the right-hand table of a NATURAL JOIN or is in a
73378            ** USING clause, then skip this match.
73379            */
73380            if( cnt==1 ){
73381              if( pItem->jointype & JT_NATURAL ) continue;
73382              if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
73383            }
73384            cnt++;
73385            pExpr->iTable = pItem->iCursor;
73386            pExpr->pTab = pTab;
73387            pMatch = pItem;
73388            pSchema = pTab->pSchema;
73389            /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
73390            pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
73391            break;
73392          }
73393        }
73394      }
73395    }
73396
73397#ifndef SQLITE_OMIT_TRIGGER
73398    /* If we have not already resolved the name, then maybe
73399    ** it is a new.* or old.* trigger argument reference
73400    */
73401    if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
73402      int op = pParse->eTriggerOp;
73403      Table *pTab = 0;
73404      assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
73405      if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
73406        pExpr->iTable = 1;
73407        pTab = pParse->pTriggerTab;
73408      }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
73409        pExpr->iTable = 0;
73410        pTab = pParse->pTriggerTab;
73411      }
73412
73413      if( pTab ){
73414        int iCol;
73415        pSchema = pTab->pSchema;
73416        cntTab++;
73417        for(iCol=0; iCol<pTab->nCol; iCol++){
73418          Column *pCol = &pTab->aCol[iCol];
73419          if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
73420            if( iCol==pTab->iPKey ){
73421              iCol = -1;
73422            }
73423            break;
73424          }
73425        }
73426        if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
73427          iCol = -1;        /* IMP: R-44911-55124 */
73428        }
73429        if( iCol<pTab->nCol ){
73430          cnt++;
73431          if( iCol<0 ){
73432            pExpr->affinity = SQLITE_AFF_INTEGER;
73433          }else if( pExpr->iTable==0 ){
73434            testcase( iCol==31 );
73435            testcase( iCol==32 );
73436            pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73437          }else{
73438            testcase( iCol==31 );
73439            testcase( iCol==32 );
73440            pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
73441          }
73442          pExpr->iColumn = (i16)iCol;
73443          pExpr->pTab = pTab;
73444          isTrigger = 1;
73445        }
73446      }
73447    }
73448#endif /* !defined(SQLITE_OMIT_TRIGGER) */
73449
73450    /*
73451    ** Perhaps the name is a reference to the ROWID
73452    */
73453    if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
73454      cnt = 1;
73455      pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
73456      pExpr->affinity = SQLITE_AFF_INTEGER;
73457    }
73458
73459    /*
73460    ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
73461    ** might refer to an result-set alias.  This happens, for example, when
73462    ** we are resolving names in the WHERE clause of the following command:
73463    **
73464    **     SELECT a+b AS x FROM table WHERE x<10;
73465    **
73466    ** In cases like this, replace pExpr with a copy of the expression that
73467    ** forms the result set entry ("a+b" in the example) and return immediately.
73468    ** Note that the expression in the result set should have already been
73469    ** resolved by the time the WHERE clause is resolved.
73470    */
73471    if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
73472      for(j=0; j<pEList->nExpr; j++){
73473        char *zAs = pEList->a[j].zName;
73474        if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
73475          Expr *pOrig;
73476          assert( pExpr->pLeft==0 && pExpr->pRight==0 );
73477          assert( pExpr->x.pList==0 );
73478          assert( pExpr->x.pSelect==0 );
73479          pOrig = pEList->a[j].pExpr;
73480          if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
73481            sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
73482            return WRC_Abort;
73483          }
73484          resolveAlias(pParse, pEList, j, pExpr, "");
73485          cnt = 1;
73486          pMatch = 0;
73487          assert( zTab==0 && zDb==0 );
73488          goto lookupname_end;
73489        }
73490      }
73491    }
73492
73493    /* Advance to the next name context.  The loop will exit when either
73494    ** we have a match (cnt>0) or when we run out of name contexts.
73495    */
73496    if( cnt==0 ){
73497      pNC = pNC->pNext;
73498    }
73499  }
73500
73501  /*
73502  ** If X and Y are NULL (in other words if only the column name Z is
73503  ** supplied) and the value of Z is enclosed in double-quotes, then
73504  ** Z is a string literal if it doesn't match any column names.  In that
73505  ** case, we need to return right away and not make any changes to
73506  ** pExpr.
73507  **
73508  ** Because no reference was made to outer contexts, the pNC->nRef
73509  ** fields are not changed in any context.
73510  */
73511  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
73512    pExpr->op = TK_STRING;
73513    pExpr->pTab = 0;
73514    return WRC_Prune;
73515  }
73516
73517  /*
73518  ** cnt==0 means there was not match.  cnt>1 means there were two or
73519  ** more matches.  Either way, we have an error.
73520  */
73521  if( cnt!=1 ){
73522    const char *zErr;
73523    zErr = cnt==0 ? "no such column" : "ambiguous column name";
73524    if( zDb ){
73525      sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
73526    }else if( zTab ){
73527      sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
73528    }else{
73529      sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
73530    }
73531    pParse->checkSchema = 1;
73532    pTopNC->nErr++;
73533  }
73534
73535  /* If a column from a table in pSrcList is referenced, then record
73536  ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
73537  ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
73538  ** column number is greater than the number of bits in the bitmask
73539  ** then set the high-order bit of the bitmask.
73540  */
73541  if( pExpr->iColumn>=0 && pMatch!=0 ){
73542    int n = pExpr->iColumn;
73543    testcase( n==BMS-1 );
73544    if( n>=BMS ){
73545      n = BMS-1;
73546    }
73547    assert( pMatch->iCursor==pExpr->iTable );
73548    pMatch->colUsed |= ((Bitmask)1)<<n;
73549  }
73550
73551  /* Clean up and return
73552  */
73553  sqlite3ExprDelete(db, pExpr->pLeft);
73554  pExpr->pLeft = 0;
73555  sqlite3ExprDelete(db, pExpr->pRight);
73556  pExpr->pRight = 0;
73557  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
73558lookupname_end:
73559  if( cnt==1 ){
73560    assert( pNC!=0 );
73561    sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
73562    /* Increment the nRef value on all name contexts from TopNC up to
73563    ** the point where the name matched. */
73564    for(;;){
73565      assert( pTopNC!=0 );
73566      pTopNC->nRef++;
73567      if( pTopNC==pNC ) break;
73568      pTopNC = pTopNC->pNext;
73569    }
73570    return WRC_Prune;
73571  } else {
73572    return WRC_Abort;
73573  }
73574}
73575
73576/*
73577** Allocate and return a pointer to an expression to load the column iCol
73578** from datasource iSrc in SrcList pSrc.
73579*/
73580SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
73581  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
73582  if( p ){
73583    struct SrcList_item *pItem = &pSrc->a[iSrc];
73584    p->pTab = pItem->pTab;
73585    p->iTable = pItem->iCursor;
73586    if( p->pTab->iPKey==iCol ){
73587      p->iColumn = -1;
73588    }else{
73589      p->iColumn = (ynVar)iCol;
73590      testcase( iCol==BMS );
73591      testcase( iCol==BMS-1 );
73592      pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
73593    }
73594    ExprSetProperty(p, EP_Resolved);
73595  }
73596  return p;
73597}
73598
73599/*
73600** This routine is callback for sqlite3WalkExpr().
73601**
73602** Resolve symbolic names into TK_COLUMN operators for the current
73603** node in the expression tree.  Return 0 to continue the search down
73604** the tree or 2 to abort the tree walk.
73605**
73606** This routine also does error checking and name resolution for
73607** function names.  The operator for aggregate functions is changed
73608** to TK_AGG_FUNCTION.
73609*/
73610static int resolveExprStep(Walker *pWalker, Expr *pExpr){
73611  NameContext *pNC;
73612  Parse *pParse;
73613
73614  pNC = pWalker->u.pNC;
73615  assert( pNC!=0 );
73616  pParse = pNC->pParse;
73617  assert( pParse==pWalker->pParse );
73618
73619  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
73620  ExprSetProperty(pExpr, EP_Resolved);
73621#ifndef NDEBUG
73622  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
73623    SrcList *pSrcList = pNC->pSrcList;
73624    int i;
73625    for(i=0; i<pNC->pSrcList->nSrc; i++){
73626      assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
73627    }
73628  }
73629#endif
73630  switch( pExpr->op ){
73631
73632#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
73633    /* The special operator TK_ROW means use the rowid for the first
73634    ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
73635    ** clause processing on UPDATE and DELETE statements.
73636    */
73637    case TK_ROW: {
73638      SrcList *pSrcList = pNC->pSrcList;
73639      struct SrcList_item *pItem;
73640      assert( pSrcList && pSrcList->nSrc==1 );
73641      pItem = pSrcList->a;
73642      pExpr->op = TK_COLUMN;
73643      pExpr->pTab = pItem->pTab;
73644      pExpr->iTable = pItem->iCursor;
73645      pExpr->iColumn = -1;
73646      pExpr->affinity = SQLITE_AFF_INTEGER;
73647      break;
73648    }
73649#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
73650
73651    /* A lone identifier is the name of a column.
73652    */
73653    case TK_ID: {
73654      return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
73655    }
73656
73657    /* A table name and column name:     ID.ID
73658    ** Or a database, table and column:  ID.ID.ID
73659    */
73660    case TK_DOT: {
73661      const char *zColumn;
73662      const char *zTable;
73663      const char *zDb;
73664      Expr *pRight;
73665
73666      /* if( pSrcList==0 ) break; */
73667      pRight = pExpr->pRight;
73668      if( pRight->op==TK_ID ){
73669        zDb = 0;
73670        zTable = pExpr->pLeft->u.zToken;
73671        zColumn = pRight->u.zToken;
73672      }else{
73673        assert( pRight->op==TK_DOT );
73674        zDb = pExpr->pLeft->u.zToken;
73675        zTable = pRight->pLeft->u.zToken;
73676        zColumn = pRight->pRight->u.zToken;
73677      }
73678      return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
73679    }
73680
73681    /* Resolve function names
73682    */
73683    case TK_CONST_FUNC:
73684    case TK_FUNCTION: {
73685      ExprList *pList = pExpr->x.pList;    /* The argument list */
73686      int n = pList ? pList->nExpr : 0;    /* Number of arguments */
73687      int no_such_func = 0;       /* True if no such function exists */
73688      int wrong_num_args = 0;     /* True if wrong number of arguments */
73689      int is_agg = 0;             /* True if is an aggregate function */
73690      int auth;                   /* Authorization to use the function */
73691      int nId;                    /* Number of characters in function name */
73692      const char *zId;            /* The function name. */
73693      FuncDef *pDef;              /* Information about the function */
73694      u8 enc = ENC(pParse->db);   /* The database encoding */
73695
73696      testcase( pExpr->op==TK_CONST_FUNC );
73697      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73698      zId = pExpr->u.zToken;
73699      nId = sqlite3Strlen30(zId);
73700      pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
73701      if( pDef==0 ){
73702        pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
73703        if( pDef==0 ){
73704          no_such_func = 1;
73705        }else{
73706          wrong_num_args = 1;
73707        }
73708      }else{
73709        is_agg = pDef->xFunc==0;
73710      }
73711#ifndef SQLITE_OMIT_AUTHORIZATION
73712      if( pDef ){
73713        auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
73714        if( auth!=SQLITE_OK ){
73715          if( auth==SQLITE_DENY ){
73716            sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
73717                                    pDef->zName);
73718            pNC->nErr++;
73719          }
73720          pExpr->op = TK_NULL;
73721          return WRC_Prune;
73722        }
73723      }
73724#endif
73725      if( is_agg && !pNC->allowAgg ){
73726        sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
73727        pNC->nErr++;
73728        is_agg = 0;
73729      }else if( no_such_func ){
73730        sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
73731        pNC->nErr++;
73732      }else if( wrong_num_args ){
73733        sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
73734             nId, zId);
73735        pNC->nErr++;
73736      }
73737      if( is_agg ){
73738        pExpr->op = TK_AGG_FUNCTION;
73739        pNC->hasAgg = 1;
73740      }
73741      if( is_agg ) pNC->allowAgg = 0;
73742      sqlite3WalkExprList(pWalker, pList);
73743      if( is_agg ) pNC->allowAgg = 1;
73744      /* FIX ME:  Compute pExpr->affinity based on the expected return
73745      ** type of the function
73746      */
73747      return WRC_Prune;
73748    }
73749#ifndef SQLITE_OMIT_SUBQUERY
73750    case TK_SELECT:
73751    case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
73752#endif
73753    case TK_IN: {
73754      testcase( pExpr->op==TK_IN );
73755      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73756        int nRef = pNC->nRef;
73757#ifndef SQLITE_OMIT_CHECK
73758        if( pNC->isCheck ){
73759          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
73760        }
73761#endif
73762        sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
73763        assert( pNC->nRef>=nRef );
73764        if( nRef!=pNC->nRef ){
73765          ExprSetProperty(pExpr, EP_VarSelect);
73766        }
73767      }
73768      break;
73769    }
73770#ifndef SQLITE_OMIT_CHECK
73771    case TK_VARIABLE: {
73772      if( pNC->isCheck ){
73773        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
73774      }
73775      break;
73776    }
73777#endif
73778  }
73779  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
73780}
73781
73782/*
73783** pEList is a list of expressions which are really the result set of the
73784** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
73785** This routine checks to see if pE is a simple identifier which corresponds
73786** to the AS-name of one of the terms of the expression list.  If it is,
73787** this routine return an integer between 1 and N where N is the number of
73788** elements in pEList, corresponding to the matching entry.  If there is
73789** no match, or if pE is not a simple identifier, then this routine
73790** return 0.
73791**
73792** pEList has been resolved.  pE has not.
73793*/
73794static int resolveAsName(
73795  Parse *pParse,     /* Parsing context for error messages */
73796  ExprList *pEList,  /* List of expressions to scan */
73797  Expr *pE           /* Expression we are trying to match */
73798){
73799  int i;             /* Loop counter */
73800
73801  UNUSED_PARAMETER(pParse);
73802
73803  if( pE->op==TK_ID ){
73804    char *zCol = pE->u.zToken;
73805    for(i=0; i<pEList->nExpr; i++){
73806      char *zAs = pEList->a[i].zName;
73807      if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
73808        return i+1;
73809      }
73810    }
73811  }
73812  return 0;
73813}
73814
73815/*
73816** pE is a pointer to an expression which is a single term in the
73817** ORDER BY of a compound SELECT.  The expression has not been
73818** name resolved.
73819**
73820** At the point this routine is called, we already know that the
73821** ORDER BY term is not an integer index into the result set.  That
73822** case is handled by the calling routine.
73823**
73824** Attempt to match pE against result set columns in the left-most
73825** SELECT statement.  Return the index i of the matching column,
73826** as an indication to the caller that it should sort by the i-th column.
73827** The left-most column is 1.  In other words, the value returned is the
73828** same integer value that would be used in the SQL statement to indicate
73829** the column.
73830**
73831** If there is no match, return 0.  Return -1 if an error occurs.
73832*/
73833static int resolveOrderByTermToExprList(
73834  Parse *pParse,     /* Parsing context for error messages */
73835  Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
73836  Expr *pE           /* The specific ORDER BY term */
73837){
73838  int i;             /* Loop counter */
73839  ExprList *pEList;  /* The columns of the result set */
73840  NameContext nc;    /* Name context for resolving pE */
73841  sqlite3 *db;       /* Database connection */
73842  int rc;            /* Return code from subprocedures */
73843  u8 savedSuppErr;   /* Saved value of db->suppressErr */
73844
73845  assert( sqlite3ExprIsInteger(pE, &i)==0 );
73846  pEList = pSelect->pEList;
73847
73848  /* Resolve all names in the ORDER BY term expression
73849  */
73850  memset(&nc, 0, sizeof(nc));
73851  nc.pParse = pParse;
73852  nc.pSrcList = pSelect->pSrc;
73853  nc.pEList = pEList;
73854  nc.allowAgg = 1;
73855  nc.nErr = 0;
73856  db = pParse->db;
73857  savedSuppErr = db->suppressErr;
73858  db->suppressErr = 1;
73859  rc = sqlite3ResolveExprNames(&nc, pE);
73860  db->suppressErr = savedSuppErr;
73861  if( rc ) return 0;
73862
73863  /* Try to match the ORDER BY expression against an expression
73864  ** in the result set.  Return an 1-based index of the matching
73865  ** result-set entry.
73866  */
73867  for(i=0; i<pEList->nExpr; i++){
73868    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
73869      return i+1;
73870    }
73871  }
73872
73873  /* If no match, return 0. */
73874  return 0;
73875}
73876
73877/*
73878** Generate an ORDER BY or GROUP BY term out-of-range error.
73879*/
73880static void resolveOutOfRangeError(
73881  Parse *pParse,         /* The error context into which to write the error */
73882  const char *zType,     /* "ORDER" or "GROUP" */
73883  int i,                 /* The index (1-based) of the term out of range */
73884  int mx                 /* Largest permissible value of i */
73885){
73886  sqlite3ErrorMsg(pParse,
73887    "%r %s BY term out of range - should be "
73888    "between 1 and %d", i, zType, mx);
73889}
73890
73891/*
73892** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
73893** each term of the ORDER BY clause is a constant integer between 1
73894** and N where N is the number of columns in the compound SELECT.
73895**
73896** ORDER BY terms that are already an integer between 1 and N are
73897** unmodified.  ORDER BY terms that are integers outside the range of
73898** 1 through N generate an error.  ORDER BY terms that are expressions
73899** are matched against result set expressions of compound SELECT
73900** beginning with the left-most SELECT and working toward the right.
73901** At the first match, the ORDER BY expression is transformed into
73902** the integer column number.
73903**
73904** Return the number of errors seen.
73905*/
73906static int resolveCompoundOrderBy(
73907  Parse *pParse,        /* Parsing context.  Leave error messages here */
73908  Select *pSelect       /* The SELECT statement containing the ORDER BY */
73909){
73910  int i;
73911  ExprList *pOrderBy;
73912  ExprList *pEList;
73913  sqlite3 *db;
73914  int moreToDo = 1;
73915
73916  pOrderBy = pSelect->pOrderBy;
73917  if( pOrderBy==0 ) return 0;
73918  db = pParse->db;
73919#if SQLITE_MAX_COLUMN
73920  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
73921    sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
73922    return 1;
73923  }
73924#endif
73925  for(i=0; i<pOrderBy->nExpr; i++){
73926    pOrderBy->a[i].done = 0;
73927  }
73928  pSelect->pNext = 0;
73929  while( pSelect->pPrior ){
73930    pSelect->pPrior->pNext = pSelect;
73931    pSelect = pSelect->pPrior;
73932  }
73933  while( pSelect && moreToDo ){
73934    struct ExprList_item *pItem;
73935    moreToDo = 0;
73936    pEList = pSelect->pEList;
73937    assert( pEList!=0 );
73938    for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
73939      int iCol = -1;
73940      Expr *pE, *pDup;
73941      if( pItem->done ) continue;
73942      pE = pItem->pExpr;
73943      if( sqlite3ExprIsInteger(pE, &iCol) ){
73944        if( iCol<=0 || iCol>pEList->nExpr ){
73945          resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
73946          return 1;
73947        }
73948      }else{
73949        iCol = resolveAsName(pParse, pEList, pE);
73950        if( iCol==0 ){
73951          pDup = sqlite3ExprDup(db, pE, 0);
73952          if( !db->mallocFailed ){
73953            assert(pDup);
73954            iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
73955          }
73956          sqlite3ExprDelete(db, pDup);
73957        }
73958      }
73959      if( iCol>0 ){
73960        CollSeq *pColl = pE->pColl;
73961        int flags = pE->flags & EP_ExpCollate;
73962        sqlite3ExprDelete(db, pE);
73963        pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
73964        if( pE==0 ) return 1;
73965        pE->pColl = pColl;
73966        pE->flags |= EP_IntValue | flags;
73967        pE->u.iValue = iCol;
73968        pItem->iOrderByCol = (u16)iCol;
73969        pItem->done = 1;
73970      }else{
73971        moreToDo = 1;
73972      }
73973    }
73974    pSelect = pSelect->pNext;
73975  }
73976  for(i=0; i<pOrderBy->nExpr; i++){
73977    if( pOrderBy->a[i].done==0 ){
73978      sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
73979            "column in the result set", i+1);
73980      return 1;
73981    }
73982  }
73983  return 0;
73984}
73985
73986/*
73987** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
73988** the SELECT statement pSelect.  If any term is reference to a
73989** result set expression (as determined by the ExprList.a.iCol field)
73990** then convert that term into a copy of the corresponding result set
73991** column.
73992**
73993** If any errors are detected, add an error message to pParse and
73994** return non-zero.  Return zero if no errors are seen.
73995*/
73996SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
73997  Parse *pParse,        /* Parsing context.  Leave error messages here */
73998  Select *pSelect,      /* The SELECT statement containing the clause */
73999  ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
74000  const char *zType     /* "ORDER" or "GROUP" */
74001){
74002  int i;
74003  sqlite3 *db = pParse->db;
74004  ExprList *pEList;
74005  struct ExprList_item *pItem;
74006
74007  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
74008#if SQLITE_MAX_COLUMN
74009  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74010    sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
74011    return 1;
74012  }
74013#endif
74014  pEList = pSelect->pEList;
74015  assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
74016  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74017    if( pItem->iOrderByCol ){
74018      if( pItem->iOrderByCol>pEList->nExpr ){
74019        resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
74020        return 1;
74021      }
74022      resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType);
74023    }
74024  }
74025  return 0;
74026}
74027
74028/*
74029** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
74030** The Name context of the SELECT statement is pNC.  zType is either
74031** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
74032**
74033** This routine resolves each term of the clause into an expression.
74034** If the order-by term is an integer I between 1 and N (where N is the
74035** number of columns in the result set of the SELECT) then the expression
74036** in the resolution is a copy of the I-th result-set expression.  If
74037** the order-by term is an identify that corresponds to the AS-name of
74038** a result-set expression, then the term resolves to a copy of the
74039** result-set expression.  Otherwise, the expression is resolved in
74040** the usual way - using sqlite3ResolveExprNames().
74041**
74042** This routine returns the number of errors.  If errors occur, then
74043** an appropriate error message might be left in pParse.  (OOM errors
74044** excepted.)
74045*/
74046static int resolveOrderGroupBy(
74047  NameContext *pNC,     /* The name context of the SELECT statement */
74048  Select *pSelect,      /* The SELECT statement holding pOrderBy */
74049  ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
74050  const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
74051){
74052  int i;                         /* Loop counter */
74053  int iCol;                      /* Column number */
74054  struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
74055  Parse *pParse;                 /* Parsing context */
74056  int nResult;                   /* Number of terms in the result set */
74057
74058  if( pOrderBy==0 ) return 0;
74059  nResult = pSelect->pEList->nExpr;
74060  pParse = pNC->pParse;
74061  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74062    Expr *pE = pItem->pExpr;
74063    iCol = resolveAsName(pParse, pSelect->pEList, pE);
74064    if( iCol>0 ){
74065      /* If an AS-name match is found, mark this ORDER BY column as being
74066      ** a copy of the iCol-th result-set column.  The subsequent call to
74067      ** sqlite3ResolveOrderGroupBy() will convert the expression to a
74068      ** copy of the iCol-th result-set expression. */
74069      pItem->iOrderByCol = (u16)iCol;
74070      continue;
74071    }
74072    if( sqlite3ExprIsInteger(pE, &iCol) ){
74073      /* The ORDER BY term is an integer constant.  Again, set the column
74074      ** number so that sqlite3ResolveOrderGroupBy() will convert the
74075      ** order-by term to a copy of the result-set expression */
74076      if( iCol<1 ){
74077        resolveOutOfRangeError(pParse, zType, i+1, nResult);
74078        return 1;
74079      }
74080      pItem->iOrderByCol = (u16)iCol;
74081      continue;
74082    }
74083
74084    /* Otherwise, treat the ORDER BY term as an ordinary expression */
74085    pItem->iOrderByCol = 0;
74086    if( sqlite3ResolveExprNames(pNC, pE) ){
74087      return 1;
74088    }
74089  }
74090  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
74091}
74092
74093/*
74094** Resolve names in the SELECT statement p and all of its descendents.
74095*/
74096static int resolveSelectStep(Walker *pWalker, Select *p){
74097  NameContext *pOuterNC;  /* Context that contains this SELECT */
74098  NameContext sNC;        /* Name context of this SELECT */
74099  int isCompound;         /* True if p is a compound select */
74100  int nCompound;          /* Number of compound terms processed so far */
74101  Parse *pParse;          /* Parsing context */
74102  ExprList *pEList;       /* Result set expression list */
74103  int i;                  /* Loop counter */
74104  ExprList *pGroupBy;     /* The GROUP BY clause */
74105  Select *pLeftmost;      /* Left-most of SELECT of a compound */
74106  sqlite3 *db;            /* Database connection */
74107
74108
74109  assert( p!=0 );
74110  if( p->selFlags & SF_Resolved ){
74111    return WRC_Prune;
74112  }
74113  pOuterNC = pWalker->u.pNC;
74114  pParse = pWalker->pParse;
74115  db = pParse->db;
74116
74117  /* Normally sqlite3SelectExpand() will be called first and will have
74118  ** already expanded this SELECT.  However, if this is a subquery within
74119  ** an expression, sqlite3ResolveExprNames() will be called without a
74120  ** prior call to sqlite3SelectExpand().  When that happens, let
74121  ** sqlite3SelectPrep() do all of the processing for this SELECT.
74122  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
74123  ** this routine in the correct order.
74124  */
74125  if( (p->selFlags & SF_Expanded)==0 ){
74126    sqlite3SelectPrep(pParse, p, pOuterNC);
74127    return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
74128  }
74129
74130  isCompound = p->pPrior!=0;
74131  nCompound = 0;
74132  pLeftmost = p;
74133  while( p ){
74134    assert( (p->selFlags & SF_Expanded)!=0 );
74135    assert( (p->selFlags & SF_Resolved)==0 );
74136    p->selFlags |= SF_Resolved;
74137
74138    /* Resolve the expressions in the LIMIT and OFFSET clauses. These
74139    ** are not allowed to refer to any names, so pass an empty NameContext.
74140    */
74141    memset(&sNC, 0, sizeof(sNC));
74142    sNC.pParse = pParse;
74143    if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
74144        sqlite3ResolveExprNames(&sNC, p->pOffset) ){
74145      return WRC_Abort;
74146    }
74147
74148    /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
74149    ** resolve the result-set expression list.
74150    */
74151    sNC.allowAgg = 1;
74152    sNC.pSrcList = p->pSrc;
74153    sNC.pNext = pOuterNC;
74154
74155    /* Resolve names in the result set. */
74156    pEList = p->pEList;
74157    assert( pEList!=0 );
74158    for(i=0; i<pEList->nExpr; i++){
74159      Expr *pX = pEList->a[i].pExpr;
74160      if( sqlite3ResolveExprNames(&sNC, pX) ){
74161        return WRC_Abort;
74162      }
74163    }
74164
74165    /* Recursively resolve names in all subqueries
74166    */
74167    for(i=0; i<p->pSrc->nSrc; i++){
74168      struct SrcList_item *pItem = &p->pSrc->a[i];
74169      if( pItem->pSelect ){
74170        NameContext *pNC;         /* Used to iterate name contexts */
74171        int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
74172        const char *zSavedContext = pParse->zAuthContext;
74173
74174        /* Count the total number of references to pOuterNC and all of its
74175        ** parent contexts. After resolving references to expressions in
74176        ** pItem->pSelect, check if this value has changed. If so, then
74177        ** SELECT statement pItem->pSelect must be correlated. Set the
74178        ** pItem->isCorrelated flag if this is the case. */
74179        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
74180
74181        if( pItem->zName ) pParse->zAuthContext = pItem->zName;
74182        sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
74183        pParse->zAuthContext = zSavedContext;
74184        if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
74185
74186        for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
74187        assert( pItem->isCorrelated==0 && nRef<=0 );
74188        pItem->isCorrelated = (nRef!=0);
74189      }
74190    }
74191
74192    /* If there are no aggregate functions in the result-set, and no GROUP BY
74193    ** expression, do not allow aggregates in any of the other expressions.
74194    */
74195    assert( (p->selFlags & SF_Aggregate)==0 );
74196    pGroupBy = p->pGroupBy;
74197    if( pGroupBy || sNC.hasAgg ){
74198      p->selFlags |= SF_Aggregate;
74199    }else{
74200      sNC.allowAgg = 0;
74201    }
74202
74203    /* If a HAVING clause is present, then there must be a GROUP BY clause.
74204    */
74205    if( p->pHaving && !pGroupBy ){
74206      sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
74207      return WRC_Abort;
74208    }
74209
74210    /* Add the expression list to the name-context before parsing the
74211    ** other expressions in the SELECT statement. This is so that
74212    ** expressions in the WHERE clause (etc.) can refer to expressions by
74213    ** aliases in the result set.
74214    **
74215    ** Minor point: If this is the case, then the expression will be
74216    ** re-evaluated for each reference to it.
74217    */
74218    sNC.pEList = p->pEList;
74219    if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
74220       sqlite3ResolveExprNames(&sNC, p->pHaving)
74221    ){
74222      return WRC_Abort;
74223    }
74224
74225    /* The ORDER BY and GROUP BY clauses may not refer to terms in
74226    ** outer queries
74227    */
74228    sNC.pNext = 0;
74229    sNC.allowAgg = 1;
74230
74231    /* Process the ORDER BY clause for singleton SELECT statements.
74232    ** The ORDER BY clause for compounds SELECT statements is handled
74233    ** below, after all of the result-sets for all of the elements of
74234    ** the compound have been resolved.
74235    */
74236    if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
74237      return WRC_Abort;
74238    }
74239    if( db->mallocFailed ){
74240      return WRC_Abort;
74241    }
74242
74243    /* Resolve the GROUP BY clause.  At the same time, make sure
74244    ** the GROUP BY clause does not contain aggregate functions.
74245    */
74246    if( pGroupBy ){
74247      struct ExprList_item *pItem;
74248
74249      if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
74250        return WRC_Abort;
74251      }
74252      for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
74253        if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
74254          sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
74255              "the GROUP BY clause");
74256          return WRC_Abort;
74257        }
74258      }
74259    }
74260
74261    /* Advance to the next term of the compound
74262    */
74263    p = p->pPrior;
74264    nCompound++;
74265  }
74266
74267  /* Resolve the ORDER BY on a compound SELECT after all terms of
74268  ** the compound have been resolved.
74269  */
74270  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
74271    return WRC_Abort;
74272  }
74273
74274  return WRC_Prune;
74275}
74276
74277/*
74278** This routine walks an expression tree and resolves references to
74279** table columns and result-set columns.  At the same time, do error
74280** checking on function usage and set a flag if any aggregate functions
74281** are seen.
74282**
74283** To resolve table columns references we look for nodes (or subtrees) of the
74284** form X.Y.Z or Y.Z or just Z where
74285**
74286**      X:   The name of a database.  Ex:  "main" or "temp" or
74287**           the symbolic name assigned to an ATTACH-ed database.
74288**
74289**      Y:   The name of a table in a FROM clause.  Or in a trigger
74290**           one of the special names "old" or "new".
74291**
74292**      Z:   The name of a column in table Y.
74293**
74294** The node at the root of the subtree is modified as follows:
74295**
74296**    Expr.op        Changed to TK_COLUMN
74297**    Expr.pTab      Points to the Table object for X.Y
74298**    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
74299**    Expr.iTable    The VDBE cursor number for X.Y
74300**
74301**
74302** To resolve result-set references, look for expression nodes of the
74303** form Z (with no X and Y prefix) where the Z matches the right-hand
74304** size of an AS clause in the result-set of a SELECT.  The Z expression
74305** is replaced by a copy of the left-hand side of the result-set expression.
74306** Table-name and function resolution occurs on the substituted expression
74307** tree.  For example, in:
74308**
74309**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
74310**
74311** The "x" term of the order by is replaced by "a+b" to render:
74312**
74313**      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
74314**
74315** Function calls are checked to make sure that the function is
74316** defined and that the correct number of arguments are specified.
74317** If the function is an aggregate function, then the pNC->hasAgg is
74318** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
74319** If an expression contains aggregate functions then the EP_Agg
74320** property on the expression is set.
74321**
74322** An error message is left in pParse if anything is amiss.  The number
74323** if errors is returned.
74324*/
74325SQLITE_PRIVATE int sqlite3ResolveExprNames(
74326  NameContext *pNC,       /* Namespace to resolve expressions in. */
74327  Expr *pExpr             /* The expression to be analyzed. */
74328){
74329  int savedHasAgg;
74330  Walker w;
74331
74332  if( pExpr==0 ) return 0;
74333#if SQLITE_MAX_EXPR_DEPTH>0
74334  {
74335    Parse *pParse = pNC->pParse;
74336    if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
74337      return 1;
74338    }
74339    pParse->nHeight += pExpr->nHeight;
74340  }
74341#endif
74342  savedHasAgg = pNC->hasAgg;
74343  pNC->hasAgg = 0;
74344  w.xExprCallback = resolveExprStep;
74345  w.xSelectCallback = resolveSelectStep;
74346  w.pParse = pNC->pParse;
74347  w.u.pNC = pNC;
74348  sqlite3WalkExpr(&w, pExpr);
74349#if SQLITE_MAX_EXPR_DEPTH>0
74350  pNC->pParse->nHeight -= pExpr->nHeight;
74351#endif
74352  if( pNC->nErr>0 || w.pParse->nErr>0 ){
74353    ExprSetProperty(pExpr, EP_Error);
74354  }
74355  if( pNC->hasAgg ){
74356    ExprSetProperty(pExpr, EP_Agg);
74357  }else if( savedHasAgg ){
74358    pNC->hasAgg = 1;
74359  }
74360  return ExprHasProperty(pExpr, EP_Error);
74361}
74362
74363
74364/*
74365** Resolve all names in all expressions of a SELECT and in all
74366** decendents of the SELECT, including compounds off of p->pPrior,
74367** subqueries in expressions, and subqueries used as FROM clause
74368** terms.
74369**
74370** See sqlite3ResolveExprNames() for a description of the kinds of
74371** transformations that occur.
74372**
74373** All SELECT statements should have been expanded using
74374** sqlite3SelectExpand() prior to invoking this routine.
74375*/
74376SQLITE_PRIVATE void sqlite3ResolveSelectNames(
74377  Parse *pParse,         /* The parser context */
74378  Select *p,             /* The SELECT statement being coded. */
74379  NameContext *pOuterNC  /* Name context for parent SELECT statement */
74380){
74381  Walker w;
74382
74383  assert( p!=0 );
74384  w.xExprCallback = resolveExprStep;
74385  w.xSelectCallback = resolveSelectStep;
74386  w.pParse = pParse;
74387  w.u.pNC = pOuterNC;
74388  sqlite3WalkSelect(&w, p);
74389}
74390
74391/************** End of resolve.c *********************************************/
74392/************** Begin file expr.c ********************************************/
74393/*
74394** 2001 September 15
74395**
74396** The author disclaims copyright to this source code.  In place of
74397** a legal notice, here is a blessing:
74398**
74399**    May you do good and not evil.
74400**    May you find forgiveness for yourself and forgive others.
74401**    May you share freely, never taking more than you give.
74402**
74403*************************************************************************
74404** This file contains routines used for analyzing expressions and
74405** for generating VDBE code that evaluates expressions in SQLite.
74406*/
74407
74408/*
74409** Return the 'affinity' of the expression pExpr if any.
74410**
74411** If pExpr is a column, a reference to a column via an 'AS' alias,
74412** or a sub-select with a column as the return value, then the
74413** affinity of that column is returned. Otherwise, 0x00 is returned,
74414** indicating no affinity for the expression.
74415**
74416** i.e. the WHERE clause expresssions in the following statements all
74417** have an affinity:
74418**
74419** CREATE TABLE t1(a);
74420** SELECT * FROM t1 WHERE a;
74421** SELECT a AS b FROM t1 WHERE b;
74422** SELECT * FROM t1 WHERE (select a from t1);
74423*/
74424SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
74425  int op = pExpr->op;
74426  if( op==TK_SELECT ){
74427    assert( pExpr->flags&EP_xIsSelect );
74428    return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
74429  }
74430#ifndef SQLITE_OMIT_CAST
74431  if( op==TK_CAST ){
74432    assert( !ExprHasProperty(pExpr, EP_IntValue) );
74433    return sqlite3AffinityType(pExpr->u.zToken);
74434  }
74435#endif
74436  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
74437   && pExpr->pTab!=0
74438  ){
74439    /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
74440    ** a TK_COLUMN but was previously evaluated and cached in a register */
74441    int j = pExpr->iColumn;
74442    if( j<0 ) return SQLITE_AFF_INTEGER;
74443    assert( pExpr->pTab && j<pExpr->pTab->nCol );
74444    return pExpr->pTab->aCol[j].affinity;
74445  }
74446  return pExpr->affinity;
74447}
74448
74449/*
74450** Set the explicit collating sequence for an expression to the
74451** collating sequence supplied in the second argument.
74452*/
74453SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Expr *pExpr, CollSeq *pColl){
74454  if( pExpr && pColl ){
74455    pExpr->pColl = pColl;
74456    pExpr->flags |= EP_ExpCollate;
74457  }
74458  return pExpr;
74459}
74460
74461/*
74462** Set the collating sequence for expression pExpr to be the collating
74463** sequence named by pToken.   Return a pointer to the revised expression.
74464** The collating sequence is marked as "explicit" using the EP_ExpCollate
74465** flag.  An explicit collating sequence will override implicit
74466** collating sequences.
74467*/
74468SQLITE_PRIVATE Expr *sqlite3ExprSetCollByToken(Parse *pParse, Expr *pExpr, Token *pCollName){
74469  char *zColl = 0;            /* Dequoted name of collation sequence */
74470  CollSeq *pColl;
74471  sqlite3 *db = pParse->db;
74472  zColl = sqlite3NameFromToken(db, pCollName);
74473  pColl = sqlite3LocateCollSeq(pParse, zColl);
74474  sqlite3ExprSetColl(pExpr, pColl);
74475  sqlite3DbFree(db, zColl);
74476  return pExpr;
74477}
74478
74479/*
74480** Return the default collation sequence for the expression pExpr. If
74481** there is no default collation type, return 0.
74482*/
74483SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
74484  CollSeq *pColl = 0;
74485  Expr *p = pExpr;
74486  while( p ){
74487    int op;
74488    pColl = p->pColl;
74489    if( pColl ) break;
74490    op = p->op;
74491    if( p->pTab!=0 && (
74492        op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
74493    )){
74494      /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
74495      ** a TK_COLUMN but was previously evaluated and cached in a register */
74496      const char *zColl;
74497      int j = p->iColumn;
74498      if( j>=0 ){
74499        sqlite3 *db = pParse->db;
74500        zColl = p->pTab->aCol[j].zColl;
74501        pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
74502        pExpr->pColl = pColl;
74503      }
74504      break;
74505    }
74506    if( op!=TK_CAST && op!=TK_UPLUS ){
74507      break;
74508    }
74509    p = p->pLeft;
74510  }
74511  if( sqlite3CheckCollSeq(pParse, pColl) ){
74512    pColl = 0;
74513  }
74514  return pColl;
74515}
74516
74517/*
74518** pExpr is an operand of a comparison operator.  aff2 is the
74519** type affinity of the other operand.  This routine returns the
74520** type affinity that should be used for the comparison operator.
74521*/
74522SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
74523  char aff1 = sqlite3ExprAffinity(pExpr);
74524  if( aff1 && aff2 ){
74525    /* Both sides of the comparison are columns. If one has numeric
74526    ** affinity, use that. Otherwise use no affinity.
74527    */
74528    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
74529      return SQLITE_AFF_NUMERIC;
74530    }else{
74531      return SQLITE_AFF_NONE;
74532    }
74533  }else if( !aff1 && !aff2 ){
74534    /* Neither side of the comparison is a column.  Compare the
74535    ** results directly.
74536    */
74537    return SQLITE_AFF_NONE;
74538  }else{
74539    /* One side is a column, the other is not. Use the columns affinity. */
74540    assert( aff1==0 || aff2==0 );
74541    return (aff1 + aff2);
74542  }
74543}
74544
74545/*
74546** pExpr is a comparison operator.  Return the type affinity that should
74547** be applied to both operands prior to doing the comparison.
74548*/
74549static char comparisonAffinity(Expr *pExpr){
74550  char aff;
74551  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
74552          pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
74553          pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
74554  assert( pExpr->pLeft );
74555  aff = sqlite3ExprAffinity(pExpr->pLeft);
74556  if( pExpr->pRight ){
74557    aff = sqlite3CompareAffinity(pExpr->pRight, aff);
74558  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74559    aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
74560  }else if( !aff ){
74561    aff = SQLITE_AFF_NONE;
74562  }
74563  return aff;
74564}
74565
74566/*
74567** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
74568** idx_affinity is the affinity of an indexed column. Return true
74569** if the index with affinity idx_affinity may be used to implement
74570** the comparison in pExpr.
74571*/
74572SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
74573  char aff = comparisonAffinity(pExpr);
74574  switch( aff ){
74575    case SQLITE_AFF_NONE:
74576      return 1;
74577    case SQLITE_AFF_TEXT:
74578      return idx_affinity==SQLITE_AFF_TEXT;
74579    default:
74580      return sqlite3IsNumericAffinity(idx_affinity);
74581  }
74582}
74583
74584/*
74585** Return the P5 value that should be used for a binary comparison
74586** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
74587*/
74588static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
74589  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
74590  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
74591  return aff;
74592}
74593
74594/*
74595** Return a pointer to the collation sequence that should be used by
74596** a binary comparison operator comparing pLeft and pRight.
74597**
74598** If the left hand expression has a collating sequence type, then it is
74599** used. Otherwise the collation sequence for the right hand expression
74600** is used, or the default (BINARY) if neither expression has a collating
74601** type.
74602**
74603** Argument pRight (but not pLeft) may be a null pointer. In this case,
74604** it is not considered.
74605*/
74606SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
74607  Parse *pParse,
74608  Expr *pLeft,
74609  Expr *pRight
74610){
74611  CollSeq *pColl;
74612  assert( pLeft );
74613  if( pLeft->flags & EP_ExpCollate ){
74614    assert( pLeft->pColl );
74615    pColl = pLeft->pColl;
74616  }else if( pRight && pRight->flags & EP_ExpCollate ){
74617    assert( pRight->pColl );
74618    pColl = pRight->pColl;
74619  }else{
74620    pColl = sqlite3ExprCollSeq(pParse, pLeft);
74621    if( !pColl ){
74622      pColl = sqlite3ExprCollSeq(pParse, pRight);
74623    }
74624  }
74625  return pColl;
74626}
74627
74628/*
74629** Generate code for a comparison operator.
74630*/
74631static int codeCompare(
74632  Parse *pParse,    /* The parsing (and code generating) context */
74633  Expr *pLeft,      /* The left operand */
74634  Expr *pRight,     /* The right operand */
74635  int opcode,       /* The comparison opcode */
74636  int in1, int in2, /* Register holding operands */
74637  int dest,         /* Jump here if true.  */
74638  int jumpIfNull    /* If true, jump if either operand is NULL */
74639){
74640  int p5;
74641  int addr;
74642  CollSeq *p4;
74643
74644  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
74645  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
74646  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
74647                           (void*)p4, P4_COLLSEQ);
74648  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
74649  return addr;
74650}
74651
74652#if SQLITE_MAX_EXPR_DEPTH>0
74653/*
74654** Check that argument nHeight is less than or equal to the maximum
74655** expression depth allowed. If it is not, leave an error message in
74656** pParse.
74657*/
74658SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
74659  int rc = SQLITE_OK;
74660  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
74661  if( nHeight>mxHeight ){
74662    sqlite3ErrorMsg(pParse,
74663       "Expression tree is too large (maximum depth %d)", mxHeight
74664    );
74665    rc = SQLITE_ERROR;
74666  }
74667  return rc;
74668}
74669
74670/* The following three functions, heightOfExpr(), heightOfExprList()
74671** and heightOfSelect(), are used to determine the maximum height
74672** of any expression tree referenced by the structure passed as the
74673** first argument.
74674**
74675** If this maximum height is greater than the current value pointed
74676** to by pnHeight, the second parameter, then set *pnHeight to that
74677** value.
74678*/
74679static void heightOfExpr(Expr *p, int *pnHeight){
74680  if( p ){
74681    if( p->nHeight>*pnHeight ){
74682      *pnHeight = p->nHeight;
74683    }
74684  }
74685}
74686static void heightOfExprList(ExprList *p, int *pnHeight){
74687  if( p ){
74688    int i;
74689    for(i=0; i<p->nExpr; i++){
74690      heightOfExpr(p->a[i].pExpr, pnHeight);
74691    }
74692  }
74693}
74694static void heightOfSelect(Select *p, int *pnHeight){
74695  if( p ){
74696    heightOfExpr(p->pWhere, pnHeight);
74697    heightOfExpr(p->pHaving, pnHeight);
74698    heightOfExpr(p->pLimit, pnHeight);
74699    heightOfExpr(p->pOffset, pnHeight);
74700    heightOfExprList(p->pEList, pnHeight);
74701    heightOfExprList(p->pGroupBy, pnHeight);
74702    heightOfExprList(p->pOrderBy, pnHeight);
74703    heightOfSelect(p->pPrior, pnHeight);
74704  }
74705}
74706
74707/*
74708** Set the Expr.nHeight variable in the structure passed as an
74709** argument. An expression with no children, Expr.pList or
74710** Expr.pSelect member has a height of 1. Any other expression
74711** has a height equal to the maximum height of any other
74712** referenced Expr plus one.
74713*/
74714static void exprSetHeight(Expr *p){
74715  int nHeight = 0;
74716  heightOfExpr(p->pLeft, &nHeight);
74717  heightOfExpr(p->pRight, &nHeight);
74718  if( ExprHasProperty(p, EP_xIsSelect) ){
74719    heightOfSelect(p->x.pSelect, &nHeight);
74720  }else{
74721    heightOfExprList(p->x.pList, &nHeight);
74722  }
74723  p->nHeight = nHeight + 1;
74724}
74725
74726/*
74727** Set the Expr.nHeight variable using the exprSetHeight() function. If
74728** the height is greater than the maximum allowed expression depth,
74729** leave an error in pParse.
74730*/
74731SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
74732  exprSetHeight(p);
74733  sqlite3ExprCheckHeight(pParse, p->nHeight);
74734}
74735
74736/*
74737** Return the maximum height of any expression tree referenced
74738** by the select statement passed as an argument.
74739*/
74740SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
74741  int nHeight = 0;
74742  heightOfSelect(p, &nHeight);
74743  return nHeight;
74744}
74745#else
74746  #define exprSetHeight(y)
74747#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
74748
74749/*
74750** This routine is the core allocator for Expr nodes.
74751**
74752** Construct a new expression node and return a pointer to it.  Memory
74753** for this node and for the pToken argument is a single allocation
74754** obtained from sqlite3DbMalloc().  The calling function
74755** is responsible for making sure the node eventually gets freed.
74756**
74757** If dequote is true, then the token (if it exists) is dequoted.
74758** If dequote is false, no dequoting is performance.  The deQuote
74759** parameter is ignored if pToken is NULL or if the token does not
74760** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
74761** then the EP_DblQuoted flag is set on the expression node.
74762**
74763** Special case:  If op==TK_INTEGER and pToken points to a string that
74764** can be translated into a 32-bit integer, then the token is not
74765** stored in u.zToken.  Instead, the integer values is written
74766** into u.iValue and the EP_IntValue flag is set.  No extra storage
74767** is allocated to hold the integer text and the dequote flag is ignored.
74768*/
74769SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
74770  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74771  int op,                 /* Expression opcode */
74772  const Token *pToken,    /* Token argument.  Might be NULL */
74773  int dequote             /* True to dequote */
74774){
74775  Expr *pNew;
74776  int nExtra = 0;
74777  int iValue = 0;
74778
74779  if( pToken ){
74780    if( op!=TK_INTEGER || pToken->z==0
74781          || sqlite3GetInt32(pToken->z, &iValue)==0 ){
74782      nExtra = pToken->n+1;
74783      assert( iValue>=0 );
74784    }
74785  }
74786  pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
74787  if( pNew ){
74788    pNew->op = (u8)op;
74789    pNew->iAgg = -1;
74790    if( pToken ){
74791      if( nExtra==0 ){
74792        pNew->flags |= EP_IntValue;
74793        pNew->u.iValue = iValue;
74794      }else{
74795        int c;
74796        pNew->u.zToken = (char*)&pNew[1];
74797        assert( pToken->z!=0 || pToken->n==0 );
74798        if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
74799        pNew->u.zToken[pToken->n] = 0;
74800        if( dequote && nExtra>=3
74801             && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
74802          sqlite3Dequote(pNew->u.zToken);
74803          if( c=='"' ) pNew->flags |= EP_DblQuoted;
74804        }
74805      }
74806    }
74807#if SQLITE_MAX_EXPR_DEPTH>0
74808    pNew->nHeight = 1;
74809#endif
74810  }
74811  return pNew;
74812}
74813
74814/*
74815** Allocate a new expression node from a zero-terminated token that has
74816** already been dequoted.
74817*/
74818SQLITE_PRIVATE Expr *sqlite3Expr(
74819  sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
74820  int op,                 /* Expression opcode */
74821  const char *zToken      /* Token argument.  Might be NULL */
74822){
74823  Token x;
74824  x.z = zToken;
74825  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
74826  return sqlite3ExprAlloc(db, op, &x, 0);
74827}
74828
74829/*
74830** Attach subtrees pLeft and pRight to the Expr node pRoot.
74831**
74832** If pRoot==NULL that means that a memory allocation error has occurred.
74833** In that case, delete the subtrees pLeft and pRight.
74834*/
74835SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
74836  sqlite3 *db,
74837  Expr *pRoot,
74838  Expr *pLeft,
74839  Expr *pRight
74840){
74841  if( pRoot==0 ){
74842    assert( db->mallocFailed );
74843    sqlite3ExprDelete(db, pLeft);
74844    sqlite3ExprDelete(db, pRight);
74845  }else{
74846    if( pRight ){
74847      pRoot->pRight = pRight;
74848      if( pRight->flags & EP_ExpCollate ){
74849        pRoot->flags |= EP_ExpCollate;
74850        pRoot->pColl = pRight->pColl;
74851      }
74852    }
74853    if( pLeft ){
74854      pRoot->pLeft = pLeft;
74855      if( pLeft->flags & EP_ExpCollate ){
74856        pRoot->flags |= EP_ExpCollate;
74857        pRoot->pColl = pLeft->pColl;
74858      }
74859    }
74860    exprSetHeight(pRoot);
74861  }
74862}
74863
74864/*
74865** Allocate a Expr node which joins as many as two subtrees.
74866**
74867** One or both of the subtrees can be NULL.  Return a pointer to the new
74868** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
74869** free the subtrees and return NULL.
74870*/
74871SQLITE_PRIVATE Expr *sqlite3PExpr(
74872  Parse *pParse,          /* Parsing context */
74873  int op,                 /* Expression opcode */
74874  Expr *pLeft,            /* Left operand */
74875  Expr *pRight,           /* Right operand */
74876  const Token *pToken     /* Argument token */
74877){
74878  Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
74879  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
74880  if( p ) {
74881    sqlite3ExprCheckHeight(pParse, p->nHeight);
74882  }
74883  return p;
74884}
74885
74886/*
74887** Join two expressions using an AND operator.  If either expression is
74888** NULL, then just return the other expression.
74889*/
74890SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
74891  if( pLeft==0 ){
74892    return pRight;
74893  }else if( pRight==0 ){
74894    return pLeft;
74895  }else{
74896    Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
74897    sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
74898    return pNew;
74899  }
74900}
74901
74902/*
74903** Construct a new expression node for a function with multiple
74904** arguments.
74905*/
74906SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
74907  Expr *pNew;
74908  sqlite3 *db = pParse->db;
74909  assert( pToken );
74910  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
74911  if( pNew==0 ){
74912    sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
74913    return 0;
74914  }
74915  pNew->x.pList = pList;
74916  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
74917  sqlite3ExprSetHeight(pParse, pNew);
74918  return pNew;
74919}
74920
74921/*
74922** Assign a variable number to an expression that encodes a wildcard
74923** in the original SQL statement.
74924**
74925** Wildcards consisting of a single "?" are assigned the next sequential
74926** variable number.
74927**
74928** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
74929** sure "nnn" is not too be to avoid a denial of service attack when
74930** the SQL statement comes from an external source.
74931**
74932** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
74933** as the previous instance of the same wildcard.  Or if this is the first
74934** instance of the wildcard, the next sequenial variable number is
74935** assigned.
74936*/
74937SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
74938  sqlite3 *db = pParse->db;
74939  const char *z;
74940
74941  if( pExpr==0 ) return;
74942  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
74943  z = pExpr->u.zToken;
74944  assert( z!=0 );
74945  assert( z[0]!=0 );
74946  if( z[1]==0 ){
74947    /* Wildcard of the form "?".  Assign the next variable number */
74948    assert( z[0]=='?' );
74949    pExpr->iColumn = (ynVar)(++pParse->nVar);
74950  }else{
74951    ynVar x = 0;
74952    u32 n = sqlite3Strlen30(z);
74953    if( z[0]=='?' ){
74954      /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
74955      ** use it as the variable number */
74956      i64 i;
74957      int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
74958      pExpr->iColumn = x = (ynVar)i;
74959      testcase( i==0 );
74960      testcase( i==1 );
74961      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
74962      testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
74963      if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
74964        sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
74965            db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
74966        x = 0;
74967      }
74968      if( i>pParse->nVar ){
74969        pParse->nVar = (int)i;
74970      }
74971    }else{
74972      /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
74973      ** number as the prior appearance of the same name, or if the name
74974      ** has never appeared before, reuse the same variable number
74975      */
74976      ynVar i;
74977      for(i=0; i<pParse->nzVar; i++){
74978        if( pParse->azVar[i] && memcmp(pParse->azVar[i],z,n+1)==0 ){
74979          pExpr->iColumn = x = (ynVar)i+1;
74980          break;
74981        }
74982      }
74983      if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
74984    }
74985    if( x>0 ){
74986      if( x>pParse->nzVar ){
74987        char **a;
74988        a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
74989        if( a==0 ) return;  /* Error reported through db->mallocFailed */
74990        pParse->azVar = a;
74991        memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
74992        pParse->nzVar = x;
74993      }
74994      if( z[0]!='?' || pParse->azVar[x-1]==0 ){
74995        sqlite3DbFree(db, pParse->azVar[x-1]);
74996        pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
74997      }
74998    }
74999  }
75000  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
75001    sqlite3ErrorMsg(pParse, "too many SQL variables");
75002  }
75003}
75004
75005/*
75006** Recursively delete an expression tree.
75007*/
75008SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
75009  if( p==0 ) return;
75010  /* Sanity check: Assert that the IntValue is non-negative if it exists */
75011  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
75012  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
75013    sqlite3ExprDelete(db, p->pLeft);
75014    sqlite3ExprDelete(db, p->pRight);
75015    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
75016      sqlite3DbFree(db, p->u.zToken);
75017    }
75018    if( ExprHasProperty(p, EP_xIsSelect) ){
75019      sqlite3SelectDelete(db, p->x.pSelect);
75020    }else{
75021      sqlite3ExprListDelete(db, p->x.pList);
75022    }
75023  }
75024  if( !ExprHasProperty(p, EP_Static) ){
75025    sqlite3DbFree(db, p);
75026  }
75027}
75028
75029/*
75030** Return the number of bytes allocated for the expression structure
75031** passed as the first argument. This is always one of EXPR_FULLSIZE,
75032** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
75033*/
75034static int exprStructSize(Expr *p){
75035  if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
75036  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
75037  return EXPR_FULLSIZE;
75038}
75039
75040/*
75041** The dupedExpr*Size() routines each return the number of bytes required
75042** to store a copy of an expression or expression tree.  They differ in
75043** how much of the tree is measured.
75044**
75045**     dupedExprStructSize()     Size of only the Expr structure
75046**     dupedExprNodeSize()       Size of Expr + space for token
75047**     dupedExprSize()           Expr + token + subtree components
75048**
75049***************************************************************************
75050**
75051** The dupedExprStructSize() function returns two values OR-ed together:
75052** (1) the space required for a copy of the Expr structure only and
75053** (2) the EP_xxx flags that indicate what the structure size should be.
75054** The return values is always one of:
75055**
75056**      EXPR_FULLSIZE
75057**      EXPR_REDUCEDSIZE   | EP_Reduced
75058**      EXPR_TOKENONLYSIZE | EP_TokenOnly
75059**
75060** The size of the structure can be found by masking the return value
75061** of this routine with 0xfff.  The flags can be found by masking the
75062** return value with EP_Reduced|EP_TokenOnly.
75063**
75064** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
75065** (unreduced) Expr objects as they or originally constructed by the parser.
75066** During expression analysis, extra information is computed and moved into
75067** later parts of teh Expr object and that extra information might get chopped
75068** off if the expression is reduced.  Note also that it does not work to
75069** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
75070** to reduce a pristine expression tree from the parser.  The implementation
75071** of dupedExprStructSize() contain multiple assert() statements that attempt
75072** to enforce this constraint.
75073*/
75074static int dupedExprStructSize(Expr *p, int flags){
75075  int nSize;
75076  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
75077  if( 0==(flags&EXPRDUP_REDUCE) ){
75078    nSize = EXPR_FULLSIZE;
75079  }else{
75080    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
75081    assert( !ExprHasProperty(p, EP_FromJoin) );
75082    assert( (p->flags2 & EP2_MallocedToken)==0 );
75083    assert( (p->flags2 & EP2_Irreducible)==0 );
75084    if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
75085      nSize = EXPR_REDUCEDSIZE | EP_Reduced;
75086    }else{
75087      nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
75088    }
75089  }
75090  return nSize;
75091}
75092
75093/*
75094** This function returns the space in bytes required to store the copy
75095** of the Expr structure and a copy of the Expr.u.zToken string (if that
75096** string is defined.)
75097*/
75098static int dupedExprNodeSize(Expr *p, int flags){
75099  int nByte = dupedExprStructSize(p, flags) & 0xfff;
75100  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75101    nByte += sqlite3Strlen30(p->u.zToken)+1;
75102  }
75103  return ROUND8(nByte);
75104}
75105
75106/*
75107** Return the number of bytes required to create a duplicate of the
75108** expression passed as the first argument. The second argument is a
75109** mask containing EXPRDUP_XXX flags.
75110**
75111** The value returned includes space to create a copy of the Expr struct
75112** itself and the buffer referred to by Expr.u.zToken, if any.
75113**
75114** If the EXPRDUP_REDUCE flag is set, then the return value includes
75115** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
75116** and Expr.pRight variables (but not for any structures pointed to or
75117** descended from the Expr.x.pList or Expr.x.pSelect variables).
75118*/
75119static int dupedExprSize(Expr *p, int flags){
75120  int nByte = 0;
75121  if( p ){
75122    nByte = dupedExprNodeSize(p, flags);
75123    if( flags&EXPRDUP_REDUCE ){
75124      nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
75125    }
75126  }
75127  return nByte;
75128}
75129
75130/*
75131** This function is similar to sqlite3ExprDup(), except that if pzBuffer
75132** is not NULL then *pzBuffer is assumed to point to a buffer large enough
75133** to store the copy of expression p, the copies of p->u.zToken
75134** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
75135** if any. Before returning, *pzBuffer is set to the first byte passed the
75136** portion of the buffer copied into by this function.
75137*/
75138static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
75139  Expr *pNew = 0;                      /* Value to return */
75140  if( p ){
75141    const int isReduced = (flags&EXPRDUP_REDUCE);
75142    u8 *zAlloc;
75143    u32 staticFlag = 0;
75144
75145    assert( pzBuffer==0 || isReduced );
75146
75147    /* Figure out where to write the new Expr structure. */
75148    if( pzBuffer ){
75149      zAlloc = *pzBuffer;
75150      staticFlag = EP_Static;
75151    }else{
75152      zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
75153    }
75154    pNew = (Expr *)zAlloc;
75155
75156    if( pNew ){
75157      /* Set nNewSize to the size allocated for the structure pointed to
75158      ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
75159      ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
75160      ** by the copy of the p->u.zToken string (if any).
75161      */
75162      const unsigned nStructSize = dupedExprStructSize(p, flags);
75163      const int nNewSize = nStructSize & 0xfff;
75164      int nToken;
75165      if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75166        nToken = sqlite3Strlen30(p->u.zToken) + 1;
75167      }else{
75168        nToken = 0;
75169      }
75170      if( isReduced ){
75171        assert( ExprHasProperty(p, EP_Reduced)==0 );
75172        memcpy(zAlloc, p, nNewSize);
75173      }else{
75174        int nSize = exprStructSize(p);
75175        memcpy(zAlloc, p, nSize);
75176        memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
75177      }
75178
75179      /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
75180      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
75181      pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
75182      pNew->flags |= staticFlag;
75183
75184      /* Copy the p->u.zToken string, if any. */
75185      if( nToken ){
75186        char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
75187        memcpy(zToken, p->u.zToken, nToken);
75188      }
75189
75190      if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
75191        /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
75192        if( ExprHasProperty(p, EP_xIsSelect) ){
75193          pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
75194        }else{
75195          pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
75196        }
75197      }
75198
75199      /* Fill in pNew->pLeft and pNew->pRight. */
75200      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
75201        zAlloc += dupedExprNodeSize(p, flags);
75202        if( ExprHasProperty(pNew, EP_Reduced) ){
75203          pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
75204          pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
75205        }
75206        if( pzBuffer ){
75207          *pzBuffer = zAlloc;
75208        }
75209      }else{
75210        pNew->flags2 = 0;
75211        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
75212          pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
75213          pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
75214        }
75215      }
75216
75217    }
75218  }
75219  return pNew;
75220}
75221
75222/*
75223** The following group of routines make deep copies of expressions,
75224** expression lists, ID lists, and select statements.  The copies can
75225** be deleted (by being passed to their respective ...Delete() routines)
75226** without effecting the originals.
75227**
75228** The expression list, ID, and source lists return by sqlite3ExprListDup(),
75229** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
75230** by subsequent calls to sqlite*ListAppend() routines.
75231**
75232** Any tables that the SrcList might point to are not duplicated.
75233**
75234** The flags parameter contains a combination of the EXPRDUP_XXX flags.
75235** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
75236** truncated version of the usual Expr structure that will be stored as
75237** part of the in-memory representation of the database schema.
75238*/
75239SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
75240  return exprDup(db, p, flags, 0);
75241}
75242SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
75243  ExprList *pNew;
75244  struct ExprList_item *pItem, *pOldItem;
75245  int i;
75246  if( p==0 ) return 0;
75247  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
75248  if( pNew==0 ) return 0;
75249  pNew->iECursor = 0;
75250  pNew->nExpr = i = p->nExpr;
75251  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
75252  pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
75253  if( pItem==0 ){
75254    sqlite3DbFree(db, pNew);
75255    return 0;
75256  }
75257  pOldItem = p->a;
75258  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
75259    Expr *pOldExpr = pOldItem->pExpr;
75260    pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
75261    pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
75262    pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
75263    pItem->sortOrder = pOldItem->sortOrder;
75264    pItem->done = 0;
75265    pItem->iOrderByCol = pOldItem->iOrderByCol;
75266    pItem->iAlias = pOldItem->iAlias;
75267  }
75268  return pNew;
75269}
75270
75271/*
75272** If cursors, triggers, views and subqueries are all omitted from
75273** the build, then none of the following routines, except for
75274** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
75275** called with a NULL argument.
75276*/
75277#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
75278 || !defined(SQLITE_OMIT_SUBQUERY)
75279SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
75280  SrcList *pNew;
75281  int i;
75282  int nByte;
75283  if( p==0 ) return 0;
75284  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
75285  pNew = sqlite3DbMallocRaw(db, nByte );
75286  if( pNew==0 ) return 0;
75287  pNew->nSrc = pNew->nAlloc = p->nSrc;
75288  for(i=0; i<p->nSrc; i++){
75289    struct SrcList_item *pNewItem = &pNew->a[i];
75290    struct SrcList_item *pOldItem = &p->a[i];
75291    Table *pTab;
75292    pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
75293    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
75294    pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
75295    pNewItem->jointype = pOldItem->jointype;
75296    pNewItem->iCursor = pOldItem->iCursor;
75297    pNewItem->addrFillSub = pOldItem->addrFillSub;
75298    pNewItem->regReturn = pOldItem->regReturn;
75299    pNewItem->isCorrelated = pOldItem->isCorrelated;
75300    pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
75301    pNewItem->notIndexed = pOldItem->notIndexed;
75302    pNewItem->pIndex = pOldItem->pIndex;
75303    pTab = pNewItem->pTab = pOldItem->pTab;
75304    if( pTab ){
75305      pTab->nRef++;
75306    }
75307    pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
75308    pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
75309    pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
75310    pNewItem->colUsed = pOldItem->colUsed;
75311  }
75312  return pNew;
75313}
75314SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
75315  IdList *pNew;
75316  int i;
75317  if( p==0 ) return 0;
75318  pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
75319  if( pNew==0 ) return 0;
75320  pNew->nId = p->nId;
75321  pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
75322  if( pNew->a==0 ){
75323    sqlite3DbFree(db, pNew);
75324    return 0;
75325  }
75326  /* Note that because the size of the allocation for p->a[] is not
75327  ** necessarily a power of two, sqlite3IdListAppend() may not be called
75328  ** on the duplicate created by this function. */
75329  for(i=0; i<p->nId; i++){
75330    struct IdList_item *pNewItem = &pNew->a[i];
75331    struct IdList_item *pOldItem = &p->a[i];
75332    pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
75333    pNewItem->idx = pOldItem->idx;
75334  }
75335  return pNew;
75336}
75337SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
75338  Select *pNew, *pPrior;
75339  if( p==0 ) return 0;
75340  pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
75341  if( pNew==0 ) return 0;
75342  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
75343  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
75344  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
75345  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
75346  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
75347  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
75348  pNew->op = p->op;
75349  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
75350  if( pPrior ) pPrior->pNext = pNew;
75351  pNew->pNext = 0;
75352  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
75353  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
75354  pNew->iLimit = 0;
75355  pNew->iOffset = 0;
75356  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
75357  pNew->pRightmost = 0;
75358  pNew->addrOpenEphm[0] = -1;
75359  pNew->addrOpenEphm[1] = -1;
75360  pNew->addrOpenEphm[2] = -1;
75361  return pNew;
75362}
75363#else
75364SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
75365  assert( p==0 );
75366  return 0;
75367}
75368#endif
75369
75370
75371/*
75372** Add a new element to the end of an expression list.  If pList is
75373** initially NULL, then create a new expression list.
75374**
75375** If a memory allocation error occurs, the entire list is freed and
75376** NULL is returned.  If non-NULL is returned, then it is guaranteed
75377** that the new entry was successfully appended.
75378*/
75379SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
75380  Parse *pParse,          /* Parsing context */
75381  ExprList *pList,        /* List to which to append. Might be NULL */
75382  Expr *pExpr             /* Expression to be appended. Might be NULL */
75383){
75384  sqlite3 *db = pParse->db;
75385  if( pList==0 ){
75386    pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
75387    if( pList==0 ){
75388      goto no_mem;
75389    }
75390    pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
75391    if( pList->a==0 ) goto no_mem;
75392  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
75393    struct ExprList_item *a;
75394    assert( pList->nExpr>0 );
75395    a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
75396    if( a==0 ){
75397      goto no_mem;
75398    }
75399    pList->a = a;
75400  }
75401  assert( pList->a!=0 );
75402  if( 1 ){
75403    struct ExprList_item *pItem = &pList->a[pList->nExpr++];
75404    memset(pItem, 0, sizeof(*pItem));
75405    pItem->pExpr = pExpr;
75406  }
75407  return pList;
75408
75409no_mem:
75410  /* Avoid leaking memory if malloc has failed. */
75411  sqlite3ExprDelete(db, pExpr);
75412  sqlite3ExprListDelete(db, pList);
75413  return 0;
75414}
75415
75416/*
75417** Set the ExprList.a[].zName element of the most recently added item
75418** on the expression list.
75419**
75420** pList might be NULL following an OOM error.  But pName should never be
75421** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75422** is set.
75423*/
75424SQLITE_PRIVATE void sqlite3ExprListSetName(
75425  Parse *pParse,          /* Parsing context */
75426  ExprList *pList,        /* List to which to add the span. */
75427  Token *pName,           /* Name to be added */
75428  int dequote             /* True to cause the name to be dequoted */
75429){
75430  assert( pList!=0 || pParse->db->mallocFailed!=0 );
75431  if( pList ){
75432    struct ExprList_item *pItem;
75433    assert( pList->nExpr>0 );
75434    pItem = &pList->a[pList->nExpr-1];
75435    assert( pItem->zName==0 );
75436    pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
75437    if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
75438  }
75439}
75440
75441/*
75442** Set the ExprList.a[].zSpan element of the most recently added item
75443** on the expression list.
75444**
75445** pList might be NULL following an OOM error.  But pSpan should never be
75446** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
75447** is set.
75448*/
75449SQLITE_PRIVATE void sqlite3ExprListSetSpan(
75450  Parse *pParse,          /* Parsing context */
75451  ExprList *pList,        /* List to which to add the span. */
75452  ExprSpan *pSpan         /* The span to be added */
75453){
75454  sqlite3 *db = pParse->db;
75455  assert( pList!=0 || db->mallocFailed!=0 );
75456  if( pList ){
75457    struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
75458    assert( pList->nExpr>0 );
75459    assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
75460    sqlite3DbFree(db, pItem->zSpan);
75461    pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
75462                                    (int)(pSpan->zEnd - pSpan->zStart));
75463  }
75464}
75465
75466/*
75467** If the expression list pEList contains more than iLimit elements,
75468** leave an error message in pParse.
75469*/
75470SQLITE_PRIVATE void sqlite3ExprListCheckLength(
75471  Parse *pParse,
75472  ExprList *pEList,
75473  const char *zObject
75474){
75475  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
75476  testcase( pEList && pEList->nExpr==mx );
75477  testcase( pEList && pEList->nExpr==mx+1 );
75478  if( pEList && pEList->nExpr>mx ){
75479    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
75480  }
75481}
75482
75483/*
75484** Delete an entire expression list.
75485*/
75486SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
75487  int i;
75488  struct ExprList_item *pItem;
75489  if( pList==0 ) return;
75490  assert( pList->a!=0 || pList->nExpr==0 );
75491  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
75492    sqlite3ExprDelete(db, pItem->pExpr);
75493    sqlite3DbFree(db, pItem->zName);
75494    sqlite3DbFree(db, pItem->zSpan);
75495  }
75496  sqlite3DbFree(db, pList->a);
75497  sqlite3DbFree(db, pList);
75498}
75499
75500/*
75501** These routines are Walker callbacks.  Walker.u.pi is a pointer
75502** to an integer.  These routines are checking an expression to see
75503** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
75504** not constant.
75505**
75506** These callback routines are used to implement the following:
75507**
75508**     sqlite3ExprIsConstant()
75509**     sqlite3ExprIsConstantNotJoin()
75510**     sqlite3ExprIsConstantOrFunction()
75511**
75512*/
75513static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
75514
75515  /* If pWalker->u.i is 3 then any term of the expression that comes from
75516  ** the ON or USING clauses of a join disqualifies the expression
75517  ** from being considered constant. */
75518  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
75519    pWalker->u.i = 0;
75520    return WRC_Abort;
75521  }
75522
75523  switch( pExpr->op ){
75524    /* Consider functions to be constant if all their arguments are constant
75525    ** and pWalker->u.i==2 */
75526    case TK_FUNCTION:
75527      if( pWalker->u.i==2 ) return 0;
75528      /* Fall through */
75529    case TK_ID:
75530    case TK_COLUMN:
75531    case TK_AGG_FUNCTION:
75532    case TK_AGG_COLUMN:
75533      testcase( pExpr->op==TK_ID );
75534      testcase( pExpr->op==TK_COLUMN );
75535      testcase( pExpr->op==TK_AGG_FUNCTION );
75536      testcase( pExpr->op==TK_AGG_COLUMN );
75537      pWalker->u.i = 0;
75538      return WRC_Abort;
75539    default:
75540      testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
75541      testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
75542      return WRC_Continue;
75543  }
75544}
75545static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
75546  UNUSED_PARAMETER(NotUsed);
75547  pWalker->u.i = 0;
75548  return WRC_Abort;
75549}
75550static int exprIsConst(Expr *p, int initFlag){
75551  Walker w;
75552  w.u.i = initFlag;
75553  w.xExprCallback = exprNodeIsConstant;
75554  w.xSelectCallback = selectNodeIsConstant;
75555  sqlite3WalkExpr(&w, p);
75556  return w.u.i;
75557}
75558
75559/*
75560** Walk an expression tree.  Return 1 if the expression is constant
75561** and 0 if it involves variables or function calls.
75562**
75563** For the purposes of this function, a double-quoted string (ex: "abc")
75564** is considered a variable but a single-quoted string (ex: 'abc') is
75565** a constant.
75566*/
75567SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
75568  return exprIsConst(p, 1);
75569}
75570
75571/*
75572** Walk an expression tree.  Return 1 if the expression is constant
75573** that does no originate from the ON or USING clauses of a join.
75574** Return 0 if it involves variables or function calls or terms from
75575** an ON or USING clause.
75576*/
75577SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
75578  return exprIsConst(p, 3);
75579}
75580
75581/*
75582** Walk an expression tree.  Return 1 if the expression is constant
75583** or a function call with constant arguments.  Return and 0 if there
75584** are any variables.
75585**
75586** For the purposes of this function, a double-quoted string (ex: "abc")
75587** is considered a variable but a single-quoted string (ex: 'abc') is
75588** a constant.
75589*/
75590SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
75591  return exprIsConst(p, 2);
75592}
75593
75594/*
75595** If the expression p codes a constant integer that is small enough
75596** to fit in a 32-bit integer, return 1 and put the value of the integer
75597** in *pValue.  If the expression is not an integer or if it is too big
75598** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
75599*/
75600SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
75601  int rc = 0;
75602
75603  /* If an expression is an integer literal that fits in a signed 32-bit
75604  ** integer, then the EP_IntValue flag will have already been set */
75605  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
75606           || sqlite3GetInt32(p->u.zToken, &rc)==0 );
75607
75608  if( p->flags & EP_IntValue ){
75609    *pValue = p->u.iValue;
75610    return 1;
75611  }
75612  switch( p->op ){
75613    case TK_UPLUS: {
75614      rc = sqlite3ExprIsInteger(p->pLeft, pValue);
75615      break;
75616    }
75617    case TK_UMINUS: {
75618      int v;
75619      if( sqlite3ExprIsInteger(p->pLeft, &v) ){
75620        *pValue = -v;
75621        rc = 1;
75622      }
75623      break;
75624    }
75625    default: break;
75626  }
75627  return rc;
75628}
75629
75630/*
75631** Return FALSE if there is no chance that the expression can be NULL.
75632**
75633** If the expression might be NULL or if the expression is too complex
75634** to tell return TRUE.
75635**
75636** This routine is used as an optimization, to skip OP_IsNull opcodes
75637** when we know that a value cannot be NULL.  Hence, a false positive
75638** (returning TRUE when in fact the expression can never be NULL) might
75639** be a small performance hit but is otherwise harmless.  On the other
75640** hand, a false negative (returning FALSE when the result could be NULL)
75641** will likely result in an incorrect answer.  So when in doubt, return
75642** TRUE.
75643*/
75644SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
75645  u8 op;
75646  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75647  op = p->op;
75648  if( op==TK_REGISTER ) op = p->op2;
75649  switch( op ){
75650    case TK_INTEGER:
75651    case TK_STRING:
75652    case TK_FLOAT:
75653    case TK_BLOB:
75654      return 0;
75655    default:
75656      return 1;
75657  }
75658}
75659
75660/*
75661** Generate an OP_IsNull instruction that tests register iReg and jumps
75662** to location iDest if the value in iReg is NULL.  The value in iReg
75663** was computed by pExpr.  If we can look at pExpr at compile-time and
75664** determine that it can never generate a NULL, then the OP_IsNull operation
75665** can be omitted.
75666*/
75667SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
75668  Vdbe *v,            /* The VDBE under construction */
75669  const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
75670  int iReg,           /* Test the value in this register for NULL */
75671  int iDest           /* Jump here if the value is null */
75672){
75673  if( sqlite3ExprCanBeNull(pExpr) ){
75674    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
75675  }
75676}
75677
75678/*
75679** Return TRUE if the given expression is a constant which would be
75680** unchanged by OP_Affinity with the affinity given in the second
75681** argument.
75682**
75683** This routine is used to determine if the OP_Affinity operation
75684** can be omitted.  When in doubt return FALSE.  A false negative
75685** is harmless.  A false positive, however, can result in the wrong
75686** answer.
75687*/
75688SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
75689  u8 op;
75690  if( aff==SQLITE_AFF_NONE ) return 1;
75691  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
75692  op = p->op;
75693  if( op==TK_REGISTER ) op = p->op2;
75694  switch( op ){
75695    case TK_INTEGER: {
75696      return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
75697    }
75698    case TK_FLOAT: {
75699      return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
75700    }
75701    case TK_STRING: {
75702      return aff==SQLITE_AFF_TEXT;
75703    }
75704    case TK_BLOB: {
75705      return 1;
75706    }
75707    case TK_COLUMN: {
75708      assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
75709      return p->iColumn<0
75710          && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
75711    }
75712    default: {
75713      return 0;
75714    }
75715  }
75716}
75717
75718/*
75719** Return TRUE if the given string is a row-id column name.
75720*/
75721SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
75722  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
75723  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
75724  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
75725  return 0;
75726}
75727
75728/*
75729** Return true if we are able to the IN operator optimization on a
75730** query of the form
75731**
75732**       x IN (SELECT ...)
75733**
75734** Where the SELECT... clause is as specified by the parameter to this
75735** routine.
75736**
75737** The Select object passed in has already been preprocessed and no
75738** errors have been found.
75739*/
75740#ifndef SQLITE_OMIT_SUBQUERY
75741static int isCandidateForInOpt(Select *p){
75742  SrcList *pSrc;
75743  ExprList *pEList;
75744  Table *pTab;
75745  if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
75746  if( p->pPrior ) return 0;              /* Not a compound SELECT */
75747  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
75748    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
75749    testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
75750    return 0; /* No DISTINCT keyword and no aggregate functions */
75751  }
75752  assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
75753  if( p->pLimit ) return 0;              /* Has no LIMIT clause */
75754  assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
75755  if( p->pWhere ) return 0;              /* Has no WHERE clause */
75756  pSrc = p->pSrc;
75757  assert( pSrc!=0 );
75758  if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
75759  if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
75760  pTab = pSrc->a[0].pTab;
75761  if( NEVER(pTab==0) ) return 0;
75762  assert( pTab->pSelect==0 );            /* FROM clause is not a view */
75763  if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
75764  pEList = p->pEList;
75765  if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
75766  if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
75767  return 1;
75768}
75769#endif /* SQLITE_OMIT_SUBQUERY */
75770
75771/*
75772** Code an OP_Once instruction and allocate space for its flag. Return the
75773** address of the new instruction.
75774*/
75775SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
75776  Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
75777  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
75778}
75779
75780/*
75781** This function is used by the implementation of the IN (...) operator.
75782** It's job is to find or create a b-tree structure that may be used
75783** either to test for membership of the (...) set or to iterate through
75784** its members, skipping duplicates.
75785**
75786** The index of the cursor opened on the b-tree (database table, database index
75787** or ephermal table) is stored in pX->iTable before this function returns.
75788** The returned value of this function indicates the b-tree type, as follows:
75789**
75790**   IN_INDEX_ROWID - The cursor was opened on a database table.
75791**   IN_INDEX_INDEX - The cursor was opened on a database index.
75792**   IN_INDEX_EPH -   The cursor was opened on a specially created and
75793**                    populated epheremal table.
75794**
75795** An existing b-tree may only be used if the SELECT is of the simple
75796** form:
75797**
75798**     SELECT <column> FROM <table>
75799**
75800** If the prNotFound parameter is 0, then the b-tree will be used to iterate
75801** through the set members, skipping any duplicates. In this case an
75802** epheremal table must be used unless the selected <column> is guaranteed
75803** to be unique - either because it is an INTEGER PRIMARY KEY or it
75804** has a UNIQUE constraint or UNIQUE index.
75805**
75806** If the prNotFound parameter is not 0, then the b-tree will be used
75807** for fast set membership tests. In this case an epheremal table must
75808** be used unless <column> is an INTEGER PRIMARY KEY or an index can
75809** be found with <column> as its left-most column.
75810**
75811** When the b-tree is being used for membership tests, the calling function
75812** needs to know whether or not the structure contains an SQL NULL
75813** value in order to correctly evaluate expressions like "X IN (Y, Z)".
75814** If there is any chance that the (...) might contain a NULL value at
75815** runtime, then a register is allocated and the register number written
75816** to *prNotFound. If there is no chance that the (...) contains a
75817** NULL value, then *prNotFound is left unchanged.
75818**
75819** If a register is allocated and its location stored in *prNotFound, then
75820** its initial value is NULL.  If the (...) does not remain constant
75821** for the duration of the query (i.e. the SELECT within the (...)
75822** is a correlated subquery) then the value of the allocated register is
75823** reset to NULL each time the subquery is rerun. This allows the
75824** caller to use vdbe code equivalent to the following:
75825**
75826**   if( register==NULL ){
75827**     has_null = <test if data structure contains null>
75828**     register = 1
75829**   }
75830**
75831** in order to avoid running the <test if data structure contains null>
75832** test more often than is necessary.
75833*/
75834#ifndef SQLITE_OMIT_SUBQUERY
75835SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
75836  Select *p;                            /* SELECT to the right of IN operator */
75837  int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
75838  int iTab = pParse->nTab++;            /* Cursor of the RHS table */
75839  int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
75840  Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
75841
75842  assert( pX->op==TK_IN );
75843
75844  /* Check to see if an existing table or index can be used to
75845  ** satisfy the query.  This is preferable to generating a new
75846  ** ephemeral table.
75847  */
75848  p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
75849  if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
75850    sqlite3 *db = pParse->db;              /* Database connection */
75851    Table *pTab;                           /* Table <table>. */
75852    Expr *pExpr;                           /* Expression <column> */
75853    int iCol;                              /* Index of column <column> */
75854    int iDb;                               /* Database idx for pTab */
75855
75856    assert( p );                        /* Because of isCandidateForInOpt(p) */
75857    assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
75858    assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
75859    assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
75860    pTab = p->pSrc->a[0].pTab;
75861    pExpr = p->pEList->a[0].pExpr;
75862    iCol = pExpr->iColumn;
75863
75864    /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
75865    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75866    sqlite3CodeVerifySchema(pParse, iDb);
75867    sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
75868
75869    /* This function is only called from two places. In both cases the vdbe
75870    ** has already been allocated. So assume sqlite3GetVdbe() is always
75871    ** successful here.
75872    */
75873    assert(v);
75874    if( iCol<0 ){
75875      int iAddr;
75876
75877      iAddr = sqlite3CodeOnce(pParse);
75878
75879      sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
75880      eType = IN_INDEX_ROWID;
75881
75882      sqlite3VdbeJumpHere(v, iAddr);
75883    }else{
75884      Index *pIdx;                         /* Iterator variable */
75885
75886      /* The collation sequence used by the comparison. If an index is to
75887      ** be used in place of a temp-table, it must be ordered according
75888      ** to this collation sequence.  */
75889      CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
75890
75891      /* Check that the affinity that will be used to perform the
75892      ** comparison is the same as the affinity of the column. If
75893      ** it is not, it is not possible to use any index.
75894      */
75895      char aff = comparisonAffinity(pX);
75896      int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
75897
75898      for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
75899        if( (pIdx->aiColumn[0]==iCol)
75900         && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
75901         && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
75902        ){
75903          int iAddr;
75904          char *pKey;
75905
75906          pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
75907          iAddr = sqlite3CodeOnce(pParse);
75908
75909          sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
75910                               pKey,P4_KEYINFO_HANDOFF);
75911          VdbeComment((v, "%s", pIdx->zName));
75912          eType = IN_INDEX_INDEX;
75913
75914          sqlite3VdbeJumpHere(v, iAddr);
75915          if( prNotFound && !pTab->aCol[iCol].notNull ){
75916            *prNotFound = ++pParse->nMem;
75917            sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75918          }
75919        }
75920      }
75921    }
75922  }
75923
75924  if( eType==0 ){
75925    /* Could not found an existing table or index to use as the RHS b-tree.
75926    ** We will have to generate an ephemeral table to do the job.
75927    */
75928    double savedNQueryLoop = pParse->nQueryLoop;
75929    int rMayHaveNull = 0;
75930    eType = IN_INDEX_EPH;
75931    if( prNotFound ){
75932      *prNotFound = rMayHaveNull = ++pParse->nMem;
75933      sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
75934    }else{
75935      testcase( pParse->nQueryLoop>(double)1 );
75936      pParse->nQueryLoop = (double)1;
75937      if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
75938        eType = IN_INDEX_ROWID;
75939      }
75940    }
75941    sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
75942    pParse->nQueryLoop = savedNQueryLoop;
75943  }else{
75944    pX->iTable = iTab;
75945  }
75946  return eType;
75947}
75948#endif
75949
75950/*
75951** Generate code for scalar subqueries used as a subquery expression, EXISTS,
75952** or IN operators.  Examples:
75953**
75954**     (SELECT a FROM b)          -- subquery
75955**     EXISTS (SELECT a FROM b)   -- EXISTS subquery
75956**     x IN (4,5,11)              -- IN operator with list on right-hand side
75957**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
75958**
75959** The pExpr parameter describes the expression that contains the IN
75960** operator or subquery.
75961**
75962** If parameter isRowid is non-zero, then expression pExpr is guaranteed
75963** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
75964** to some integer key column of a table B-Tree. In this case, use an
75965** intkey B-Tree to store the set of IN(...) values instead of the usual
75966** (slower) variable length keys B-Tree.
75967**
75968** If rMayHaveNull is non-zero, that means that the operation is an IN
75969** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
75970** Furthermore, the IN is in a WHERE clause and that we really want
75971** to iterate over the RHS of the IN operator in order to quickly locate
75972** all corresponding LHS elements.  All this routine does is initialize
75973** the register given by rMayHaveNull to NULL.  Calling routines will take
75974** care of changing this register value to non-NULL if the RHS is NULL-free.
75975**
75976** If rMayHaveNull is zero, that means that the subquery is being used
75977** for membership testing only.  There is no need to initialize any
75978** registers to indicate the presense or absence of NULLs on the RHS.
75979**
75980** For a SELECT or EXISTS operator, return the register that holds the
75981** result.  For IN operators or if an error occurs, the return value is 0.
75982*/
75983#ifndef SQLITE_OMIT_SUBQUERY
75984SQLITE_PRIVATE int sqlite3CodeSubselect(
75985  Parse *pParse,          /* Parsing context */
75986  Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
75987  int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
75988  int isRowid             /* If true, LHS of IN operator is a rowid */
75989){
75990  int testAddr = -1;                      /* One-time test address */
75991  int rReg = 0;                           /* Register storing resulting */
75992  Vdbe *v = sqlite3GetVdbe(pParse);
75993  if( NEVER(v==0) ) return 0;
75994  sqlite3ExprCachePush(pParse);
75995
75996  /* This code must be run in its entirety every time it is encountered
75997  ** if any of the following is true:
75998  **
75999  **    *  The right-hand side is a correlated subquery
76000  **    *  The right-hand side is an expression list containing variables
76001  **    *  We are inside a trigger
76002  **
76003  ** If all of the above are false, then we can run this code just once
76004  ** save the results, and reuse the same result on subsequent invocations.
76005  */
76006  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
76007    testAddr = sqlite3CodeOnce(pParse);
76008  }
76009
76010#ifndef SQLITE_OMIT_EXPLAIN
76011  if( pParse->explain==2 ){
76012    char *zMsg = sqlite3MPrintf(
76013        pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
76014        pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
76015    );
76016    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
76017  }
76018#endif
76019
76020  switch( pExpr->op ){
76021    case TK_IN: {
76022      char affinity;              /* Affinity of the LHS of the IN */
76023      KeyInfo keyInfo;            /* Keyinfo for the generated table */
76024      int addr;                   /* Address of OP_OpenEphemeral instruction */
76025      Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
76026
76027      if( rMayHaveNull ){
76028        sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
76029      }
76030
76031      affinity = sqlite3ExprAffinity(pLeft);
76032
76033      /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
76034      ** expression it is handled the same way.  An ephemeral table is
76035      ** filled with single-field index keys representing the results
76036      ** from the SELECT or the <exprlist>.
76037      **
76038      ** If the 'x' expression is a column value, or the SELECT...
76039      ** statement returns a column value, then the affinity of that
76040      ** column is used to build the index keys. If both 'x' and the
76041      ** SELECT... statement are columns, then numeric affinity is used
76042      ** if either column has NUMERIC or INTEGER affinity. If neither
76043      ** 'x' nor the SELECT... statement are columns, then numeric affinity
76044      ** is used.
76045      */
76046      pExpr->iTable = pParse->nTab++;
76047      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
76048      if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
76049      memset(&keyInfo, 0, sizeof(keyInfo));
76050      keyInfo.nField = 1;
76051
76052      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76053        /* Case 1:     expr IN (SELECT ...)
76054        **
76055        ** Generate code to write the results of the select into the temporary
76056        ** table allocated and opened above.
76057        */
76058        SelectDest dest;
76059        ExprList *pEList;
76060
76061        assert( !isRowid );
76062        sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
76063        dest.affinity = (u8)affinity;
76064        assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
76065        pExpr->x.pSelect->iLimit = 0;
76066        if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
76067          return 0;
76068        }
76069        pEList = pExpr->x.pSelect->pEList;
76070        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
76071          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
76072              pEList->a[0].pExpr);
76073        }
76074      }else if( ALWAYS(pExpr->x.pList!=0) ){
76075        /* Case 2:     expr IN (exprlist)
76076        **
76077        ** For each expression, build an index key from the evaluation and
76078        ** store it in the temporary table. If <expr> is a column, then use
76079        ** that columns affinity when building index keys. If <expr> is not
76080        ** a column, use numeric affinity.
76081        */
76082        int i;
76083        ExprList *pList = pExpr->x.pList;
76084        struct ExprList_item *pItem;
76085        int r1, r2, r3;
76086
76087        if( !affinity ){
76088          affinity = SQLITE_AFF_NONE;
76089        }
76090        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
76091
76092        /* Loop through each expression in <exprlist>. */
76093        r1 = sqlite3GetTempReg(pParse);
76094        r2 = sqlite3GetTempReg(pParse);
76095        sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
76096        for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
76097          Expr *pE2 = pItem->pExpr;
76098          int iValToIns;
76099
76100          /* If the expression is not constant then we will need to
76101          ** disable the test that was generated above that makes sure
76102          ** this code only executes once.  Because for a non-constant
76103          ** expression we need to rerun this code each time.
76104          */
76105          if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
76106            sqlite3VdbeChangeToNoop(v, testAddr);
76107            testAddr = -1;
76108          }
76109
76110          /* Evaluate the expression and insert it into the temp table */
76111          if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
76112            sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
76113          }else{
76114            r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
76115            if( isRowid ){
76116              sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
76117                                sqlite3VdbeCurrentAddr(v)+2);
76118              sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
76119            }else{
76120              sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
76121              sqlite3ExprCacheAffinityChange(pParse, r3, 1);
76122              sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
76123            }
76124          }
76125        }
76126        sqlite3ReleaseTempReg(pParse, r1);
76127        sqlite3ReleaseTempReg(pParse, r2);
76128      }
76129      if( !isRowid ){
76130        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
76131      }
76132      break;
76133    }
76134
76135    case TK_EXISTS:
76136    case TK_SELECT:
76137    default: {
76138      /* If this has to be a scalar SELECT.  Generate code to put the
76139      ** value of this select in a memory cell and record the number
76140      ** of the memory cell in iColumn.  If this is an EXISTS, write
76141      ** an integer 0 (not exists) or 1 (exists) into a memory cell
76142      ** and record that memory cell in iColumn.
76143      */
76144      Select *pSel;                         /* SELECT statement to encode */
76145      SelectDest dest;                      /* How to deal with SELECt result */
76146
76147      testcase( pExpr->op==TK_EXISTS );
76148      testcase( pExpr->op==TK_SELECT );
76149      assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
76150
76151      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
76152      pSel = pExpr->x.pSelect;
76153      sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
76154      if( pExpr->op==TK_SELECT ){
76155        dest.eDest = SRT_Mem;
76156        sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
76157        VdbeComment((v, "Init subquery result"));
76158      }else{
76159        dest.eDest = SRT_Exists;
76160        sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
76161        VdbeComment((v, "Init EXISTS result"));
76162      }
76163      sqlite3ExprDelete(pParse->db, pSel->pLimit);
76164      pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
76165                                  &sqlite3IntTokens[1]);
76166      pSel->iLimit = 0;
76167      if( sqlite3Select(pParse, pSel, &dest) ){
76168        return 0;
76169      }
76170      rReg = dest.iParm;
76171      ExprSetIrreducible(pExpr);
76172      break;
76173    }
76174  }
76175
76176  if( testAddr>=0 ){
76177    sqlite3VdbeJumpHere(v, testAddr);
76178  }
76179  sqlite3ExprCachePop(pParse, 1);
76180
76181  return rReg;
76182}
76183#endif /* SQLITE_OMIT_SUBQUERY */
76184
76185#ifndef SQLITE_OMIT_SUBQUERY
76186/*
76187** Generate code for an IN expression.
76188**
76189**      x IN (SELECT ...)
76190**      x IN (value, value, ...)
76191**
76192** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
76193** is an array of zero or more values.  The expression is true if the LHS is
76194** contained within the RHS.  The value of the expression is unknown (NULL)
76195** if the LHS is NULL or if the LHS is not contained within the RHS and the
76196** RHS contains one or more NULL values.
76197**
76198** This routine generates code will jump to destIfFalse if the LHS is not
76199** contained within the RHS.  If due to NULLs we cannot determine if the LHS
76200** is contained in the RHS then jump to destIfNull.  If the LHS is contained
76201** within the RHS then fall through.
76202*/
76203static void sqlite3ExprCodeIN(
76204  Parse *pParse,        /* Parsing and code generating context */
76205  Expr *pExpr,          /* The IN expression */
76206  int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
76207  int destIfNull        /* Jump here if the results are unknown due to NULLs */
76208){
76209  int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
76210  char affinity;        /* Comparison affinity to use */
76211  int eType;            /* Type of the RHS */
76212  int r1;               /* Temporary use register */
76213  Vdbe *v;              /* Statement under construction */
76214
76215  /* Compute the RHS.   After this step, the table with cursor
76216  ** pExpr->iTable will contains the values that make up the RHS.
76217  */
76218  v = pParse->pVdbe;
76219  assert( v!=0 );       /* OOM detected prior to this routine */
76220  VdbeNoopComment((v, "begin IN expr"));
76221  eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
76222
76223  /* Figure out the affinity to use to create a key from the results
76224  ** of the expression. affinityStr stores a static string suitable for
76225  ** P4 of OP_MakeRecord.
76226  */
76227  affinity = comparisonAffinity(pExpr);
76228
76229  /* Code the LHS, the <expr> from "<expr> IN (...)".
76230  */
76231  sqlite3ExprCachePush(pParse);
76232  r1 = sqlite3GetTempReg(pParse);
76233  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
76234
76235  /* If the LHS is NULL, then the result is either false or NULL depending
76236  ** on whether the RHS is empty or not, respectively.
76237  */
76238  if( destIfNull==destIfFalse ){
76239    /* Shortcut for the common case where the false and NULL outcomes are
76240    ** the same. */
76241    sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
76242  }else{
76243    int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
76244    sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
76245    sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
76246    sqlite3VdbeJumpHere(v, addr1);
76247  }
76248
76249  if( eType==IN_INDEX_ROWID ){
76250    /* In this case, the RHS is the ROWID of table b-tree
76251    */
76252    sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
76253    sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
76254  }else{
76255    /* In this case, the RHS is an index b-tree.
76256    */
76257    sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
76258
76259    /* If the set membership test fails, then the result of the
76260    ** "x IN (...)" expression must be either 0 or NULL. If the set
76261    ** contains no NULL values, then the result is 0. If the set
76262    ** contains one or more NULL values, then the result of the
76263    ** expression is also NULL.
76264    */
76265    if( rRhsHasNull==0 || destIfFalse==destIfNull ){
76266      /* This branch runs if it is known at compile time that the RHS
76267      ** cannot contain NULL values. This happens as the result
76268      ** of a "NOT NULL" constraint in the database schema.
76269      **
76270      ** Also run this branch if NULL is equivalent to FALSE
76271      ** for this particular IN operator.
76272      */
76273      sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
76274
76275    }else{
76276      /* In this branch, the RHS of the IN might contain a NULL and
76277      ** the presence of a NULL on the RHS makes a difference in the
76278      ** outcome.
76279      */
76280      int j1, j2, j3;
76281
76282      /* First check to see if the LHS is contained in the RHS.  If so,
76283      ** then the presence of NULLs in the RHS does not matter, so jump
76284      ** over all of the code that follows.
76285      */
76286      j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
76287
76288      /* Here we begin generating code that runs if the LHS is not
76289      ** contained within the RHS.  Generate additional code that
76290      ** tests the RHS for NULLs.  If the RHS contains a NULL then
76291      ** jump to destIfNull.  If there are no NULLs in the RHS then
76292      ** jump to destIfFalse.
76293      */
76294      j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
76295      j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
76296      sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
76297      sqlite3VdbeJumpHere(v, j3);
76298      sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
76299      sqlite3VdbeJumpHere(v, j2);
76300
76301      /* Jump to the appropriate target depending on whether or not
76302      ** the RHS contains a NULL
76303      */
76304      sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
76305      sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
76306
76307      /* The OP_Found at the top of this branch jumps here when true,
76308      ** causing the overall IN expression evaluation to fall through.
76309      */
76310      sqlite3VdbeJumpHere(v, j1);
76311    }
76312  }
76313  sqlite3ReleaseTempReg(pParse, r1);
76314  sqlite3ExprCachePop(pParse, 1);
76315  VdbeComment((v, "end IN expr"));
76316}
76317#endif /* SQLITE_OMIT_SUBQUERY */
76318
76319/*
76320** Duplicate an 8-byte value
76321*/
76322static char *dup8bytes(Vdbe *v, const char *in){
76323  char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
76324  if( out ){
76325    memcpy(out, in, 8);
76326  }
76327  return out;
76328}
76329
76330#ifndef SQLITE_OMIT_FLOATING_POINT
76331/*
76332** Generate an instruction that will put the floating point
76333** value described by z[0..n-1] into register iMem.
76334**
76335** The z[] string will probably not be zero-terminated.  But the
76336** z[n] character is guaranteed to be something that does not look
76337** like the continuation of the number.
76338*/
76339static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
76340  if( ALWAYS(z!=0) ){
76341    double value;
76342    char *zV;
76343    sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
76344    assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
76345    if( negateFlag ) value = -value;
76346    zV = dup8bytes(v, (char*)&value);
76347    sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
76348  }
76349}
76350#endif
76351
76352
76353/*
76354** Generate an instruction that will put the integer describe by
76355** text z[0..n-1] into register iMem.
76356**
76357** Expr.u.zToken is always UTF8 and zero-terminated.
76358*/
76359static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
76360  Vdbe *v = pParse->pVdbe;
76361  if( pExpr->flags & EP_IntValue ){
76362    int i = pExpr->u.iValue;
76363    assert( i>=0 );
76364    if( negFlag ) i = -i;
76365    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
76366  }else{
76367    int c;
76368    i64 value;
76369    const char *z = pExpr->u.zToken;
76370    assert( z!=0 );
76371    c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
76372    if( c==0 || (c==2 && negFlag) ){
76373      char *zV;
76374      if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
76375      zV = dup8bytes(v, (char*)&value);
76376      sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
76377    }else{
76378#ifdef SQLITE_OMIT_FLOATING_POINT
76379      sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
76380#else
76381      codeReal(v, z, negFlag, iMem);
76382#endif
76383    }
76384  }
76385}
76386
76387/*
76388** Clear a cache entry.
76389*/
76390static void cacheEntryClear(Parse *pParse, struct yColCache *p){
76391  if( p->tempReg ){
76392    if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
76393      pParse->aTempReg[pParse->nTempReg++] = p->iReg;
76394    }
76395    p->tempReg = 0;
76396  }
76397}
76398
76399
76400/*
76401** Record in the column cache that a particular column from a
76402** particular table is stored in a particular register.
76403*/
76404SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
76405  int i;
76406  int minLru;
76407  int idxLru;
76408  struct yColCache *p;
76409
76410  assert( iReg>0 );  /* Register numbers are always positive */
76411  assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
76412
76413  /* The SQLITE_ColumnCache flag disables the column cache.  This is used
76414  ** for testing only - to verify that SQLite always gets the same answer
76415  ** with and without the column cache.
76416  */
76417  if( pParse->db->flags & SQLITE_ColumnCache ) return;
76418
76419  /* First replace any existing entry.
76420  **
76421  ** Actually, the way the column cache is currently used, we are guaranteed
76422  ** that the object will never already be in cache.  Verify this guarantee.
76423  */
76424#ifndef NDEBUG
76425  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76426#if 0 /* This code wold remove the entry from the cache if it existed */
76427    if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
76428      cacheEntryClear(pParse, p);
76429      p->iLevel = pParse->iCacheLevel;
76430      p->iReg = iReg;
76431      p->lru = pParse->iCacheCnt++;
76432      return;
76433    }
76434#endif
76435    assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
76436  }
76437#endif
76438
76439  /* Find an empty slot and replace it */
76440  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76441    if( p->iReg==0 ){
76442      p->iLevel = pParse->iCacheLevel;
76443      p->iTable = iTab;
76444      p->iColumn = iCol;
76445      p->iReg = iReg;
76446      p->tempReg = 0;
76447      p->lru = pParse->iCacheCnt++;
76448      return;
76449    }
76450  }
76451
76452  /* Replace the last recently used */
76453  minLru = 0x7fffffff;
76454  idxLru = -1;
76455  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76456    if( p->lru<minLru ){
76457      idxLru = i;
76458      minLru = p->lru;
76459    }
76460  }
76461  if( ALWAYS(idxLru>=0) ){
76462    p = &pParse->aColCache[idxLru];
76463    p->iLevel = pParse->iCacheLevel;
76464    p->iTable = iTab;
76465    p->iColumn = iCol;
76466    p->iReg = iReg;
76467    p->tempReg = 0;
76468    p->lru = pParse->iCacheCnt++;
76469    return;
76470  }
76471}
76472
76473/*
76474** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
76475** Purge the range of registers from the column cache.
76476*/
76477SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
76478  int i;
76479  int iLast = iReg + nReg - 1;
76480  struct yColCache *p;
76481  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76482    int r = p->iReg;
76483    if( r>=iReg && r<=iLast ){
76484      cacheEntryClear(pParse, p);
76485      p->iReg = 0;
76486    }
76487  }
76488}
76489
76490/*
76491** Remember the current column cache context.  Any new entries added
76492** added to the column cache after this call are removed when the
76493** corresponding pop occurs.
76494*/
76495SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
76496  pParse->iCacheLevel++;
76497}
76498
76499/*
76500** Remove from the column cache any entries that were added since the
76501** the previous N Push operations.  In other words, restore the cache
76502** to the state it was in N Pushes ago.
76503*/
76504SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
76505  int i;
76506  struct yColCache *p;
76507  assert( N>0 );
76508  assert( pParse->iCacheLevel>=N );
76509  pParse->iCacheLevel -= N;
76510  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76511    if( p->iReg && p->iLevel>pParse->iCacheLevel ){
76512      cacheEntryClear(pParse, p);
76513      p->iReg = 0;
76514    }
76515  }
76516}
76517
76518/*
76519** When a cached column is reused, make sure that its register is
76520** no longer available as a temp register.  ticket #3879:  that same
76521** register might be in the cache in multiple places, so be sure to
76522** get them all.
76523*/
76524static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
76525  int i;
76526  struct yColCache *p;
76527  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76528    if( p->iReg==iReg ){
76529      p->tempReg = 0;
76530    }
76531  }
76532}
76533
76534/*
76535** Generate code to extract the value of the iCol-th column of a table.
76536*/
76537SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
76538  Vdbe *v,        /* The VDBE under construction */
76539  Table *pTab,    /* The table containing the value */
76540  int iTabCur,    /* The cursor for this table */
76541  int iCol,       /* Index of the column to extract */
76542  int regOut      /* Extract the valud into this register */
76543){
76544  if( iCol<0 || iCol==pTab->iPKey ){
76545    sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
76546  }else{
76547    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
76548    sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
76549  }
76550  if( iCol>=0 ){
76551    sqlite3ColumnDefault(v, pTab, iCol, regOut);
76552  }
76553}
76554
76555/*
76556** Generate code that will extract the iColumn-th column from
76557** table pTab and store the column value in a register.  An effort
76558** is made to store the column value in register iReg, but this is
76559** not guaranteed.  The location of the column value is returned.
76560**
76561** There must be an open cursor to pTab in iTable when this routine
76562** is called.  If iColumn<0 then code is generated that extracts the rowid.
76563*/
76564SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
76565  Parse *pParse,   /* Parsing and code generating context */
76566  Table *pTab,     /* Description of the table we are reading from */
76567  int iColumn,     /* Index of the table column */
76568  int iTable,      /* The cursor pointing to the table */
76569  int iReg         /* Store results here */
76570){
76571  Vdbe *v = pParse->pVdbe;
76572  int i;
76573  struct yColCache *p;
76574
76575  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76576    if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
76577      p->lru = pParse->iCacheCnt++;
76578      sqlite3ExprCachePinRegister(pParse, p->iReg);
76579      return p->iReg;
76580    }
76581  }
76582  assert( v!=0 );
76583  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
76584  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
76585  return iReg;
76586}
76587
76588/*
76589** Clear all column cache entries.
76590*/
76591SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
76592  int i;
76593  struct yColCache *p;
76594
76595  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76596    if( p->iReg ){
76597      cacheEntryClear(pParse, p);
76598      p->iReg = 0;
76599    }
76600  }
76601}
76602
76603/*
76604** Record the fact that an affinity change has occurred on iCount
76605** registers starting with iStart.
76606*/
76607SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
76608  sqlite3ExprCacheRemove(pParse, iStart, iCount);
76609}
76610
76611/*
76612** Generate code to move content from registers iFrom...iFrom+nReg-1
76613** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
76614*/
76615SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
76616  int i;
76617  struct yColCache *p;
76618  if( NEVER(iFrom==iTo) ) return;
76619  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
76620  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76621    int x = p->iReg;
76622    if( x>=iFrom && x<iFrom+nReg ){
76623      p->iReg += iTo-iFrom;
76624    }
76625  }
76626}
76627
76628/*
76629** Generate code to copy content from registers iFrom...iFrom+nReg-1
76630** over to iTo..iTo+nReg-1.
76631*/
76632SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
76633  int i;
76634  if( NEVER(iFrom==iTo) ) return;
76635  for(i=0; i<nReg; i++){
76636    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
76637  }
76638}
76639
76640#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
76641/*
76642** Return true if any register in the range iFrom..iTo (inclusive)
76643** is used as part of the column cache.
76644**
76645** This routine is used within assert() and testcase() macros only
76646** and does not appear in a normal build.
76647*/
76648static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
76649  int i;
76650  struct yColCache *p;
76651  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
76652    int r = p->iReg;
76653    if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
76654  }
76655  return 0;
76656}
76657#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
76658
76659/*
76660** Generate code into the current Vdbe to evaluate the given
76661** expression.  Attempt to store the results in register "target".
76662** Return the register where results are stored.
76663**
76664** With this routine, there is no guarantee that results will
76665** be stored in target.  The result might be stored in some other
76666** register if it is convenient to do so.  The calling function
76667** must check the return code and move the results to the desired
76668** register.
76669*/
76670SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
76671  Vdbe *v = pParse->pVdbe;  /* The VM under construction */
76672  int op;                   /* The opcode being coded */
76673  int inReg = target;       /* Results stored in register inReg */
76674  int regFree1 = 0;         /* If non-zero free this temporary register */
76675  int regFree2 = 0;         /* If non-zero free this temporary register */
76676  int r1, r2, r3, r4;       /* Various register numbers */
76677  sqlite3 *db = pParse->db; /* The database connection */
76678
76679  assert( target>0 && target<=pParse->nMem );
76680  if( v==0 ){
76681    assert( pParse->db->mallocFailed );
76682    return 0;
76683  }
76684
76685  if( pExpr==0 ){
76686    op = TK_NULL;
76687  }else{
76688    op = pExpr->op;
76689  }
76690  switch( op ){
76691    case TK_AGG_COLUMN: {
76692      AggInfo *pAggInfo = pExpr->pAggInfo;
76693      struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
76694      if( !pAggInfo->directMode ){
76695        assert( pCol->iMem>0 );
76696        inReg = pCol->iMem;
76697        break;
76698      }else if( pAggInfo->useSortingIdx ){
76699        sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
76700                              pCol->iSorterColumn, target);
76701        break;
76702      }
76703      /* Otherwise, fall thru into the TK_COLUMN case */
76704    }
76705    case TK_COLUMN: {
76706      if( pExpr->iTable<0 ){
76707        /* This only happens when coding check constraints */
76708        assert( pParse->ckBase>0 );
76709        inReg = pExpr->iColumn + pParse->ckBase;
76710      }else{
76711        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
76712                                 pExpr->iColumn, pExpr->iTable, target);
76713      }
76714      break;
76715    }
76716    case TK_INTEGER: {
76717      codeInteger(pParse, pExpr, 0, target);
76718      break;
76719    }
76720#ifndef SQLITE_OMIT_FLOATING_POINT
76721    case TK_FLOAT: {
76722      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76723      codeReal(v, pExpr->u.zToken, 0, target);
76724      break;
76725    }
76726#endif
76727    case TK_STRING: {
76728      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76729      sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
76730      break;
76731    }
76732    case TK_NULL: {
76733      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
76734      break;
76735    }
76736#ifndef SQLITE_OMIT_BLOB_LITERAL
76737    case TK_BLOB: {
76738      int n;
76739      const char *z;
76740      char *zBlob;
76741      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76742      assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
76743      assert( pExpr->u.zToken[1]=='\'' );
76744      z = &pExpr->u.zToken[2];
76745      n = sqlite3Strlen30(z) - 1;
76746      assert( z[n]=='\'' );
76747      zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
76748      sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
76749      break;
76750    }
76751#endif
76752    case TK_VARIABLE: {
76753      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76754      assert( pExpr->u.zToken!=0 );
76755      assert( pExpr->u.zToken[0]!=0 );
76756      sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
76757      if( pExpr->u.zToken[1]!=0 ){
76758        assert( pExpr->u.zToken[0]=='?'
76759             || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
76760        sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
76761      }
76762      break;
76763    }
76764    case TK_REGISTER: {
76765      inReg = pExpr->iTable;
76766      break;
76767    }
76768    case TK_AS: {
76769      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76770      break;
76771    }
76772#ifndef SQLITE_OMIT_CAST
76773    case TK_CAST: {
76774      /* Expressions of the form:   CAST(pLeft AS token) */
76775      int aff, to_op;
76776      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
76777      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76778      aff = sqlite3AffinityType(pExpr->u.zToken);
76779      to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
76780      assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
76781      assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
76782      assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
76783      assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
76784      assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
76785      testcase( to_op==OP_ToText );
76786      testcase( to_op==OP_ToBlob );
76787      testcase( to_op==OP_ToNumeric );
76788      testcase( to_op==OP_ToInt );
76789      testcase( to_op==OP_ToReal );
76790      if( inReg!=target ){
76791        sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
76792        inReg = target;
76793      }
76794      sqlite3VdbeAddOp1(v, to_op, inReg);
76795      testcase( usedAsColumnCache(pParse, inReg, inReg) );
76796      sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
76797      break;
76798    }
76799#endif /* SQLITE_OMIT_CAST */
76800    case TK_LT:
76801    case TK_LE:
76802    case TK_GT:
76803    case TK_GE:
76804    case TK_NE:
76805    case TK_EQ: {
76806      assert( TK_LT==OP_Lt );
76807      assert( TK_LE==OP_Le );
76808      assert( TK_GT==OP_Gt );
76809      assert( TK_GE==OP_Ge );
76810      assert( TK_EQ==OP_Eq );
76811      assert( TK_NE==OP_Ne );
76812      testcase( op==TK_LT );
76813      testcase( op==TK_LE );
76814      testcase( op==TK_GT );
76815      testcase( op==TK_GE );
76816      testcase( op==TK_EQ );
76817      testcase( op==TK_NE );
76818      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76819      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76820      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76821                  r1, r2, inReg, SQLITE_STOREP2);
76822      testcase( regFree1==0 );
76823      testcase( regFree2==0 );
76824      break;
76825    }
76826    case TK_IS:
76827    case TK_ISNOT: {
76828      testcase( op==TK_IS );
76829      testcase( op==TK_ISNOT );
76830      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76831      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76832      op = (op==TK_IS) ? TK_EQ : TK_NE;
76833      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
76834                  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
76835      testcase( regFree1==0 );
76836      testcase( regFree2==0 );
76837      break;
76838    }
76839    case TK_AND:
76840    case TK_OR:
76841    case TK_PLUS:
76842    case TK_STAR:
76843    case TK_MINUS:
76844    case TK_REM:
76845    case TK_BITAND:
76846    case TK_BITOR:
76847    case TK_SLASH:
76848    case TK_LSHIFT:
76849    case TK_RSHIFT:
76850    case TK_CONCAT: {
76851      assert( TK_AND==OP_And );
76852      assert( TK_OR==OP_Or );
76853      assert( TK_PLUS==OP_Add );
76854      assert( TK_MINUS==OP_Subtract );
76855      assert( TK_REM==OP_Remainder );
76856      assert( TK_BITAND==OP_BitAnd );
76857      assert( TK_BITOR==OP_BitOr );
76858      assert( TK_SLASH==OP_Divide );
76859      assert( TK_LSHIFT==OP_ShiftLeft );
76860      assert( TK_RSHIFT==OP_ShiftRight );
76861      assert( TK_CONCAT==OP_Concat );
76862      testcase( op==TK_AND );
76863      testcase( op==TK_OR );
76864      testcase( op==TK_PLUS );
76865      testcase( op==TK_MINUS );
76866      testcase( op==TK_REM );
76867      testcase( op==TK_BITAND );
76868      testcase( op==TK_BITOR );
76869      testcase( op==TK_SLASH );
76870      testcase( op==TK_LSHIFT );
76871      testcase( op==TK_RSHIFT );
76872      testcase( op==TK_CONCAT );
76873      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76874      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
76875      sqlite3VdbeAddOp3(v, op, r2, r1, target);
76876      testcase( regFree1==0 );
76877      testcase( regFree2==0 );
76878      break;
76879    }
76880    case TK_UMINUS: {
76881      Expr *pLeft = pExpr->pLeft;
76882      assert( pLeft );
76883      if( pLeft->op==TK_INTEGER ){
76884        codeInteger(pParse, pLeft, 1, target);
76885#ifndef SQLITE_OMIT_FLOATING_POINT
76886      }else if( pLeft->op==TK_FLOAT ){
76887        assert( !ExprHasProperty(pExpr, EP_IntValue) );
76888        codeReal(v, pLeft->u.zToken, 1, target);
76889#endif
76890      }else{
76891        regFree1 = r1 = sqlite3GetTempReg(pParse);
76892        sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
76893        r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
76894        sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
76895        testcase( regFree2==0 );
76896      }
76897      inReg = target;
76898      break;
76899    }
76900    case TK_BITNOT:
76901    case TK_NOT: {
76902      assert( TK_BITNOT==OP_BitNot );
76903      assert( TK_NOT==OP_Not );
76904      testcase( op==TK_BITNOT );
76905      testcase( op==TK_NOT );
76906      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76907      testcase( regFree1==0 );
76908      inReg = target;
76909      sqlite3VdbeAddOp2(v, op, r1, inReg);
76910      break;
76911    }
76912    case TK_ISNULL:
76913    case TK_NOTNULL: {
76914      int addr;
76915      assert( TK_ISNULL==OP_IsNull );
76916      assert( TK_NOTNULL==OP_NotNull );
76917      testcase( op==TK_ISNULL );
76918      testcase( op==TK_NOTNULL );
76919      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
76920      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
76921      testcase( regFree1==0 );
76922      addr = sqlite3VdbeAddOp1(v, op, r1);
76923      sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
76924      sqlite3VdbeJumpHere(v, addr);
76925      break;
76926    }
76927    case TK_AGG_FUNCTION: {
76928      AggInfo *pInfo = pExpr->pAggInfo;
76929      if( pInfo==0 ){
76930        assert( !ExprHasProperty(pExpr, EP_IntValue) );
76931        sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
76932      }else{
76933        inReg = pInfo->aFunc[pExpr->iAgg].iMem;
76934      }
76935      break;
76936    }
76937    case TK_CONST_FUNC:
76938    case TK_FUNCTION: {
76939      ExprList *pFarg;       /* List of function arguments */
76940      int nFarg;             /* Number of function arguments */
76941      FuncDef *pDef;         /* The function definition object */
76942      int nId;               /* Length of the function name in bytes */
76943      const char *zId;       /* The function name */
76944      int constMask = 0;     /* Mask of function arguments that are constant */
76945      int i;                 /* Loop counter */
76946      u8 enc = ENC(db);      /* The text encoding used by this database */
76947      CollSeq *pColl = 0;    /* A collating sequence */
76948
76949      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
76950      testcase( op==TK_CONST_FUNC );
76951      testcase( op==TK_FUNCTION );
76952      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
76953        pFarg = 0;
76954      }else{
76955        pFarg = pExpr->x.pList;
76956      }
76957      nFarg = pFarg ? pFarg->nExpr : 0;
76958      assert( !ExprHasProperty(pExpr, EP_IntValue) );
76959      zId = pExpr->u.zToken;
76960      nId = sqlite3Strlen30(zId);
76961      pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
76962      if( pDef==0 ){
76963        sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
76964        break;
76965      }
76966
76967      /* Attempt a direct implementation of the built-in COALESCE() and
76968      ** IFNULL() functions.  This avoids unnecessary evalation of
76969      ** arguments past the first non-NULL argument.
76970      */
76971      if( pDef->flags & SQLITE_FUNC_COALESCE ){
76972        int endCoalesce = sqlite3VdbeMakeLabel(v);
76973        assert( nFarg>=2 );
76974        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
76975        for(i=1; i<nFarg; i++){
76976          sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
76977          sqlite3ExprCacheRemove(pParse, target, 1);
76978          sqlite3ExprCachePush(pParse);
76979          sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
76980          sqlite3ExprCachePop(pParse, 1);
76981        }
76982        sqlite3VdbeResolveLabel(v, endCoalesce);
76983        break;
76984      }
76985
76986
76987      if( pFarg ){
76988        r1 = sqlite3GetTempRange(pParse, nFarg);
76989        sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
76990        sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
76991        sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
76992      }else{
76993        r1 = 0;
76994      }
76995#ifndef SQLITE_OMIT_VIRTUALTABLE
76996      /* Possibly overload the function if the first argument is
76997      ** a virtual table column.
76998      **
76999      ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
77000      ** second argument, not the first, as the argument to test to
77001      ** see if it is a column in a virtual table.  This is done because
77002      ** the left operand of infix functions (the operand we want to
77003      ** control overloading) ends up as the second argument to the
77004      ** function.  The expression "A glob B" is equivalent to
77005      ** "glob(B,A).  We want to use the A in "A glob B" to test
77006      ** for function overloading.  But we use the B term in "glob(B,A)".
77007      */
77008      if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
77009        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
77010      }else if( nFarg>0 ){
77011        pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
77012      }
77013#endif
77014      for(i=0; i<nFarg; i++){
77015        if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
77016          constMask |= (1<<i);
77017        }
77018        if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
77019          pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
77020        }
77021      }
77022      if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
77023        if( !pColl ) pColl = db->pDfltColl;
77024        sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
77025      }
77026      sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
77027                        (char*)pDef, P4_FUNCDEF);
77028      sqlite3VdbeChangeP5(v, (u8)nFarg);
77029      if( nFarg ){
77030        sqlite3ReleaseTempRange(pParse, r1, nFarg);
77031      }
77032      break;
77033    }
77034#ifndef SQLITE_OMIT_SUBQUERY
77035    case TK_EXISTS:
77036    case TK_SELECT: {
77037      testcase( op==TK_EXISTS );
77038      testcase( op==TK_SELECT );
77039      inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
77040      break;
77041    }
77042    case TK_IN: {
77043      int destIfFalse = sqlite3VdbeMakeLabel(v);
77044      int destIfNull = sqlite3VdbeMakeLabel(v);
77045      sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77046      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77047      sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
77048      sqlite3VdbeResolveLabel(v, destIfFalse);
77049      sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
77050      sqlite3VdbeResolveLabel(v, destIfNull);
77051      break;
77052    }
77053#endif /* SQLITE_OMIT_SUBQUERY */
77054
77055
77056    /*
77057    **    x BETWEEN y AND z
77058    **
77059    ** This is equivalent to
77060    **
77061    **    x>=y AND x<=z
77062    **
77063    ** X is stored in pExpr->pLeft.
77064    ** Y is stored in pExpr->pList->a[0].pExpr.
77065    ** Z is stored in pExpr->pList->a[1].pExpr.
77066    */
77067    case TK_BETWEEN: {
77068      Expr *pLeft = pExpr->pLeft;
77069      struct ExprList_item *pLItem = pExpr->x.pList->a;
77070      Expr *pRight = pLItem->pExpr;
77071
77072      r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
77073      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
77074      testcase( regFree1==0 );
77075      testcase( regFree2==0 );
77076      r3 = sqlite3GetTempReg(pParse);
77077      r4 = sqlite3GetTempReg(pParse);
77078      codeCompare(pParse, pLeft, pRight, OP_Ge,
77079                  r1, r2, r3, SQLITE_STOREP2);
77080      pLItem++;
77081      pRight = pLItem->pExpr;
77082      sqlite3ReleaseTempReg(pParse, regFree2);
77083      r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
77084      testcase( regFree2==0 );
77085      codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
77086      sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
77087      sqlite3ReleaseTempReg(pParse, r3);
77088      sqlite3ReleaseTempReg(pParse, r4);
77089      break;
77090    }
77091    case TK_UPLUS: {
77092      inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77093      break;
77094    }
77095
77096    case TK_TRIGGER: {
77097      /* If the opcode is TK_TRIGGER, then the expression is a reference
77098      ** to a column in the new.* or old.* pseudo-tables available to
77099      ** trigger programs. In this case Expr.iTable is set to 1 for the
77100      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
77101      ** is set to the column of the pseudo-table to read, or to -1 to
77102      ** read the rowid field.
77103      **
77104      ** The expression is implemented using an OP_Param opcode. The p1
77105      ** parameter is set to 0 for an old.rowid reference, or to (i+1)
77106      ** to reference another column of the old.* pseudo-table, where
77107      ** i is the index of the column. For a new.rowid reference, p1 is
77108      ** set to (n+1), where n is the number of columns in each pseudo-table.
77109      ** For a reference to any other column in the new.* pseudo-table, p1
77110      ** is set to (n+2+i), where n and i are as defined previously. For
77111      ** example, if the table on which triggers are being fired is
77112      ** declared as:
77113      **
77114      **   CREATE TABLE t1(a, b);
77115      **
77116      ** Then p1 is interpreted as follows:
77117      **
77118      **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
77119      **   p1==1   ->    old.a         p1==4   ->    new.a
77120      **   p1==2   ->    old.b         p1==5   ->    new.b
77121      */
77122      Table *pTab = pExpr->pTab;
77123      int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
77124
77125      assert( pExpr->iTable==0 || pExpr->iTable==1 );
77126      assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
77127      assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
77128      assert( p1>=0 && p1<(pTab->nCol*2+2) );
77129
77130      sqlite3VdbeAddOp2(v, OP_Param, p1, target);
77131      VdbeComment((v, "%s.%s -> $%d",
77132        (pExpr->iTable ? "new" : "old"),
77133        (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
77134        target
77135      ));
77136
77137#ifndef SQLITE_OMIT_FLOATING_POINT
77138      /* If the column has REAL affinity, it may currently be stored as an
77139      ** integer. Use OP_RealAffinity to make sure it is really real.  */
77140      if( pExpr->iColumn>=0
77141       && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
77142      ){
77143        sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
77144      }
77145#endif
77146      break;
77147    }
77148
77149
77150    /*
77151    ** Form A:
77152    **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
77153    **
77154    ** Form B:
77155    **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
77156    **
77157    ** Form A is can be transformed into the equivalent form B as follows:
77158    **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
77159    **        WHEN x=eN THEN rN ELSE y END
77160    **
77161    ** X (if it exists) is in pExpr->pLeft.
77162    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
77163    ** ELSE clause and no other term matches, then the result of the
77164    ** exprssion is NULL.
77165    ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
77166    **
77167    ** The result of the expression is the Ri for the first matching Ei,
77168    ** or if there is no matching Ei, the ELSE term Y, or if there is
77169    ** no ELSE term, NULL.
77170    */
77171    default: assert( op==TK_CASE ); {
77172      int endLabel;                     /* GOTO label for end of CASE stmt */
77173      int nextCase;                     /* GOTO label for next WHEN clause */
77174      int nExpr;                        /* 2x number of WHEN terms */
77175      int i;                            /* Loop counter */
77176      ExprList *pEList;                 /* List of WHEN terms */
77177      struct ExprList_item *aListelem;  /* Array of WHEN terms */
77178      Expr opCompare;                   /* The X==Ei expression */
77179      Expr cacheX;                      /* Cached expression X */
77180      Expr *pX;                         /* The X expression */
77181      Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
77182      VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
77183
77184      assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
77185      assert((pExpr->x.pList->nExpr % 2) == 0);
77186      assert(pExpr->x.pList->nExpr > 0);
77187      pEList = pExpr->x.pList;
77188      aListelem = pEList->a;
77189      nExpr = pEList->nExpr;
77190      endLabel = sqlite3VdbeMakeLabel(v);
77191      if( (pX = pExpr->pLeft)!=0 ){
77192        cacheX = *pX;
77193        testcase( pX->op==TK_COLUMN );
77194        testcase( pX->op==TK_REGISTER );
77195        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
77196        testcase( regFree1==0 );
77197        cacheX.op = TK_REGISTER;
77198        opCompare.op = TK_EQ;
77199        opCompare.pLeft = &cacheX;
77200        pTest = &opCompare;
77201        /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
77202        ** The value in regFree1 might get SCopy-ed into the file result.
77203        ** So make sure that the regFree1 register is not reused for other
77204        ** purposes and possibly overwritten.  */
77205        regFree1 = 0;
77206      }
77207      for(i=0; i<nExpr; i=i+2){
77208        sqlite3ExprCachePush(pParse);
77209        if( pX ){
77210          assert( pTest!=0 );
77211          opCompare.pRight = aListelem[i].pExpr;
77212        }else{
77213          pTest = aListelem[i].pExpr;
77214        }
77215        nextCase = sqlite3VdbeMakeLabel(v);
77216        testcase( pTest->op==TK_COLUMN );
77217        sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
77218        testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
77219        testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
77220        sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
77221        sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
77222        sqlite3ExprCachePop(pParse, 1);
77223        sqlite3VdbeResolveLabel(v, nextCase);
77224      }
77225      if( pExpr->pRight ){
77226        sqlite3ExprCachePush(pParse);
77227        sqlite3ExprCode(pParse, pExpr->pRight, target);
77228        sqlite3ExprCachePop(pParse, 1);
77229      }else{
77230        sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77231      }
77232      assert( db->mallocFailed || pParse->nErr>0
77233           || pParse->iCacheLevel==iCacheLevel );
77234      sqlite3VdbeResolveLabel(v, endLabel);
77235      break;
77236    }
77237#ifndef SQLITE_OMIT_TRIGGER
77238    case TK_RAISE: {
77239      assert( pExpr->affinity==OE_Rollback
77240           || pExpr->affinity==OE_Abort
77241           || pExpr->affinity==OE_Fail
77242           || pExpr->affinity==OE_Ignore
77243      );
77244      if( !pParse->pTriggerTab ){
77245        sqlite3ErrorMsg(pParse,
77246                       "RAISE() may only be used within a trigger-program");
77247        return 0;
77248      }
77249      if( pExpr->affinity==OE_Abort ){
77250        sqlite3MayAbort(pParse);
77251      }
77252      assert( !ExprHasProperty(pExpr, EP_IntValue) );
77253      if( pExpr->affinity==OE_Ignore ){
77254        sqlite3VdbeAddOp4(
77255            v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
77256      }else{
77257        sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
77258      }
77259
77260      break;
77261    }
77262#endif
77263  }
77264  sqlite3ReleaseTempReg(pParse, regFree1);
77265  sqlite3ReleaseTempReg(pParse, regFree2);
77266  return inReg;
77267}
77268
77269/*
77270** Generate code to evaluate an expression and store the results
77271** into a register.  Return the register number where the results
77272** are stored.
77273**
77274** If the register is a temporary register that can be deallocated,
77275** then write its number into *pReg.  If the result register is not
77276** a temporary, then set *pReg to zero.
77277*/
77278SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
77279  int r1 = sqlite3GetTempReg(pParse);
77280  int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
77281  if( r2==r1 ){
77282    *pReg = r1;
77283  }else{
77284    sqlite3ReleaseTempReg(pParse, r1);
77285    *pReg = 0;
77286  }
77287  return r2;
77288}
77289
77290/*
77291** Generate code that will evaluate expression pExpr and store the
77292** results in register target.  The results are guaranteed to appear
77293** in register target.
77294*/
77295SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
77296  int inReg;
77297
77298  assert( target>0 && target<=pParse->nMem );
77299  if( pExpr && pExpr->op==TK_REGISTER ){
77300    sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
77301  }else{
77302    inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
77303    assert( pParse->pVdbe || pParse->db->mallocFailed );
77304    if( inReg!=target && pParse->pVdbe ){
77305      sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
77306    }
77307  }
77308  return target;
77309}
77310
77311/*
77312** Generate code that evalutes the given expression and puts the result
77313** in register target.
77314**
77315** Also make a copy of the expression results into another "cache" register
77316** and modify the expression so that the next time it is evaluated,
77317** the result is a copy of the cache register.
77318**
77319** This routine is used for expressions that are used multiple
77320** times.  They are evaluated once and the results of the expression
77321** are reused.
77322*/
77323SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
77324  Vdbe *v = pParse->pVdbe;
77325  int inReg;
77326  inReg = sqlite3ExprCode(pParse, pExpr, target);
77327  assert( target>0 );
77328  /* This routine is called for terms to INSERT or UPDATE.  And the only
77329  ** other place where expressions can be converted into TK_REGISTER is
77330  ** in WHERE clause processing.  So as currently implemented, there is
77331  ** no way for a TK_REGISTER to exist here.  But it seems prudent to
77332  ** keep the ALWAYS() in case the conditions above change with future
77333  ** modifications or enhancements. */
77334  if( ALWAYS(pExpr->op!=TK_REGISTER) ){
77335    int iMem;
77336    iMem = ++pParse->nMem;
77337    sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
77338    pExpr->iTable = iMem;
77339    pExpr->op2 = pExpr->op;
77340    pExpr->op = TK_REGISTER;
77341  }
77342  return inReg;
77343}
77344
77345#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
77346/*
77347** Generate a human-readable explanation of an expression tree.
77348*/
77349SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
77350  int op;                   /* The opcode being coded */
77351  const char *zBinOp = 0;   /* Binary operator */
77352  const char *zUniOp = 0;   /* Unary operator */
77353  if( pExpr==0 ){
77354    op = TK_NULL;
77355  }else{
77356    op = pExpr->op;
77357  }
77358  switch( op ){
77359    case TK_AGG_COLUMN: {
77360      sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
77361            pExpr->iTable, pExpr->iColumn);
77362      break;
77363    }
77364    case TK_COLUMN: {
77365      if( pExpr->iTable<0 ){
77366        /* This only happens when coding check constraints */
77367        sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
77368      }else{
77369        sqlite3ExplainPrintf(pOut, "{%d:%d}",
77370                             pExpr->iTable, pExpr->iColumn);
77371      }
77372      break;
77373    }
77374    case TK_INTEGER: {
77375      if( pExpr->flags & EP_IntValue ){
77376        sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
77377      }else{
77378        sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
77379      }
77380      break;
77381    }
77382#ifndef SQLITE_OMIT_FLOATING_POINT
77383    case TK_FLOAT: {
77384      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
77385      break;
77386    }
77387#endif
77388    case TK_STRING: {
77389      sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
77390      break;
77391    }
77392    case TK_NULL: {
77393      sqlite3ExplainPrintf(pOut,"NULL");
77394      break;
77395    }
77396#ifndef SQLITE_OMIT_BLOB_LITERAL
77397    case TK_BLOB: {
77398      sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
77399      break;
77400    }
77401#endif
77402    case TK_VARIABLE: {
77403      sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
77404                           pExpr->u.zToken, pExpr->iColumn);
77405      break;
77406    }
77407    case TK_REGISTER: {
77408      sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
77409      break;
77410    }
77411    case TK_AS: {
77412      sqlite3ExplainExpr(pOut, pExpr->pLeft);
77413      break;
77414    }
77415#ifndef SQLITE_OMIT_CAST
77416    case TK_CAST: {
77417      /* Expressions of the form:   CAST(pLeft AS token) */
77418      const char *zAff = "unk";
77419      switch( sqlite3AffinityType(pExpr->u.zToken) ){
77420        case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
77421        case SQLITE_AFF_NONE:    zAff = "NONE";     break;
77422        case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
77423        case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
77424        case SQLITE_AFF_REAL:    zAff = "REAL";     break;
77425      }
77426      sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
77427      sqlite3ExplainExpr(pOut, pExpr->pLeft);
77428      sqlite3ExplainPrintf(pOut, ")");
77429      break;
77430    }
77431#endif /* SQLITE_OMIT_CAST */
77432    case TK_LT:      zBinOp = "LT";     break;
77433    case TK_LE:      zBinOp = "LE";     break;
77434    case TK_GT:      zBinOp = "GT";     break;
77435    case TK_GE:      zBinOp = "GE";     break;
77436    case TK_NE:      zBinOp = "NE";     break;
77437    case TK_EQ:      zBinOp = "EQ";     break;
77438    case TK_IS:      zBinOp = "IS";     break;
77439    case TK_ISNOT:   zBinOp = "ISNOT";  break;
77440    case TK_AND:     zBinOp = "AND";    break;
77441    case TK_OR:      zBinOp = "OR";     break;
77442    case TK_PLUS:    zBinOp = "ADD";    break;
77443    case TK_STAR:    zBinOp = "MUL";    break;
77444    case TK_MINUS:   zBinOp = "SUB";    break;
77445    case TK_REM:     zBinOp = "REM";    break;
77446    case TK_BITAND:  zBinOp = "BITAND"; break;
77447    case TK_BITOR:   zBinOp = "BITOR";  break;
77448    case TK_SLASH:   zBinOp = "DIV";    break;
77449    case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
77450    case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
77451    case TK_CONCAT:  zBinOp = "CONCAT"; break;
77452
77453    case TK_UMINUS:  zUniOp = "UMINUS"; break;
77454    case TK_UPLUS:   zUniOp = "UPLUS";  break;
77455    case TK_BITNOT:  zUniOp = "BITNOT"; break;
77456    case TK_NOT:     zUniOp = "NOT";    break;
77457    case TK_ISNULL:  zUniOp = "ISNULL"; break;
77458    case TK_NOTNULL: zUniOp = "NOTNULL"; break;
77459
77460    case TK_AGG_FUNCTION:
77461    case TK_CONST_FUNC:
77462    case TK_FUNCTION: {
77463      ExprList *pFarg;       /* List of function arguments */
77464      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
77465        pFarg = 0;
77466      }else{
77467        pFarg = pExpr->x.pList;
77468      }
77469      sqlite3ExplainPrintf(pOut, "%sFUNCTION:%s(",
77470                           op==TK_AGG_FUNCTION ? "AGG_" : "",
77471                           pExpr->u.zToken);
77472      if( pFarg ){
77473        sqlite3ExplainExprList(pOut, pFarg);
77474      }
77475      sqlite3ExplainPrintf(pOut, ")");
77476      break;
77477    }
77478#ifndef SQLITE_OMIT_SUBQUERY
77479    case TK_EXISTS: {
77480      sqlite3ExplainPrintf(pOut, "EXISTS(");
77481      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77482      sqlite3ExplainPrintf(pOut,")");
77483      break;
77484    }
77485    case TK_SELECT: {
77486      sqlite3ExplainPrintf(pOut, "(");
77487      sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77488      sqlite3ExplainPrintf(pOut, ")");
77489      break;
77490    }
77491    case TK_IN: {
77492      sqlite3ExplainPrintf(pOut, "IN(");
77493      sqlite3ExplainExpr(pOut, pExpr->pLeft);
77494      sqlite3ExplainPrintf(pOut, ",");
77495      if( ExprHasProperty(pExpr, EP_xIsSelect) ){
77496        sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
77497      }else{
77498        sqlite3ExplainExprList(pOut, pExpr->x.pList);
77499      }
77500      sqlite3ExplainPrintf(pOut, ")");
77501      break;
77502    }
77503#endif /* SQLITE_OMIT_SUBQUERY */
77504
77505    /*
77506    **    x BETWEEN y AND z
77507    **
77508    ** This is equivalent to
77509    **
77510    **    x>=y AND x<=z
77511    **
77512    ** X is stored in pExpr->pLeft.
77513    ** Y is stored in pExpr->pList->a[0].pExpr.
77514    ** Z is stored in pExpr->pList->a[1].pExpr.
77515    */
77516    case TK_BETWEEN: {
77517      Expr *pX = pExpr->pLeft;
77518      Expr *pY = pExpr->x.pList->a[0].pExpr;
77519      Expr *pZ = pExpr->x.pList->a[1].pExpr;
77520      sqlite3ExplainPrintf(pOut, "BETWEEN(");
77521      sqlite3ExplainExpr(pOut, pX);
77522      sqlite3ExplainPrintf(pOut, ",");
77523      sqlite3ExplainExpr(pOut, pY);
77524      sqlite3ExplainPrintf(pOut, ",");
77525      sqlite3ExplainExpr(pOut, pZ);
77526      sqlite3ExplainPrintf(pOut, ")");
77527      break;
77528    }
77529    case TK_TRIGGER: {
77530      /* If the opcode is TK_TRIGGER, then the expression is a reference
77531      ** to a column in the new.* or old.* pseudo-tables available to
77532      ** trigger programs. In this case Expr.iTable is set to 1 for the
77533      ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
77534      ** is set to the column of the pseudo-table to read, or to -1 to
77535      ** read the rowid field.
77536      */
77537      sqlite3ExplainPrintf(pOut, "%s(%d)",
77538          pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
77539      break;
77540    }
77541    case TK_CASE: {
77542      sqlite3ExplainPrintf(pOut, "CASE(");
77543      sqlite3ExplainExpr(pOut, pExpr->pLeft);
77544      sqlite3ExplainPrintf(pOut, ",");
77545      sqlite3ExplainExprList(pOut, pExpr->x.pList);
77546      break;
77547    }
77548#ifndef SQLITE_OMIT_TRIGGER
77549    case TK_RAISE: {
77550      const char *zType = "unk";
77551      switch( pExpr->affinity ){
77552        case OE_Rollback:   zType = "rollback";  break;
77553        case OE_Abort:      zType = "abort";     break;
77554        case OE_Fail:       zType = "fail";      break;
77555        case OE_Ignore:     zType = "ignore";    break;
77556      }
77557      sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
77558      break;
77559    }
77560#endif
77561  }
77562  if( zBinOp ){
77563    sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
77564    sqlite3ExplainExpr(pOut, pExpr->pLeft);
77565    sqlite3ExplainPrintf(pOut,",");
77566    sqlite3ExplainExpr(pOut, pExpr->pRight);
77567    sqlite3ExplainPrintf(pOut,")");
77568  }else if( zUniOp ){
77569    sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
77570    sqlite3ExplainExpr(pOut, pExpr->pLeft);
77571    sqlite3ExplainPrintf(pOut,")");
77572  }
77573}
77574#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
77575
77576#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
77577/*
77578** Generate a human-readable explanation of an expression list.
77579*/
77580SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
77581  int i;
77582  if( pList==0 || pList->nExpr==0 ){
77583    sqlite3ExplainPrintf(pOut, "(empty-list)");
77584    return;
77585  }else if( pList->nExpr==1 ){
77586    sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
77587  }else{
77588    sqlite3ExplainPush(pOut);
77589    for(i=0; i<pList->nExpr; i++){
77590      sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
77591      sqlite3ExplainPush(pOut);
77592      sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
77593      sqlite3ExplainPop(pOut);
77594      if( i<pList->nExpr-1 ){
77595        sqlite3ExplainNL(pOut);
77596      }
77597    }
77598    sqlite3ExplainPop(pOut);
77599  }
77600}
77601#endif /* SQLITE_DEBUG */
77602
77603/*
77604** Return TRUE if pExpr is an constant expression that is appropriate
77605** for factoring out of a loop.  Appropriate expressions are:
77606**
77607**    *  Any expression that evaluates to two or more opcodes.
77608**
77609**    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
77610**       or OP_Variable that does not need to be placed in a
77611**       specific register.
77612**
77613** There is no point in factoring out single-instruction constant
77614** expressions that need to be placed in a particular register.
77615** We could factor them out, but then we would end up adding an
77616** OP_SCopy instruction to move the value into the correct register
77617** later.  We might as well just use the original instruction and
77618** avoid the OP_SCopy.
77619*/
77620static int isAppropriateForFactoring(Expr *p){
77621  if( !sqlite3ExprIsConstantNotJoin(p) ){
77622    return 0;  /* Only constant expressions are appropriate for factoring */
77623  }
77624  if( (p->flags & EP_FixedDest)==0 ){
77625    return 1;  /* Any constant without a fixed destination is appropriate */
77626  }
77627  while( p->op==TK_UPLUS ) p = p->pLeft;
77628  switch( p->op ){
77629#ifndef SQLITE_OMIT_BLOB_LITERAL
77630    case TK_BLOB:
77631#endif
77632    case TK_VARIABLE:
77633    case TK_INTEGER:
77634    case TK_FLOAT:
77635    case TK_NULL:
77636    case TK_STRING: {
77637      testcase( p->op==TK_BLOB );
77638      testcase( p->op==TK_VARIABLE );
77639      testcase( p->op==TK_INTEGER );
77640      testcase( p->op==TK_FLOAT );
77641      testcase( p->op==TK_NULL );
77642      testcase( p->op==TK_STRING );
77643      /* Single-instruction constants with a fixed destination are
77644      ** better done in-line.  If we factor them, they will just end
77645      ** up generating an OP_SCopy to move the value to the destination
77646      ** register. */
77647      return 0;
77648    }
77649    case TK_UMINUS: {
77650      if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
77651        return 0;
77652      }
77653      break;
77654    }
77655    default: {
77656      break;
77657    }
77658  }
77659  return 1;
77660}
77661
77662/*
77663** If pExpr is a constant expression that is appropriate for
77664** factoring out of a loop, then evaluate the expression
77665** into a register and convert the expression into a TK_REGISTER
77666** expression.
77667*/
77668static int evalConstExpr(Walker *pWalker, Expr *pExpr){
77669  Parse *pParse = pWalker->pParse;
77670  switch( pExpr->op ){
77671    case TK_IN:
77672    case TK_REGISTER: {
77673      return WRC_Prune;
77674    }
77675    case TK_FUNCTION:
77676    case TK_AGG_FUNCTION:
77677    case TK_CONST_FUNC: {
77678      /* The arguments to a function have a fixed destination.
77679      ** Mark them this way to avoid generated unneeded OP_SCopy
77680      ** instructions.
77681      */
77682      ExprList *pList = pExpr->x.pList;
77683      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77684      if( pList ){
77685        int i = pList->nExpr;
77686        struct ExprList_item *pItem = pList->a;
77687        for(; i>0; i--, pItem++){
77688          if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
77689        }
77690      }
77691      break;
77692    }
77693  }
77694  if( isAppropriateForFactoring(pExpr) ){
77695    int r1 = ++pParse->nMem;
77696    int r2;
77697    r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
77698    if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
77699    pExpr->op2 = pExpr->op;
77700    pExpr->op = TK_REGISTER;
77701    pExpr->iTable = r2;
77702    return WRC_Prune;
77703  }
77704  return WRC_Continue;
77705}
77706
77707/*
77708** Preevaluate constant subexpressions within pExpr and store the
77709** results in registers.  Modify pExpr so that the constant subexpresions
77710** are TK_REGISTER opcodes that refer to the precomputed values.
77711**
77712** This routine is a no-op if the jump to the cookie-check code has
77713** already occur.  Since the cookie-check jump is generated prior to
77714** any other serious processing, this check ensures that there is no
77715** way to accidently bypass the constant initializations.
77716**
77717** This routine is also a no-op if the SQLITE_FactorOutConst optimization
77718** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
77719** interface.  This allows test logic to verify that the same answer is
77720** obtained for queries regardless of whether or not constants are
77721** precomputed into registers or if they are inserted in-line.
77722*/
77723SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
77724  Walker w;
77725  if( pParse->cookieGoto ) return;
77726  if( (pParse->db->flags & SQLITE_FactorOutConst)!=0 ) return;
77727  w.xExprCallback = evalConstExpr;
77728  w.xSelectCallback = 0;
77729  w.pParse = pParse;
77730  sqlite3WalkExpr(&w, pExpr);
77731}
77732
77733
77734/*
77735** Generate code that pushes the value of every element of the given
77736** expression list into a sequence of registers beginning at target.
77737**
77738** Return the number of elements evaluated.
77739*/
77740SQLITE_PRIVATE int sqlite3ExprCodeExprList(
77741  Parse *pParse,     /* Parsing context */
77742  ExprList *pList,   /* The expression list to be coded */
77743  int target,        /* Where to write results */
77744  int doHardCopy     /* Make a hard copy of every element */
77745){
77746  struct ExprList_item *pItem;
77747  int i, n;
77748  assert( pList!=0 );
77749  assert( target>0 );
77750  assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
77751  n = pList->nExpr;
77752  for(pItem=pList->a, i=0; i<n; i++, pItem++){
77753    Expr *pExpr = pItem->pExpr;
77754    int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
77755    if( inReg!=target+i ){
77756      sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
77757                        inReg, target+i);
77758    }
77759  }
77760  return n;
77761}
77762
77763/*
77764** Generate code for a BETWEEN operator.
77765**
77766**    x BETWEEN y AND z
77767**
77768** The above is equivalent to
77769**
77770**    x>=y AND x<=z
77771**
77772** Code it as such, taking care to do the common subexpression
77773** elementation of x.
77774*/
77775static void exprCodeBetween(
77776  Parse *pParse,    /* Parsing and code generating context */
77777  Expr *pExpr,      /* The BETWEEN expression */
77778  int dest,         /* Jump here if the jump is taken */
77779  int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
77780  int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
77781){
77782  Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
77783  Expr compLeft;    /* The  x>=y  term */
77784  Expr compRight;   /* The  x<=z  term */
77785  Expr exprX;       /* The  x  subexpression */
77786  int regFree1 = 0; /* Temporary use register */
77787
77788  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77789  exprX = *pExpr->pLeft;
77790  exprAnd.op = TK_AND;
77791  exprAnd.pLeft = &compLeft;
77792  exprAnd.pRight = &compRight;
77793  compLeft.op = TK_GE;
77794  compLeft.pLeft = &exprX;
77795  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
77796  compRight.op = TK_LE;
77797  compRight.pLeft = &exprX;
77798  compRight.pRight = pExpr->x.pList->a[1].pExpr;
77799  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
77800  exprX.op = TK_REGISTER;
77801  if( jumpIfTrue ){
77802    sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
77803  }else{
77804    sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
77805  }
77806  sqlite3ReleaseTempReg(pParse, regFree1);
77807
77808  /* Ensure adequate test coverage */
77809  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
77810  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
77811  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
77812  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
77813  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
77814  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
77815  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
77816  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
77817}
77818
77819/*
77820** Generate code for a boolean expression such that a jump is made
77821** to the label "dest" if the expression is true but execution
77822** continues straight thru if the expression is false.
77823**
77824** If the expression evaluates to NULL (neither true nor false), then
77825** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
77826**
77827** This code depends on the fact that certain token values (ex: TK_EQ)
77828** are the same as opcode values (ex: OP_Eq) that implement the corresponding
77829** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
77830** the make process cause these values to align.  Assert()s in the code
77831** below verify that the numbers are aligned correctly.
77832*/
77833SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77834  Vdbe *v = pParse->pVdbe;
77835  int op = 0;
77836  int regFree1 = 0;
77837  int regFree2 = 0;
77838  int r1, r2;
77839
77840  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77841  if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
77842  if( NEVER(pExpr==0) ) return;  /* No way this can happen */
77843  op = pExpr->op;
77844  switch( op ){
77845    case TK_AND: {
77846      int d2 = sqlite3VdbeMakeLabel(v);
77847      testcase( jumpIfNull==0 );
77848      sqlite3ExprCachePush(pParse);
77849      sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
77850      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77851      sqlite3VdbeResolveLabel(v, d2);
77852      sqlite3ExprCachePop(pParse, 1);
77853      break;
77854    }
77855    case TK_OR: {
77856      testcase( jumpIfNull==0 );
77857      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
77858      sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
77859      break;
77860    }
77861    case TK_NOT: {
77862      testcase( jumpIfNull==0 );
77863      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77864      break;
77865    }
77866    case TK_LT:
77867    case TK_LE:
77868    case TK_GT:
77869    case TK_GE:
77870    case TK_NE:
77871    case TK_EQ: {
77872      assert( TK_LT==OP_Lt );
77873      assert( TK_LE==OP_Le );
77874      assert( TK_GT==OP_Gt );
77875      assert( TK_GE==OP_Ge );
77876      assert( TK_EQ==OP_Eq );
77877      assert( TK_NE==OP_Ne );
77878      testcase( op==TK_LT );
77879      testcase( op==TK_LE );
77880      testcase( op==TK_GT );
77881      testcase( op==TK_GE );
77882      testcase( op==TK_EQ );
77883      testcase( op==TK_NE );
77884      testcase( jumpIfNull==0 );
77885      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77886      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77887      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77888                  r1, r2, dest, jumpIfNull);
77889      testcase( regFree1==0 );
77890      testcase( regFree2==0 );
77891      break;
77892    }
77893    case TK_IS:
77894    case TK_ISNOT: {
77895      testcase( op==TK_IS );
77896      testcase( op==TK_ISNOT );
77897      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77898      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77899      op = (op==TK_IS) ? TK_EQ : TK_NE;
77900      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77901                  r1, r2, dest, SQLITE_NULLEQ);
77902      testcase( regFree1==0 );
77903      testcase( regFree2==0 );
77904      break;
77905    }
77906    case TK_ISNULL:
77907    case TK_NOTNULL: {
77908      assert( TK_ISNULL==OP_IsNull );
77909      assert( TK_NOTNULL==OP_NotNull );
77910      testcase( op==TK_ISNULL );
77911      testcase( op==TK_NOTNULL );
77912      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77913      sqlite3VdbeAddOp2(v, op, r1, dest);
77914      testcase( regFree1==0 );
77915      break;
77916    }
77917    case TK_BETWEEN: {
77918      testcase( jumpIfNull==0 );
77919      exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
77920      break;
77921    }
77922#ifndef SQLITE_OMIT_SUBQUERY
77923    case TK_IN: {
77924      int destIfFalse = sqlite3VdbeMakeLabel(v);
77925      int destIfNull = jumpIfNull ? dest : destIfFalse;
77926      sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77927      sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
77928      sqlite3VdbeResolveLabel(v, destIfFalse);
77929      break;
77930    }
77931#endif
77932    default: {
77933      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
77934      sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
77935      testcase( regFree1==0 );
77936      testcase( jumpIfNull==0 );
77937      break;
77938    }
77939  }
77940  sqlite3ReleaseTempReg(pParse, regFree1);
77941  sqlite3ReleaseTempReg(pParse, regFree2);
77942}
77943
77944/*
77945** Generate code for a boolean expression such that a jump is made
77946** to the label "dest" if the expression is false but execution
77947** continues straight thru if the expression is true.
77948**
77949** If the expression evaluates to NULL (neither true nor false) then
77950** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
77951** is 0.
77952*/
77953SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
77954  Vdbe *v = pParse->pVdbe;
77955  int op = 0;
77956  int regFree1 = 0;
77957  int regFree2 = 0;
77958  int r1, r2;
77959
77960  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
77961  if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
77962  if( pExpr==0 )    return;
77963
77964  /* The value of pExpr->op and op are related as follows:
77965  **
77966  **       pExpr->op            op
77967  **       ---------          ----------
77968  **       TK_ISNULL          OP_NotNull
77969  **       TK_NOTNULL         OP_IsNull
77970  **       TK_NE              OP_Eq
77971  **       TK_EQ              OP_Ne
77972  **       TK_GT              OP_Le
77973  **       TK_LE              OP_Gt
77974  **       TK_GE              OP_Lt
77975  **       TK_LT              OP_Ge
77976  **
77977  ** For other values of pExpr->op, op is undefined and unused.
77978  ** The value of TK_ and OP_ constants are arranged such that we
77979  ** can compute the mapping above using the following expression.
77980  ** Assert()s verify that the computation is correct.
77981  */
77982  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
77983
77984  /* Verify correct alignment of TK_ and OP_ constants
77985  */
77986  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
77987  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
77988  assert( pExpr->op!=TK_NE || op==OP_Eq );
77989  assert( pExpr->op!=TK_EQ || op==OP_Ne );
77990  assert( pExpr->op!=TK_LT || op==OP_Ge );
77991  assert( pExpr->op!=TK_LE || op==OP_Gt );
77992  assert( pExpr->op!=TK_GT || op==OP_Le );
77993  assert( pExpr->op!=TK_GE || op==OP_Lt );
77994
77995  switch( pExpr->op ){
77996    case TK_AND: {
77997      testcase( jumpIfNull==0 );
77998      sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
77999      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78000      break;
78001    }
78002    case TK_OR: {
78003      int d2 = sqlite3VdbeMakeLabel(v);
78004      testcase( jumpIfNull==0 );
78005      sqlite3ExprCachePush(pParse);
78006      sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
78007      sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78008      sqlite3VdbeResolveLabel(v, d2);
78009      sqlite3ExprCachePop(pParse, 1);
78010      break;
78011    }
78012    case TK_NOT: {
78013      testcase( jumpIfNull==0 );
78014      sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
78015      break;
78016    }
78017    case TK_LT:
78018    case TK_LE:
78019    case TK_GT:
78020    case TK_GE:
78021    case TK_NE:
78022    case TK_EQ: {
78023      testcase( op==TK_LT );
78024      testcase( op==TK_LE );
78025      testcase( op==TK_GT );
78026      testcase( op==TK_GE );
78027      testcase( op==TK_EQ );
78028      testcase( op==TK_NE );
78029      testcase( jumpIfNull==0 );
78030      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78031      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78032      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78033                  r1, r2, dest, jumpIfNull);
78034      testcase( regFree1==0 );
78035      testcase( regFree2==0 );
78036      break;
78037    }
78038    case TK_IS:
78039    case TK_ISNOT: {
78040      testcase( pExpr->op==TK_IS );
78041      testcase( pExpr->op==TK_ISNOT );
78042      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78043      r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78044      op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
78045      codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78046                  r1, r2, dest, SQLITE_NULLEQ);
78047      testcase( regFree1==0 );
78048      testcase( regFree2==0 );
78049      break;
78050    }
78051    case TK_ISNULL:
78052    case TK_NOTNULL: {
78053      testcase( op==TK_ISNULL );
78054      testcase( op==TK_NOTNULL );
78055      r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78056      sqlite3VdbeAddOp2(v, op, r1, dest);
78057      testcase( regFree1==0 );
78058      break;
78059    }
78060    case TK_BETWEEN: {
78061      testcase( jumpIfNull==0 );
78062      exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
78063      break;
78064    }
78065#ifndef SQLITE_OMIT_SUBQUERY
78066    case TK_IN: {
78067      if( jumpIfNull ){
78068        sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
78069      }else{
78070        int destIfNull = sqlite3VdbeMakeLabel(v);
78071        sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
78072        sqlite3VdbeResolveLabel(v, destIfNull);
78073      }
78074      break;
78075    }
78076#endif
78077    default: {
78078      r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
78079      sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
78080      testcase( regFree1==0 );
78081      testcase( jumpIfNull==0 );
78082      break;
78083    }
78084  }
78085  sqlite3ReleaseTempReg(pParse, regFree1);
78086  sqlite3ReleaseTempReg(pParse, regFree2);
78087}
78088
78089/*
78090** Do a deep comparison of two expression trees.  Return 0 if the two
78091** expressions are completely identical.  Return 1 if they differ only
78092** by a COLLATE operator at the top level.  Return 2 if there are differences
78093** other than the top-level COLLATE operator.
78094**
78095** Sometimes this routine will return 2 even if the two expressions
78096** really are equivalent.  If we cannot prove that the expressions are
78097** identical, we return 2 just to be safe.  So if this routine
78098** returns 2, then you do not really know for certain if the two
78099** expressions are the same.  But if you get a 0 or 1 return, then you
78100** can be sure the expressions are the same.  In the places where
78101** this routine is used, it does not hurt to get an extra 2 - that
78102** just might result in some slightly slower code.  But returning
78103** an incorrect 0 or 1 could lead to a malfunction.
78104*/
78105SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
78106  if( pA==0||pB==0 ){
78107    return pB==pA ? 0 : 2;
78108  }
78109  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
78110  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
78111  if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
78112    return 2;
78113  }
78114  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
78115  if( pA->op!=pB->op ) return 2;
78116  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
78117  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
78118  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
78119  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
78120  if( ExprHasProperty(pA, EP_IntValue) ){
78121    if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
78122      return 2;
78123    }
78124  }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
78125    if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
78126    if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
78127      return 2;
78128    }
78129  }
78130  if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
78131  if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
78132  return 0;
78133}
78134
78135/*
78136** Compare two ExprList objects.  Return 0 if they are identical and
78137** non-zero if they differ in any way.
78138**
78139** This routine might return non-zero for equivalent ExprLists.  The
78140** only consequence will be disabled optimizations.  But this routine
78141** must never return 0 if the two ExprList objects are different, or
78142** a malfunction will result.
78143**
78144** Two NULL pointers are considered to be the same.  But a NULL pointer
78145** always differs from a non-NULL pointer.
78146*/
78147SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
78148  int i;
78149  if( pA==0 && pB==0 ) return 0;
78150  if( pA==0 || pB==0 ) return 1;
78151  if( pA->nExpr!=pB->nExpr ) return 1;
78152  for(i=0; i<pA->nExpr; i++){
78153    Expr *pExprA = pA->a[i].pExpr;
78154    Expr *pExprB = pB->a[i].pExpr;
78155    if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
78156    if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
78157  }
78158  return 0;
78159}
78160
78161/*
78162** Add a new element to the pAggInfo->aCol[] array.  Return the index of
78163** the new element.  Return a negative number if malloc fails.
78164*/
78165static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
78166  int i;
78167  pInfo->aCol = sqlite3ArrayAllocate(
78168       db,
78169       pInfo->aCol,
78170       sizeof(pInfo->aCol[0]),
78171       &pInfo->nColumn,
78172       &i
78173  );
78174  return i;
78175}
78176
78177/*
78178** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
78179** the new element.  Return a negative number if malloc fails.
78180*/
78181static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
78182  int i;
78183  pInfo->aFunc = sqlite3ArrayAllocate(
78184       db,
78185       pInfo->aFunc,
78186       sizeof(pInfo->aFunc[0]),
78187       &pInfo->nFunc,
78188       &i
78189  );
78190  return i;
78191}
78192
78193/*
78194** This is the xExprCallback for a tree walker.  It is used to
78195** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
78196** for additional information.
78197*/
78198static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
78199  int i;
78200  NameContext *pNC = pWalker->u.pNC;
78201  Parse *pParse = pNC->pParse;
78202  SrcList *pSrcList = pNC->pSrcList;
78203  AggInfo *pAggInfo = pNC->pAggInfo;
78204
78205  switch( pExpr->op ){
78206    case TK_AGG_COLUMN:
78207    case TK_COLUMN: {
78208      testcase( pExpr->op==TK_AGG_COLUMN );
78209      testcase( pExpr->op==TK_COLUMN );
78210      /* Check to see if the column is in one of the tables in the FROM
78211      ** clause of the aggregate query */
78212      if( ALWAYS(pSrcList!=0) ){
78213        struct SrcList_item *pItem = pSrcList->a;
78214        for(i=0; i<pSrcList->nSrc; i++, pItem++){
78215          struct AggInfo_col *pCol;
78216          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
78217          if( pExpr->iTable==pItem->iCursor ){
78218            /* If we reach this point, it means that pExpr refers to a table
78219            ** that is in the FROM clause of the aggregate query.
78220            **
78221            ** Make an entry for the column in pAggInfo->aCol[] if there
78222            ** is not an entry there already.
78223            */
78224            int k;
78225            pCol = pAggInfo->aCol;
78226            for(k=0; k<pAggInfo->nColumn; k++, pCol++){
78227              if( pCol->iTable==pExpr->iTable &&
78228                  pCol->iColumn==pExpr->iColumn ){
78229                break;
78230              }
78231            }
78232            if( (k>=pAggInfo->nColumn)
78233             && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
78234            ){
78235              pCol = &pAggInfo->aCol[k];
78236              pCol->pTab = pExpr->pTab;
78237              pCol->iTable = pExpr->iTable;
78238              pCol->iColumn = pExpr->iColumn;
78239              pCol->iMem = ++pParse->nMem;
78240              pCol->iSorterColumn = -1;
78241              pCol->pExpr = pExpr;
78242              if( pAggInfo->pGroupBy ){
78243                int j, n;
78244                ExprList *pGB = pAggInfo->pGroupBy;
78245                struct ExprList_item *pTerm = pGB->a;
78246                n = pGB->nExpr;
78247                for(j=0; j<n; j++, pTerm++){
78248                  Expr *pE = pTerm->pExpr;
78249                  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
78250                      pE->iColumn==pExpr->iColumn ){
78251                    pCol->iSorterColumn = j;
78252                    break;
78253                  }
78254                }
78255              }
78256              if( pCol->iSorterColumn<0 ){
78257                pCol->iSorterColumn = pAggInfo->nSortingColumn++;
78258              }
78259            }
78260            /* There is now an entry for pExpr in pAggInfo->aCol[] (either
78261            ** because it was there before or because we just created it).
78262            ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
78263            ** pAggInfo->aCol[] entry.
78264            */
78265            ExprSetIrreducible(pExpr);
78266            pExpr->pAggInfo = pAggInfo;
78267            pExpr->op = TK_AGG_COLUMN;
78268            pExpr->iAgg = (i16)k;
78269            break;
78270          } /* endif pExpr->iTable==pItem->iCursor */
78271        } /* end loop over pSrcList */
78272      }
78273      return WRC_Prune;
78274    }
78275    case TK_AGG_FUNCTION: {
78276      /* The pNC->nDepth==0 test causes aggregate functions in subqueries
78277      ** to be ignored */
78278      if( pNC->nDepth==0 ){
78279        /* Check to see if pExpr is a duplicate of another aggregate
78280        ** function that is already in the pAggInfo structure
78281        */
78282        struct AggInfo_func *pItem = pAggInfo->aFunc;
78283        for(i=0; i<pAggInfo->nFunc; i++, pItem++){
78284          if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
78285            break;
78286          }
78287        }
78288        if( i>=pAggInfo->nFunc ){
78289          /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
78290          */
78291          u8 enc = ENC(pParse->db);
78292          i = addAggInfoFunc(pParse->db, pAggInfo);
78293          if( i>=0 ){
78294            assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78295            pItem = &pAggInfo->aFunc[i];
78296            pItem->pExpr = pExpr;
78297            pItem->iMem = ++pParse->nMem;
78298            assert( !ExprHasProperty(pExpr, EP_IntValue) );
78299            pItem->pFunc = sqlite3FindFunction(pParse->db,
78300                   pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
78301                   pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
78302            if( pExpr->flags & EP_Distinct ){
78303              pItem->iDistinct = pParse->nTab++;
78304            }else{
78305              pItem->iDistinct = -1;
78306            }
78307          }
78308        }
78309        /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
78310        */
78311        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
78312        ExprSetIrreducible(pExpr);
78313        pExpr->iAgg = (i16)i;
78314        pExpr->pAggInfo = pAggInfo;
78315        return WRC_Prune;
78316      }
78317    }
78318  }
78319  return WRC_Continue;
78320}
78321static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
78322  NameContext *pNC = pWalker->u.pNC;
78323  if( pNC->nDepth==0 ){
78324    pNC->nDepth++;
78325    sqlite3WalkSelect(pWalker, pSelect);
78326    pNC->nDepth--;
78327    return WRC_Prune;
78328  }else{
78329    return WRC_Continue;
78330  }
78331}
78332
78333/*
78334** Analyze the given expression looking for aggregate functions and
78335** for variables that need to be added to the pParse->aAgg[] array.
78336** Make additional entries to the pParse->aAgg[] array as necessary.
78337**
78338** This routine should only be called after the expression has been
78339** analyzed by sqlite3ResolveExprNames().
78340*/
78341SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
78342  Walker w;
78343  w.xExprCallback = analyzeAggregate;
78344  w.xSelectCallback = analyzeAggregatesInSelect;
78345  w.u.pNC = pNC;
78346  assert( pNC->pSrcList!=0 );
78347  sqlite3WalkExpr(&w, pExpr);
78348}
78349
78350/*
78351** Call sqlite3ExprAnalyzeAggregates() for every expression in an
78352** expression list.  Return the number of errors.
78353**
78354** If an error is found, the analysis is cut short.
78355*/
78356SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
78357  struct ExprList_item *pItem;
78358  int i;
78359  if( pList ){
78360    for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
78361      sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
78362    }
78363  }
78364}
78365
78366/*
78367** Allocate a single new register for use to hold some intermediate result.
78368*/
78369SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
78370  if( pParse->nTempReg==0 ){
78371    return ++pParse->nMem;
78372  }
78373  return pParse->aTempReg[--pParse->nTempReg];
78374}
78375
78376/*
78377** Deallocate a register, making available for reuse for some other
78378** purpose.
78379**
78380** If a register is currently being used by the column cache, then
78381** the dallocation is deferred until the column cache line that uses
78382** the register becomes stale.
78383*/
78384SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
78385  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
78386    int i;
78387    struct yColCache *p;
78388    for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
78389      if( p->iReg==iReg ){
78390        p->tempReg = 1;
78391        return;
78392      }
78393    }
78394    pParse->aTempReg[pParse->nTempReg++] = iReg;
78395  }
78396}
78397
78398/*
78399** Allocate or deallocate a block of nReg consecutive registers
78400*/
78401SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
78402  int i, n;
78403  i = pParse->iRangeReg;
78404  n = pParse->nRangeReg;
78405  if( nReg<=n ){
78406    assert( !usedAsColumnCache(pParse, i, i+n-1) );
78407    pParse->iRangeReg += nReg;
78408    pParse->nRangeReg -= nReg;
78409  }else{
78410    i = pParse->nMem+1;
78411    pParse->nMem += nReg;
78412  }
78413  return i;
78414}
78415SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
78416  sqlite3ExprCacheRemove(pParse, iReg, nReg);
78417  if( nReg>pParse->nRangeReg ){
78418    pParse->nRangeReg = nReg;
78419    pParse->iRangeReg = iReg;
78420  }
78421}
78422
78423/*
78424** Mark all temporary registers as being unavailable for reuse.
78425*/
78426SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
78427  pParse->nTempReg = 0;
78428  pParse->nRangeReg = 0;
78429}
78430
78431/************** End of expr.c ************************************************/
78432/************** Begin file alter.c *******************************************/
78433/*
78434** 2005 February 15
78435**
78436** The author disclaims copyright to this source code.  In place of
78437** a legal notice, here is a blessing:
78438**
78439**    May you do good and not evil.
78440**    May you find forgiveness for yourself and forgive others.
78441**    May you share freely, never taking more than you give.
78442**
78443*************************************************************************
78444** This file contains C code routines that used to generate VDBE code
78445** that implements the ALTER TABLE command.
78446*/
78447
78448/*
78449** The code in this file only exists if we are not omitting the
78450** ALTER TABLE logic from the build.
78451*/
78452#ifndef SQLITE_OMIT_ALTERTABLE
78453
78454
78455/*
78456** This function is used by SQL generated to implement the
78457** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
78458** CREATE INDEX command. The second is a table name. The table name in
78459** the CREATE TABLE or CREATE INDEX statement is replaced with the third
78460** argument and the result returned. Examples:
78461**
78462** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
78463**     -> 'CREATE TABLE def(a, b, c)'
78464**
78465** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
78466**     -> 'CREATE INDEX i ON def(a, b, c)'
78467*/
78468static void renameTableFunc(
78469  sqlite3_context *context,
78470  int NotUsed,
78471  sqlite3_value **argv
78472){
78473  unsigned char const *zSql = sqlite3_value_text(argv[0]);
78474  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78475
78476  int token;
78477  Token tname;
78478  unsigned char const *zCsr = zSql;
78479  int len = 0;
78480  char *zRet;
78481
78482  sqlite3 *db = sqlite3_context_db_handle(context);
78483
78484  UNUSED_PARAMETER(NotUsed);
78485
78486  /* The principle used to locate the table name in the CREATE TABLE
78487  ** statement is that the table name is the first non-space token that
78488  ** is immediately followed by a TK_LP or TK_USING token.
78489  */
78490  if( zSql ){
78491    do {
78492      if( !*zCsr ){
78493        /* Ran out of input before finding an opening bracket. Return NULL. */
78494        return;
78495      }
78496
78497      /* Store the token that zCsr points to in tname. */
78498      tname.z = (char*)zCsr;
78499      tname.n = len;
78500
78501      /* Advance zCsr to the next token. Store that token type in 'token',
78502      ** and its length in 'len' (to be used next iteration of this loop).
78503      */
78504      do {
78505        zCsr += len;
78506        len = sqlite3GetToken(zCsr, &token);
78507      } while( token==TK_SPACE );
78508      assert( len>0 );
78509    } while( token!=TK_LP && token!=TK_USING );
78510
78511    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
78512       zTableName, tname.z+tname.n);
78513    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78514  }
78515}
78516
78517/*
78518** This C function implements an SQL user function that is used by SQL code
78519** generated by the ALTER TABLE ... RENAME command to modify the definition
78520** of any foreign key constraints that use the table being renamed as the
78521** parent table. It is passed three arguments:
78522**
78523**   1) The complete text of the CREATE TABLE statement being modified,
78524**   2) The old name of the table being renamed, and
78525**   3) The new name of the table being renamed.
78526**
78527** It returns the new CREATE TABLE statement. For example:
78528**
78529**   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
78530**       -> 'CREATE TABLE t1(a REFERENCES t3)'
78531*/
78532#ifndef SQLITE_OMIT_FOREIGN_KEY
78533static void renameParentFunc(
78534  sqlite3_context *context,
78535  int NotUsed,
78536  sqlite3_value **argv
78537){
78538  sqlite3 *db = sqlite3_context_db_handle(context);
78539  char *zOutput = 0;
78540  char *zResult;
78541  unsigned char const *zInput = sqlite3_value_text(argv[0]);
78542  unsigned char const *zOld = sqlite3_value_text(argv[1]);
78543  unsigned char const *zNew = sqlite3_value_text(argv[2]);
78544
78545  unsigned const char *z;         /* Pointer to token */
78546  int n;                          /* Length of token z */
78547  int token;                      /* Type of token */
78548
78549  UNUSED_PARAMETER(NotUsed);
78550  for(z=zInput; *z; z=z+n){
78551    n = sqlite3GetToken(z, &token);
78552    if( token==TK_REFERENCES ){
78553      char *zParent;
78554      do {
78555        z += n;
78556        n = sqlite3GetToken(z, &token);
78557      }while( token==TK_SPACE );
78558
78559      zParent = sqlite3DbStrNDup(db, (const char *)z, n);
78560      if( zParent==0 ) break;
78561      sqlite3Dequote(zParent);
78562      if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
78563        char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
78564            (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
78565        );
78566        sqlite3DbFree(db, zOutput);
78567        zOutput = zOut;
78568        zInput = &z[n];
78569      }
78570      sqlite3DbFree(db, zParent);
78571    }
78572  }
78573
78574  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
78575  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
78576  sqlite3DbFree(db, zOutput);
78577}
78578#endif
78579
78580#ifndef SQLITE_OMIT_TRIGGER
78581/* This function is used by SQL generated to implement the
78582** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
78583** statement. The second is a table name. The table name in the CREATE
78584** TRIGGER statement is replaced with the third argument and the result
78585** returned. This is analagous to renameTableFunc() above, except for CREATE
78586** TRIGGER, not CREATE INDEX and CREATE TABLE.
78587*/
78588static void renameTriggerFunc(
78589  sqlite3_context *context,
78590  int NotUsed,
78591  sqlite3_value **argv
78592){
78593  unsigned char const *zSql = sqlite3_value_text(argv[0]);
78594  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
78595
78596  int token;
78597  Token tname;
78598  int dist = 3;
78599  unsigned char const *zCsr = zSql;
78600  int len = 0;
78601  char *zRet;
78602  sqlite3 *db = sqlite3_context_db_handle(context);
78603
78604  UNUSED_PARAMETER(NotUsed);
78605
78606  /* The principle used to locate the table name in the CREATE TRIGGER
78607  ** statement is that the table name is the first token that is immediatedly
78608  ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
78609  ** of TK_WHEN, TK_BEGIN or TK_FOR.
78610  */
78611  if( zSql ){
78612    do {
78613
78614      if( !*zCsr ){
78615        /* Ran out of input before finding the table name. Return NULL. */
78616        return;
78617      }
78618
78619      /* Store the token that zCsr points to in tname. */
78620      tname.z = (char*)zCsr;
78621      tname.n = len;
78622
78623      /* Advance zCsr to the next token. Store that token type in 'token',
78624      ** and its length in 'len' (to be used next iteration of this loop).
78625      */
78626      do {
78627        zCsr += len;
78628        len = sqlite3GetToken(zCsr, &token);
78629      }while( token==TK_SPACE );
78630      assert( len>0 );
78631
78632      /* Variable 'dist' stores the number of tokens read since the most
78633      ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
78634      ** token is read and 'dist' equals 2, the condition stated above
78635      ** to be met.
78636      **
78637      ** Note that ON cannot be a database, table or column name, so
78638      ** there is no need to worry about syntax like
78639      ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
78640      */
78641      dist++;
78642      if( token==TK_DOT || token==TK_ON ){
78643        dist = 0;
78644      }
78645    } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
78646
78647    /* Variable tname now contains the token that is the old table-name
78648    ** in the CREATE TRIGGER statement.
78649    */
78650    zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
78651       zTableName, tname.z+tname.n);
78652    sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
78653  }
78654}
78655#endif   /* !SQLITE_OMIT_TRIGGER */
78656
78657/*
78658** Register built-in functions used to help implement ALTER TABLE
78659*/
78660SQLITE_PRIVATE void sqlite3AlterFunctions(void){
78661  static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
78662    FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
78663#ifndef SQLITE_OMIT_TRIGGER
78664    FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
78665#endif
78666#ifndef SQLITE_OMIT_FOREIGN_KEY
78667    FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
78668#endif
78669  };
78670  int i;
78671  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
78672  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
78673
78674  for(i=0; i<ArraySize(aAlterTableFuncs); i++){
78675    sqlite3FuncDefInsert(pHash, &aFunc[i]);
78676  }
78677}
78678
78679/*
78680** This function is used to create the text of expressions of the form:
78681**
78682**   name=<constant1> OR name=<constant2> OR ...
78683**
78684** If argument zWhere is NULL, then a pointer string containing the text
78685** "name=<constant>" is returned, where <constant> is the quoted version
78686** of the string passed as argument zConstant. The returned buffer is
78687** allocated using sqlite3DbMalloc(). It is the responsibility of the
78688** caller to ensure that it is eventually freed.
78689**
78690** If argument zWhere is not NULL, then the string returned is
78691** "<where> OR name=<constant>", where <where> is the contents of zWhere.
78692** In this case zWhere is passed to sqlite3DbFree() before returning.
78693**
78694*/
78695static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
78696  char *zNew;
78697  if( !zWhere ){
78698    zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
78699  }else{
78700    zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
78701    sqlite3DbFree(db, zWhere);
78702  }
78703  return zNew;
78704}
78705
78706#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78707/*
78708** Generate the text of a WHERE expression which can be used to select all
78709** tables that have foreign key constraints that refer to table pTab (i.e.
78710** constraints for which pTab is the parent table) from the sqlite_master
78711** table.
78712*/
78713static char *whereForeignKeys(Parse *pParse, Table *pTab){
78714  FKey *p;
78715  char *zWhere = 0;
78716  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
78717    zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
78718  }
78719  return zWhere;
78720}
78721#endif
78722
78723/*
78724** Generate the text of a WHERE expression which can be used to select all
78725** temporary triggers on table pTab from the sqlite_temp_master table. If
78726** table pTab has no temporary triggers, or is itself stored in the
78727** temporary database, NULL is returned.
78728*/
78729static char *whereTempTriggers(Parse *pParse, Table *pTab){
78730  Trigger *pTrig;
78731  char *zWhere = 0;
78732  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
78733
78734  /* If the table is not located in the temp-db (in which case NULL is
78735  ** returned, loop through the tables list of triggers. For each trigger
78736  ** that is not part of the temp-db schema, add a clause to the WHERE
78737  ** expression being built up in zWhere.
78738  */
78739  if( pTab->pSchema!=pTempSchema ){
78740    sqlite3 *db = pParse->db;
78741    for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78742      if( pTrig->pSchema==pTempSchema ){
78743        zWhere = whereOrName(db, zWhere, pTrig->zName);
78744      }
78745    }
78746  }
78747  if( zWhere ){
78748    char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
78749    sqlite3DbFree(pParse->db, zWhere);
78750    zWhere = zNew;
78751  }
78752  return zWhere;
78753}
78754
78755/*
78756** Generate code to drop and reload the internal representation of table
78757** pTab from the database, including triggers and temporary triggers.
78758** Argument zName is the name of the table in the database schema at
78759** the time the generated code is executed. This can be different from
78760** pTab->zName if this function is being called to code part of an
78761** "ALTER TABLE RENAME TO" statement.
78762*/
78763static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
78764  Vdbe *v;
78765  char *zWhere;
78766  int iDb;                   /* Index of database containing pTab */
78767#ifndef SQLITE_OMIT_TRIGGER
78768  Trigger *pTrig;
78769#endif
78770
78771  v = sqlite3GetVdbe(pParse);
78772  if( NEVER(v==0) ) return;
78773  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78774  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78775  assert( iDb>=0 );
78776
78777#ifndef SQLITE_OMIT_TRIGGER
78778  /* Drop any table triggers from the internal schema. */
78779  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
78780    int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
78781    assert( iTrigDb==iDb || iTrigDb==1 );
78782    sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
78783  }
78784#endif
78785
78786  /* Drop the table and index from the internal schema.  */
78787  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
78788
78789  /* Reload the table, index and permanent trigger schemas. */
78790  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
78791  if( !zWhere ) return;
78792  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
78793
78794#ifndef SQLITE_OMIT_TRIGGER
78795  /* Now, if the table is not stored in the temp database, reload any temp
78796  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
78797  */
78798  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78799    sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
78800  }
78801#endif
78802}
78803
78804/*
78805** Parameter zName is the name of a table that is about to be altered
78806** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
78807** If the table is a system table, this function leaves an error message
78808** in pParse->zErr (system tables may not be altered) and returns non-zero.
78809**
78810** Or, if zName is not a system table, zero is returned.
78811*/
78812static int isSystemTable(Parse *pParse, const char *zName){
78813  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
78814    sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
78815    return 1;
78816  }
78817  return 0;
78818}
78819
78820/*
78821** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
78822** command.
78823*/
78824SQLITE_PRIVATE void sqlite3AlterRenameTable(
78825  Parse *pParse,            /* Parser context. */
78826  SrcList *pSrc,            /* The table to rename. */
78827  Token *pName              /* The new table name. */
78828){
78829  int iDb;                  /* Database that contains the table */
78830  char *zDb;                /* Name of database iDb */
78831  Table *pTab;              /* Table being renamed */
78832  char *zName = 0;          /* NULL-terminated version of pName */
78833  sqlite3 *db = pParse->db; /* Database connection */
78834  int nTabName;             /* Number of UTF-8 characters in zTabName */
78835  const char *zTabName;     /* Original name of the table */
78836  Vdbe *v;
78837#ifndef SQLITE_OMIT_TRIGGER
78838  char *zWhere = 0;         /* Where clause to locate temp triggers */
78839#endif
78840  VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
78841  int savedDbFlags;         /* Saved value of db->flags */
78842
78843  savedDbFlags = db->flags;
78844  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
78845  assert( pSrc->nSrc==1 );
78846  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
78847
78848  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
78849  if( !pTab ) goto exit_rename_table;
78850  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
78851  zDb = db->aDb[iDb].zName;
78852  db->flags |= SQLITE_PreferBuiltin;
78853
78854  /* Get a NULL terminated version of the new table name. */
78855  zName = sqlite3NameFromToken(db, pName);
78856  if( !zName ) goto exit_rename_table;
78857
78858  /* Check that a table or index named 'zName' does not already exist
78859  ** in database iDb. If so, this is an error.
78860  */
78861  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
78862    sqlite3ErrorMsg(pParse,
78863        "there is already another table or index with this name: %s", zName);
78864    goto exit_rename_table;
78865  }
78866
78867  /* Make sure it is not a system table being altered, or a reserved name
78868  ** that the table is being renamed to.
78869  */
78870  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
78871    goto exit_rename_table;
78872  }
78873  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
78874    exit_rename_table;
78875  }
78876
78877#ifndef SQLITE_OMIT_VIEW
78878  if( pTab->pSelect ){
78879    sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
78880    goto exit_rename_table;
78881  }
78882#endif
78883
78884#ifndef SQLITE_OMIT_AUTHORIZATION
78885  /* Invoke the authorization callback. */
78886  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
78887    goto exit_rename_table;
78888  }
78889#endif
78890
78891#ifndef SQLITE_OMIT_VIRTUALTABLE
78892  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
78893    goto exit_rename_table;
78894  }
78895  if( IsVirtual(pTab) ){
78896    pVTab = sqlite3GetVTable(db, pTab);
78897    if( pVTab->pVtab->pModule->xRename==0 ){
78898      pVTab = 0;
78899    }
78900  }
78901#endif
78902
78903  /* Begin a transaction and code the VerifyCookie for database iDb.
78904  ** Then modify the schema cookie (since the ALTER TABLE modifies the
78905  ** schema). Open a statement transaction if the table is a virtual
78906  ** table.
78907  */
78908  v = sqlite3GetVdbe(pParse);
78909  if( v==0 ){
78910    goto exit_rename_table;
78911  }
78912  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
78913  sqlite3ChangeCookie(pParse, iDb);
78914
78915  /* If this is a virtual table, invoke the xRename() function if
78916  ** one is defined. The xRename() callback will modify the names
78917  ** of any resources used by the v-table implementation (including other
78918  ** SQLite tables) that are identified by the name of the virtual table.
78919  */
78920#ifndef SQLITE_OMIT_VIRTUALTABLE
78921  if( pVTab ){
78922    int i = ++pParse->nMem;
78923    sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
78924    sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
78925    sqlite3MayAbort(pParse);
78926  }
78927#endif
78928
78929  /* figure out how many UTF-8 characters are in zName */
78930  zTabName = pTab->zName;
78931  nTabName = sqlite3Utf8CharLen(zTabName, -1);
78932
78933#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78934  if( db->flags&SQLITE_ForeignKeys ){
78935    /* If foreign-key support is enabled, rewrite the CREATE TABLE
78936    ** statements corresponding to all child tables of foreign key constraints
78937    ** for which the renamed table is the parent table.  */
78938    if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
78939      sqlite3NestedParse(pParse,
78940          "UPDATE \"%w\".%s SET "
78941              "sql = sqlite_rename_parent(sql, %Q, %Q) "
78942              "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
78943      sqlite3DbFree(db, zWhere);
78944    }
78945  }
78946#endif
78947
78948  /* Modify the sqlite_master table to use the new table name. */
78949  sqlite3NestedParse(pParse,
78950      "UPDATE %Q.%s SET "
78951#ifdef SQLITE_OMIT_TRIGGER
78952          "sql = sqlite_rename_table(sql, %Q), "
78953#else
78954          "sql = CASE "
78955            "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
78956            "ELSE sqlite_rename_table(sql, %Q) END, "
78957#endif
78958          "tbl_name = %Q, "
78959          "name = CASE "
78960            "WHEN type='table' THEN %Q "
78961            "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
78962             "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
78963            "ELSE name END "
78964      "WHERE tbl_name=%Q COLLATE nocase AND "
78965          "(type='table' OR type='index' OR type='trigger');",
78966      zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
78967#ifndef SQLITE_OMIT_TRIGGER
78968      zName,
78969#endif
78970      zName, nTabName, zTabName
78971  );
78972
78973#ifndef SQLITE_OMIT_AUTOINCREMENT
78974  /* If the sqlite_sequence table exists in this database, then update
78975  ** it with the new table name.
78976  */
78977  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
78978    sqlite3NestedParse(pParse,
78979        "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
78980        zDb, zName, pTab->zName);
78981  }
78982#endif
78983
78984#ifndef SQLITE_OMIT_TRIGGER
78985  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
78986  ** table. Don't do this if the table being ALTERed is itself located in
78987  ** the temp database.
78988  */
78989  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
78990    sqlite3NestedParse(pParse,
78991        "UPDATE sqlite_temp_master SET "
78992            "sql = sqlite_rename_trigger(sql, %Q), "
78993            "tbl_name = %Q "
78994            "WHERE %s;", zName, zName, zWhere);
78995    sqlite3DbFree(db, zWhere);
78996  }
78997#endif
78998
78999#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79000  if( db->flags&SQLITE_ForeignKeys ){
79001    FKey *p;
79002    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79003      Table *pFrom = p->pFrom;
79004      if( pFrom!=pTab ){
79005        reloadTableSchema(pParse, p->pFrom, pFrom->zName);
79006      }
79007    }
79008  }
79009#endif
79010
79011  /* Drop and reload the internal table schema. */
79012  reloadTableSchema(pParse, pTab, zName);
79013
79014exit_rename_table:
79015  sqlite3SrcListDelete(db, pSrc);
79016  sqlite3DbFree(db, zName);
79017  db->flags = savedDbFlags;
79018}
79019
79020
79021/*
79022** Generate code to make sure the file format number is at least minFormat.
79023** The generated code will increase the file format number if necessary.
79024*/
79025SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
79026  Vdbe *v;
79027  v = sqlite3GetVdbe(pParse);
79028  /* The VDBE should have been allocated before this routine is called.
79029  ** If that allocation failed, we would have quit before reaching this
79030  ** point */
79031  if( ALWAYS(v) ){
79032    int r1 = sqlite3GetTempReg(pParse);
79033    int r2 = sqlite3GetTempReg(pParse);
79034    int j1;
79035    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
79036    sqlite3VdbeUsesBtree(v, iDb);
79037    sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
79038    j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
79039    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
79040    sqlite3VdbeJumpHere(v, j1);
79041    sqlite3ReleaseTempReg(pParse, r1);
79042    sqlite3ReleaseTempReg(pParse, r2);
79043  }
79044}
79045
79046/*
79047** This function is called after an "ALTER TABLE ... ADD" statement
79048** has been parsed. Argument pColDef contains the text of the new
79049** column definition.
79050**
79051** The Table structure pParse->pNewTable was extended to include
79052** the new column during parsing.
79053*/
79054SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
79055  Table *pNew;              /* Copy of pParse->pNewTable */
79056  Table *pTab;              /* Table being altered */
79057  int iDb;                  /* Database number */
79058  const char *zDb;          /* Database name */
79059  const char *zTab;         /* Table name */
79060  char *zCol;               /* Null-terminated column definition */
79061  Column *pCol;             /* The new column */
79062  Expr *pDflt;              /* Default value for the new column */
79063  sqlite3 *db;              /* The database connection; */
79064
79065  db = pParse->db;
79066  if( pParse->nErr || db->mallocFailed ) return;
79067  pNew = pParse->pNewTable;
79068  assert( pNew );
79069
79070  assert( sqlite3BtreeHoldsAllMutexes(db) );
79071  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
79072  zDb = db->aDb[iDb].zName;
79073  zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
79074  pCol = &pNew->aCol[pNew->nCol-1];
79075  pDflt = pCol->pDflt;
79076  pTab = sqlite3FindTable(db, zTab, zDb);
79077  assert( pTab );
79078
79079#ifndef SQLITE_OMIT_AUTHORIZATION
79080  /* Invoke the authorization callback. */
79081  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
79082    return;
79083  }
79084#endif
79085
79086  /* If the default value for the new column was specified with a
79087  ** literal NULL, then set pDflt to 0. This simplifies checking
79088  ** for an SQL NULL default below.
79089  */
79090  if( pDflt && pDflt->op==TK_NULL ){
79091    pDflt = 0;
79092  }
79093
79094  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
79095  ** If there is a NOT NULL constraint, then the default value for the
79096  ** column must not be NULL.
79097  */
79098  if( pCol->isPrimKey ){
79099    sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
79100    return;
79101  }
79102  if( pNew->pIndex ){
79103    sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
79104    return;
79105  }
79106  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
79107    sqlite3ErrorMsg(pParse,
79108        "Cannot add a REFERENCES column with non-NULL default value");
79109    return;
79110  }
79111  if( pCol->notNull && !pDflt ){
79112    sqlite3ErrorMsg(pParse,
79113        "Cannot add a NOT NULL column with default value NULL");
79114    return;
79115  }
79116
79117  /* Ensure the default expression is something that sqlite3ValueFromExpr()
79118  ** can handle (i.e. not CURRENT_TIME etc.)
79119  */
79120  if( pDflt ){
79121    sqlite3_value *pVal;
79122    if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
79123      db->mallocFailed = 1;
79124      return;
79125    }
79126    if( !pVal ){
79127      sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
79128      return;
79129    }
79130    sqlite3ValueFree(pVal);
79131  }
79132
79133  /* Modify the CREATE TABLE statement. */
79134  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
79135  if( zCol ){
79136    char *zEnd = &zCol[pColDef->n-1];
79137    int savedDbFlags = db->flags;
79138    while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
79139      *zEnd-- = '\0';
79140    }
79141    db->flags |= SQLITE_PreferBuiltin;
79142    sqlite3NestedParse(pParse,
79143        "UPDATE \"%w\".%s SET "
79144          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
79145        "WHERE type = 'table' AND name = %Q",
79146      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
79147      zTab
79148    );
79149    sqlite3DbFree(db, zCol);
79150    db->flags = savedDbFlags;
79151  }
79152
79153  /* If the default value of the new column is NULL, then set the file
79154  ** format to 2. If the default value of the new column is not NULL,
79155  ** the file format becomes 3.
79156  */
79157  sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
79158
79159  /* Reload the schema of the modified table. */
79160  reloadTableSchema(pParse, pTab, pTab->zName);
79161}
79162
79163/*
79164** This function is called by the parser after the table-name in
79165** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
79166** pSrc is the full-name of the table being altered.
79167**
79168** This routine makes a (partial) copy of the Table structure
79169** for the table being altered and sets Parse.pNewTable to point
79170** to it. Routines called by the parser as the column definition
79171** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
79172** the copy. The copy of the Table structure is deleted by tokenize.c
79173** after parsing is finished.
79174**
79175** Routine sqlite3AlterFinishAddColumn() will be called to complete
79176** coding the "ALTER TABLE ... ADD" statement.
79177*/
79178SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
79179  Table *pNew;
79180  Table *pTab;
79181  Vdbe *v;
79182  int iDb;
79183  int i;
79184  int nAlloc;
79185  sqlite3 *db = pParse->db;
79186
79187  /* Look up the table being altered. */
79188  assert( pParse->pNewTable==0 );
79189  assert( sqlite3BtreeHoldsAllMutexes(db) );
79190  if( db->mallocFailed ) goto exit_begin_add_column;
79191  pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
79192  if( !pTab ) goto exit_begin_add_column;
79193
79194#ifndef SQLITE_OMIT_VIRTUALTABLE
79195  if( IsVirtual(pTab) ){
79196    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
79197    goto exit_begin_add_column;
79198  }
79199#endif
79200
79201  /* Make sure this is not an attempt to ALTER a view. */
79202  if( pTab->pSelect ){
79203    sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
79204    goto exit_begin_add_column;
79205  }
79206  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
79207    goto exit_begin_add_column;
79208  }
79209
79210  assert( pTab->addColOffset>0 );
79211  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79212
79213  /* Put a copy of the Table struct in Parse.pNewTable for the
79214  ** sqlite3AddColumn() function and friends to modify.  But modify
79215  ** the name by adding an "sqlite_altertab_" prefix.  By adding this
79216  ** prefix, we insure that the name will not collide with an existing
79217  ** table because user table are not allowed to have the "sqlite_"
79218  ** prefix on their name.
79219  */
79220  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
79221  if( !pNew ) goto exit_begin_add_column;
79222  pParse->pNewTable = pNew;
79223  pNew->nRef = 1;
79224  pNew->nCol = pTab->nCol;
79225  assert( pNew->nCol>0 );
79226  nAlloc = (((pNew->nCol-1)/8)*8)+8;
79227  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
79228  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
79229  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
79230  if( !pNew->aCol || !pNew->zName ){
79231    db->mallocFailed = 1;
79232    goto exit_begin_add_column;
79233  }
79234  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
79235  for(i=0; i<pNew->nCol; i++){
79236    Column *pCol = &pNew->aCol[i];
79237    pCol->zName = sqlite3DbStrDup(db, pCol->zName);
79238    pCol->zColl = 0;
79239    pCol->zType = 0;
79240    pCol->pDflt = 0;
79241    pCol->zDflt = 0;
79242  }
79243  pNew->pSchema = db->aDb[iDb].pSchema;
79244  pNew->addColOffset = pTab->addColOffset;
79245  pNew->nRef = 1;
79246
79247  /* Begin a transaction and increment the schema cookie.  */
79248  sqlite3BeginWriteOperation(pParse, 0, iDb);
79249  v = sqlite3GetVdbe(pParse);
79250  if( !v ) goto exit_begin_add_column;
79251  sqlite3ChangeCookie(pParse, iDb);
79252
79253exit_begin_add_column:
79254  sqlite3SrcListDelete(db, pSrc);
79255  return;
79256}
79257#endif  /* SQLITE_ALTER_TABLE */
79258
79259/************** End of alter.c ***********************************************/
79260/************** Begin file analyze.c *****************************************/
79261/*
79262** 2005 July 8
79263**
79264** The author disclaims copyright to this source code.  In place of
79265** a legal notice, here is a blessing:
79266**
79267**    May you do good and not evil.
79268**    May you find forgiveness for yourself and forgive others.
79269**    May you share freely, never taking more than you give.
79270**
79271*************************************************************************
79272** This file contains code associated with the ANALYZE command.
79273**
79274** The ANALYZE command gather statistics about the content of tables
79275** and indices.  These statistics are made available to the query planner
79276** to help it make better decisions about how to perform queries.
79277**
79278** The following system tables are or have been supported:
79279**
79280**    CREATE TABLE sqlite_stat1(tbl, idx, stat);
79281**    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
79282**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
79283**
79284** Additional tables might be added in future releases of SQLite.
79285** The sqlite_stat2 table is not created or used unless the SQLite version
79286** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
79287** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
79288** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
79289** created and used by SQLite versions 3.7.9 and later and with
79290** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
79291** is a superset of sqlite_stat2.
79292**
79293** Format of sqlite_stat1:
79294**
79295** There is normally one row per index, with the index identified by the
79296** name in the idx column.  The tbl column is the name of the table to
79297** which the index belongs.  In each such row, the stat column will be
79298** a string consisting of a list of integers.  The first integer in this
79299** list is the number of rows in the index and in the table.  The second
79300** integer is the average number of rows in the index that have the same
79301** value in the first column of the index.  The third integer is the average
79302** number of rows in the index that have the same value for the first two
79303** columns.  The N-th integer (for N>1) is the average number of rows in
79304** the index which have the same value for the first N-1 columns.  For
79305** a K-column index, there will be K+1 integers in the stat column.  If
79306** the index is unique, then the last integer will be 1.
79307**
79308** The list of integers in the stat column can optionally be followed
79309** by the keyword "unordered".  The "unordered" keyword, if it is present,
79310** must be separated from the last integer by a single space.  If the
79311** "unordered" keyword is present, then the query planner assumes that
79312** the index is unordered and will not use the index for a range query.
79313**
79314** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
79315** column contains a single integer which is the (estimated) number of
79316** rows in the table identified by sqlite_stat1.tbl.
79317**
79318** Format of sqlite_stat2:
79319**
79320** The sqlite_stat2 is only created and is only used if SQLite is compiled
79321** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
79322** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
79323** about the distribution of keys within an index.  The index is identified by
79324** the "idx" column and the "tbl" column is the name of the table to which
79325** the index belongs.  There are usually 10 rows in the sqlite_stat2
79326** table for each index.
79327**
79328** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
79329** inclusive are samples of the left-most key value in the index taken at
79330** evenly spaced points along the index.  Let the number of samples be S
79331** (10 in the standard build) and let C be the number of rows in the index.
79332** Then the sampled rows are given by:
79333**
79334**     rownumber = (i*C*2 + C)/(S*2)
79335**
79336** For i between 0 and S-1.  Conceptually, the index space is divided into
79337** S uniform buckets and the samples are the middle row from each bucket.
79338**
79339** The format for sqlite_stat2 is recorded here for legacy reference.  This
79340** version of SQLite does not support sqlite_stat2.  It neither reads nor
79341** writes the sqlite_stat2 table.  This version of SQLite only supports
79342** sqlite_stat3.
79343**
79344** Format for sqlite_stat3:
79345**
79346** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
79347** used to avoid compatibility problems.
79348**
79349** The format of the sqlite_stat3 table is similar to the format of
79350** the sqlite_stat2 table.  There are multiple entries for each index.
79351** The idx column names the index and the tbl column is the table of the
79352** index.  If the idx and tbl columns are the same, then the sample is
79353** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
79354** the left-most column of the index.  The nEq column is the approximate
79355** number of entires in the index whose left-most column exactly matches
79356** the sample.  nLt is the approximate number of entires whose left-most
79357** column is less than the sample.  The nDLt column is the approximate
79358** number of distinct left-most entries in the index that are less than
79359** the sample.
79360**
79361** Future versions of SQLite might change to store a string containing
79362** multiple integers values in the nDLt column of sqlite_stat3.  The first
79363** integer will be the number of prior index entires that are distinct in
79364** the left-most column.  The second integer will be the number of prior index
79365** entries that are distinct in the first two columns.  The third integer
79366** will be the number of prior index entries that are distinct in the first
79367** three columns.  And so forth.  With that extension, the nDLt field is
79368** similar in function to the sqlite_stat1.stat field.
79369**
79370** There can be an arbitrary number of sqlite_stat3 entries per index.
79371** The ANALYZE command will typically generate sqlite_stat3 tables
79372** that contain between 10 and 40 samples which are distributed across
79373** the key space, though not uniformly, and which include samples with
79374** largest possible nEq values.
79375*/
79376#ifndef SQLITE_OMIT_ANALYZE
79377
79378/*
79379** This routine generates code that opens the sqlite_stat1 table for
79380** writing with cursor iStatCur. If the library was built with the
79381** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
79382** opened for writing using cursor (iStatCur+1)
79383**
79384** If the sqlite_stat1 tables does not previously exist, it is created.
79385** Similarly, if the sqlite_stat3 table does not exist and the library
79386** is compiled with SQLITE_ENABLE_STAT3 defined, it is created.
79387**
79388** Argument zWhere may be a pointer to a buffer containing a table name,
79389** or it may be a NULL pointer. If it is not NULL, then all entries in
79390** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
79391** with the named table are deleted. If zWhere==0, then code is generated
79392** to delete all stat table entries.
79393*/
79394static void openStatTable(
79395  Parse *pParse,          /* Parsing context */
79396  int iDb,                /* The database we are looking in */
79397  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
79398  const char *zWhere,     /* Delete entries for this table or index */
79399  const char *zWhereType  /* Either "tbl" or "idx" */
79400){
79401  static const struct {
79402    const char *zName;
79403    const char *zCols;
79404  } aTable[] = {
79405    { "sqlite_stat1", "tbl,idx,stat" },
79406#ifdef SQLITE_ENABLE_STAT3
79407    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
79408#endif
79409  };
79410
79411  int aRoot[] = {0, 0};
79412  u8 aCreateTbl[] = {0, 0};
79413
79414  int i;
79415  sqlite3 *db = pParse->db;
79416  Db *pDb;
79417  Vdbe *v = sqlite3GetVdbe(pParse);
79418  if( v==0 ) return;
79419  assert( sqlite3BtreeHoldsAllMutexes(db) );
79420  assert( sqlite3VdbeDb(v)==db );
79421  pDb = &db->aDb[iDb];
79422
79423  /* Create new statistic tables if they do not exist, or clear them
79424  ** if they do already exist.
79425  */
79426  for(i=0; i<ArraySize(aTable); i++){
79427    const char *zTab = aTable[i].zName;
79428    Table *pStat;
79429    if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
79430      /* The sqlite_stat[12] table does not exist. Create it. Note that a
79431      ** side-effect of the CREATE TABLE statement is to leave the rootpage
79432      ** of the new table in register pParse->regRoot. This is important
79433      ** because the OpenWrite opcode below will be needing it. */
79434      sqlite3NestedParse(pParse,
79435          "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
79436      );
79437      aRoot[i] = pParse->regRoot;
79438      aCreateTbl[i] = 1;
79439    }else{
79440      /* The table already exists. If zWhere is not NULL, delete all entries
79441      ** associated with the table zWhere. If zWhere is NULL, delete the
79442      ** entire contents of the table. */
79443      aRoot[i] = pStat->tnum;
79444      sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
79445      if( zWhere ){
79446        sqlite3NestedParse(pParse,
79447           "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
79448        );
79449      }else{
79450        /* The sqlite_stat[12] table already exists.  Delete all rows. */
79451        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
79452      }
79453    }
79454  }
79455
79456  /* Open the sqlite_stat[13] tables for writing. */
79457  for(i=0; i<ArraySize(aTable); i++){
79458    sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
79459    sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
79460    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
79461  }
79462}
79463
79464/*
79465** Recommended number of samples for sqlite_stat3
79466*/
79467#ifndef SQLITE_STAT3_SAMPLES
79468# define SQLITE_STAT3_SAMPLES 24
79469#endif
79470
79471/*
79472** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
79473** share an instance of the following structure to hold their state
79474** information.
79475*/
79476typedef struct Stat3Accum Stat3Accum;
79477struct Stat3Accum {
79478  tRowcnt nRow;             /* Number of rows in the entire table */
79479  tRowcnt nPSample;         /* How often to do a periodic sample */
79480  int iMin;                 /* Index of entry with minimum nEq and hash */
79481  int mxSample;             /* Maximum number of samples to accumulate */
79482  int nSample;              /* Current number of samples */
79483  u32 iPrn;                 /* Pseudo-random number used for sampling */
79484  struct Stat3Sample {
79485    i64 iRowid;                /* Rowid in main table of the key */
79486    tRowcnt nEq;               /* sqlite_stat3.nEq */
79487    tRowcnt nLt;               /* sqlite_stat3.nLt */
79488    tRowcnt nDLt;              /* sqlite_stat3.nDLt */
79489    u8 isPSample;              /* True if a periodic sample */
79490    u32 iHash;                 /* Tiebreaker hash */
79491  } *a;                     /* An array of samples */
79492};
79493
79494#ifdef SQLITE_ENABLE_STAT3
79495/*
79496** Implementation of the stat3_init(C,S) SQL function.  The two parameters
79497** are the number of rows in the table or index (C) and the number of samples
79498** to accumulate (S).
79499**
79500** This routine allocates the Stat3Accum object.
79501**
79502** The return value is the Stat3Accum object (P).
79503*/
79504static void stat3Init(
79505  sqlite3_context *context,
79506  int argc,
79507  sqlite3_value **argv
79508){
79509  Stat3Accum *p;
79510  tRowcnt nRow;
79511  int mxSample;
79512  int n;
79513
79514  UNUSED_PARAMETER(argc);
79515  nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
79516  mxSample = sqlite3_value_int(argv[1]);
79517  n = sizeof(*p) + sizeof(p->a[0])*mxSample;
79518  p = sqlite3_malloc( n );
79519  if( p==0 ){
79520    sqlite3_result_error_nomem(context);
79521    return;
79522  }
79523  memset(p, 0, n);
79524  p->a = (struct Stat3Sample*)&p[1];
79525  p->nRow = nRow;
79526  p->mxSample = mxSample;
79527  p->nPSample = p->nRow/(mxSample/3+1) + 1;
79528  sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
79529  sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
79530}
79531static const FuncDef stat3InitFuncdef = {
79532  2,                /* nArg */
79533  SQLITE_UTF8,      /* iPrefEnc */
79534  0,                /* flags */
79535  0,                /* pUserData */
79536  0,                /* pNext */
79537  stat3Init,        /* xFunc */
79538  0,                /* xStep */
79539  0,                /* xFinalize */
79540  "stat3_init",     /* zName */
79541  0,                /* pHash */
79542  0                 /* pDestructor */
79543};
79544
79545
79546/*
79547** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
79548** arguments describe a single key instance.  This routine makes the
79549** decision about whether or not to retain this key for the sqlite_stat3
79550** table.
79551**
79552** The return value is NULL.
79553*/
79554static void stat3Push(
79555  sqlite3_context *context,
79556  int argc,
79557  sqlite3_value **argv
79558){
79559  Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
79560  tRowcnt nEq = sqlite3_value_int64(argv[0]);
79561  tRowcnt nLt = sqlite3_value_int64(argv[1]);
79562  tRowcnt nDLt = sqlite3_value_int64(argv[2]);
79563  i64 rowid = sqlite3_value_int64(argv[3]);
79564  u8 isPSample = 0;
79565  u8 doInsert = 0;
79566  int iMin = p->iMin;
79567  struct Stat3Sample *pSample;
79568  int i;
79569  u32 h;
79570
79571  UNUSED_PARAMETER(context);
79572  UNUSED_PARAMETER(argc);
79573  if( nEq==0 ) return;
79574  h = p->iPrn = p->iPrn*1103515245 + 12345;
79575  if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
79576    doInsert = isPSample = 1;
79577  }else if( p->nSample<p->mxSample ){
79578    doInsert = 1;
79579  }else{
79580    if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
79581      doInsert = 1;
79582    }
79583  }
79584  if( !doInsert ) return;
79585  if( p->nSample==p->mxSample ){
79586    assert( p->nSample - iMin - 1 >= 0 );
79587    memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
79588    pSample = &p->a[p->nSample-1];
79589  }else{
79590    pSample = &p->a[p->nSample++];
79591  }
79592  pSample->iRowid = rowid;
79593  pSample->nEq = nEq;
79594  pSample->nLt = nLt;
79595  pSample->nDLt = nDLt;
79596  pSample->iHash = h;
79597  pSample->isPSample = isPSample;
79598
79599  /* Find the new minimum */
79600  if( p->nSample==p->mxSample ){
79601    pSample = p->a;
79602    i = 0;
79603    while( pSample->isPSample ){
79604      i++;
79605      pSample++;
79606      assert( i<p->nSample );
79607    }
79608    nEq = pSample->nEq;
79609    h = pSample->iHash;
79610    iMin = i;
79611    for(i++, pSample++; i<p->nSample; i++, pSample++){
79612      if( pSample->isPSample ) continue;
79613      if( pSample->nEq<nEq
79614       || (pSample->nEq==nEq && pSample->iHash<h)
79615      ){
79616        iMin = i;
79617        nEq = pSample->nEq;
79618        h = pSample->iHash;
79619      }
79620    }
79621    p->iMin = iMin;
79622  }
79623}
79624static const FuncDef stat3PushFuncdef = {
79625  5,                /* nArg */
79626  SQLITE_UTF8,      /* iPrefEnc */
79627  0,                /* flags */
79628  0,                /* pUserData */
79629  0,                /* pNext */
79630  stat3Push,        /* xFunc */
79631  0,                /* xStep */
79632  0,                /* xFinalize */
79633  "stat3_push",     /* zName */
79634  0,                /* pHash */
79635  0                 /* pDestructor */
79636};
79637
79638/*
79639** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
79640** used to query the results.  Content is returned for the Nth sqlite_stat3
79641** row where N is between 0 and S-1 and S is the number of samples.  The
79642** value returned depends on the number of arguments.
79643**
79644**   argc==2    result:  rowid
79645**   argc==3    result:  nEq
79646**   argc==4    result:  nLt
79647**   argc==5    result:  nDLt
79648*/
79649static void stat3Get(
79650  sqlite3_context *context,
79651  int argc,
79652  sqlite3_value **argv
79653){
79654  int n = sqlite3_value_int(argv[1]);
79655  Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
79656
79657  assert( p!=0 );
79658  if( p->nSample<=n ) return;
79659  switch( argc ){
79660    case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
79661    case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
79662    case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
79663    default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
79664  }
79665}
79666static const FuncDef stat3GetFuncdef = {
79667  -1,               /* nArg */
79668  SQLITE_UTF8,      /* iPrefEnc */
79669  0,                /* flags */
79670  0,                /* pUserData */
79671  0,                /* pNext */
79672  stat3Get,         /* xFunc */
79673  0,                /* xStep */
79674  0,                /* xFinalize */
79675  "stat3_get",     /* zName */
79676  0,                /* pHash */
79677  0                 /* pDestructor */
79678};
79679#endif /* SQLITE_ENABLE_STAT3 */
79680
79681
79682
79683
79684/*
79685** Generate code to do an analysis of all indices associated with
79686** a single table.
79687*/
79688static void analyzeOneTable(
79689  Parse *pParse,   /* Parser context */
79690  Table *pTab,     /* Table whose indices are to be analyzed */
79691  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
79692  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
79693  int iMem         /* Available memory locations begin here */
79694){
79695  sqlite3 *db = pParse->db;    /* Database handle */
79696  Index *pIdx;                 /* An index to being analyzed */
79697  int iIdxCur;                 /* Cursor open on index being analyzed */
79698  Vdbe *v;                     /* The virtual machine being built up */
79699  int i;                       /* Loop counter */
79700  int topOfLoop;               /* The top of the loop */
79701  int endOfLoop;               /* The end of the loop */
79702  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
79703  int iDb;                     /* Index of database containing pTab */
79704  int regTabname = iMem++;     /* Register containing table name */
79705  int regIdxname = iMem++;     /* Register containing index name */
79706  int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
79707#ifdef SQLITE_ENABLE_STAT3
79708  int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
79709  int regNumLt = iMem++;       /* Number of keys less than regSample */
79710  int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
79711  int regSample = iMem++;      /* The next sample value */
79712  int regRowid = regSample;    /* Rowid of a sample */
79713  int regAccum = iMem++;       /* Register to hold Stat3Accum object */
79714  int regLoop = iMem++;        /* Loop counter */
79715  int regCount = iMem++;       /* Number of rows in the table or index */
79716  int regTemp1 = iMem++;       /* Intermediate register */
79717  int regTemp2 = iMem++;       /* Intermediate register */
79718  int once = 1;                /* One-time initialization */
79719  int shortJump = 0;           /* Instruction address */
79720  int iTabCur = pParse->nTab++; /* Table cursor */
79721#endif
79722  int regCol = iMem++;         /* Content of a column in analyzed table */
79723  int regRec = iMem++;         /* Register holding completed record */
79724  int regTemp = iMem++;        /* Temporary use register */
79725  int regNewRowid = iMem++;    /* Rowid for the inserted record */
79726
79727
79728  v = sqlite3GetVdbe(pParse);
79729  if( v==0 || NEVER(pTab==0) ){
79730    return;
79731  }
79732  if( pTab->tnum==0 ){
79733    /* Do not gather statistics on views or virtual tables */
79734    return;
79735  }
79736  if( memcmp(pTab->zName, "sqlite_", 7)==0 ){
79737    /* Do not gather statistics on system tables */
79738    return;
79739  }
79740  assert( sqlite3BtreeHoldsAllMutexes(db) );
79741  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
79742  assert( iDb>=0 );
79743  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79744#ifndef SQLITE_OMIT_AUTHORIZATION
79745  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
79746      db->aDb[iDb].zName ) ){
79747    return;
79748  }
79749#endif
79750
79751  /* Establish a read-lock on the table at the shared-cache level. */
79752  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
79753
79754  iIdxCur = pParse->nTab++;
79755  sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
79756  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79757    int nCol;
79758    KeyInfo *pKey;
79759    int addrIfNot = 0;           /* address of OP_IfNot */
79760    int *aChngAddr;              /* Array of jump instruction addresses */
79761
79762    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
79763    VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
79764    nCol = pIdx->nColumn;
79765    aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
79766    if( aChngAddr==0 ) continue;
79767    pKey = sqlite3IndexKeyinfo(pParse, pIdx);
79768    if( iMem+1+(nCol*2)>pParse->nMem ){
79769      pParse->nMem = iMem+1+(nCol*2);
79770    }
79771
79772    /* Open a cursor to the index to be analyzed. */
79773    assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
79774    sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
79775        (char *)pKey, P4_KEYINFO_HANDOFF);
79776    VdbeComment((v, "%s", pIdx->zName));
79777
79778    /* Populate the register containing the index name. */
79779    sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
79780
79781#ifdef SQLITE_ENABLE_STAT3
79782    if( once ){
79783      once = 0;
79784      sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
79785    }
79786    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
79787    sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
79788    sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
79789    sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
79790    sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
79791    sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
79792    sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
79793                      (char*)&stat3InitFuncdef, P4_FUNCDEF);
79794    sqlite3VdbeChangeP5(v, 2);
79795#endif /* SQLITE_ENABLE_STAT3 */
79796
79797    /* The block of memory cells initialized here is used as follows.
79798    **
79799    **    iMem:
79800    **        The total number of rows in the table.
79801    **
79802    **    iMem+1 .. iMem+nCol:
79803    **        Number of distinct entries in index considering the
79804    **        left-most N columns only, where N is between 1 and nCol,
79805    **        inclusive.
79806    **
79807    **    iMem+nCol+1 .. Mem+2*nCol:
79808    **        Previous value of indexed columns, from left to right.
79809    **
79810    ** Cells iMem through iMem+nCol are initialized to 0. The others are
79811    ** initialized to contain an SQL NULL.
79812    */
79813    for(i=0; i<=nCol; i++){
79814      sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
79815    }
79816    for(i=0; i<nCol; i++){
79817      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
79818    }
79819
79820    /* Start the analysis loop. This loop runs through all the entries in
79821    ** the index b-tree.  */
79822    endOfLoop = sqlite3VdbeMakeLabel(v);
79823    sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
79824    topOfLoop = sqlite3VdbeCurrentAddr(v);
79825    sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
79826
79827    for(i=0; i<nCol; i++){
79828      CollSeq *pColl;
79829      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
79830      if( i==0 ){
79831        /* Always record the very first row */
79832        addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
79833      }
79834      assert( pIdx->azColl!=0 );
79835      assert( pIdx->azColl[i]!=0 );
79836      pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
79837      aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
79838                                      (char*)pColl, P4_COLLSEQ);
79839      sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
79840      VdbeComment((v, "jump if column %d changed", i));
79841#ifdef SQLITE_ENABLE_STAT3
79842      if( i==0 ){
79843        sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
79844        VdbeComment((v, "incr repeat count"));
79845      }
79846#endif
79847    }
79848    sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
79849    for(i=0; i<nCol; i++){
79850      sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
79851      if( i==0 ){
79852        sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
79853#ifdef SQLITE_ENABLE_STAT3
79854        sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79855                          (char*)&stat3PushFuncdef, P4_FUNCDEF);
79856        sqlite3VdbeChangeP5(v, 5);
79857        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
79858        sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
79859        sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
79860        sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
79861#endif
79862      }
79863      sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
79864      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
79865    }
79866    sqlite3DbFree(db, aChngAddr);
79867
79868    /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
79869    sqlite3VdbeResolveLabel(v, endOfLoop);
79870
79871    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
79872    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79873#ifdef SQLITE_ENABLE_STAT3
79874    sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
79875                      (char*)&stat3PushFuncdef, P4_FUNCDEF);
79876    sqlite3VdbeChangeP5(v, 5);
79877    sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
79878    shortJump =
79879    sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
79880    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
79881                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
79882    sqlite3VdbeChangeP5(v, 2);
79883    sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
79884    sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
79885    sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
79886    sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
79887    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
79888                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
79889    sqlite3VdbeChangeP5(v, 3);
79890    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
79891                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
79892    sqlite3VdbeChangeP5(v, 4);
79893    sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
79894                      (char*)&stat3GetFuncdef, P4_FUNCDEF);
79895    sqlite3VdbeChangeP5(v, 5);
79896    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
79897    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
79898    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
79899    sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
79900    sqlite3VdbeJumpHere(v, shortJump+2);
79901#endif
79902
79903    /* Store the results in sqlite_stat1.
79904    **
79905    ** The result is a single row of the sqlite_stat1 table.  The first
79906    ** two columns are the names of the table and index.  The third column
79907    ** is a string composed of a list of integer statistics about the
79908    ** index.  The first integer in the list is the total number of entries
79909    ** in the index.  There is one additional integer in the list for each
79910    ** column of the table.  This additional integer is a guess of how many
79911    ** rows of the table the index will select.  If D is the count of distinct
79912    ** values and K is the total number of rows, then the integer is computed
79913    ** as:
79914    **
79915    **        I = (K+D-1)/D
79916    **
79917    ** If K==0 then no entry is made into the sqlite_stat1 table.
79918    ** If K>0 then it is always the case the D>0 so division by zero
79919    ** is never possible.
79920    */
79921    sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
79922    if( jZeroRows<0 ){
79923      jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
79924    }
79925    for(i=0; i<nCol; i++){
79926      sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
79927      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79928      sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
79929      sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
79930      sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
79931      sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
79932      sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
79933    }
79934    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79935    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79936    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79937    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79938  }
79939
79940  /* If the table has no indices, create a single sqlite_stat1 entry
79941  ** containing NULL as the index name and the row count as the content.
79942  */
79943  if( pTab->pIndex==0 ){
79944    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
79945    VdbeComment((v, "%s", pTab->zName));
79946    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
79947    sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
79948    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
79949  }else{
79950    sqlite3VdbeJumpHere(v, jZeroRows);
79951    jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
79952  }
79953  sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
79954  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
79955  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
79956  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
79957  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
79958  if( pParse->nMem<regRec ) pParse->nMem = regRec;
79959  sqlite3VdbeJumpHere(v, jZeroRows);
79960}
79961
79962
79963/*
79964** Generate code that will cause the most recent index analysis to
79965** be loaded into internal hash tables where is can be used.
79966*/
79967static void loadAnalysis(Parse *pParse, int iDb){
79968  Vdbe *v = sqlite3GetVdbe(pParse);
79969  if( v ){
79970    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
79971  }
79972}
79973
79974/*
79975** Generate code that will do an analysis of an entire database
79976*/
79977static void analyzeDatabase(Parse *pParse, int iDb){
79978  sqlite3 *db = pParse->db;
79979  Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
79980  HashElem *k;
79981  int iStatCur;
79982  int iMem;
79983
79984  sqlite3BeginWriteOperation(pParse, 0, iDb);
79985  iStatCur = pParse->nTab;
79986  pParse->nTab += 3;
79987  openStatTable(pParse, iDb, iStatCur, 0, 0);
79988  iMem = pParse->nMem+1;
79989  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
79990  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
79991    Table *pTab = (Table*)sqliteHashData(k);
79992    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
79993  }
79994  loadAnalysis(pParse, iDb);
79995}
79996
79997/*
79998** Generate code that will do an analysis of a single table in
79999** a database.  If pOnlyIdx is not NULL then it is a single index
80000** in pTab that should be analyzed.
80001*/
80002static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
80003  int iDb;
80004  int iStatCur;
80005
80006  assert( pTab!=0 );
80007  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80008  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80009  sqlite3BeginWriteOperation(pParse, 0, iDb);
80010  iStatCur = pParse->nTab;
80011  pParse->nTab += 3;
80012  if( pOnlyIdx ){
80013    openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
80014  }else{
80015    openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
80016  }
80017  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
80018  loadAnalysis(pParse, iDb);
80019}
80020
80021/*
80022** Generate code for the ANALYZE command.  The parser calls this routine
80023** when it recognizes an ANALYZE command.
80024**
80025**        ANALYZE                            -- 1
80026**        ANALYZE  <database>                -- 2
80027**        ANALYZE  ?<database>.?<tablename>  -- 3
80028**
80029** Form 1 causes all indices in all attached databases to be analyzed.
80030** Form 2 analyzes all indices the single database named.
80031** Form 3 analyzes all indices associated with the named table.
80032*/
80033SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
80034  sqlite3 *db = pParse->db;
80035  int iDb;
80036  int i;
80037  char *z, *zDb;
80038  Table *pTab;
80039  Index *pIdx;
80040  Token *pTableName;
80041
80042  /* Read the database schema. If an error occurs, leave an error message
80043  ** and code in pParse and return NULL. */
80044  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80045  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
80046    return;
80047  }
80048
80049  assert( pName2!=0 || pName1==0 );
80050  if( pName1==0 ){
80051    /* Form 1:  Analyze everything */
80052    for(i=0; i<db->nDb; i++){
80053      if( i==1 ) continue;  /* Do not analyze the TEMP database */
80054      analyzeDatabase(pParse, i);
80055    }
80056  }else if( pName2->n==0 ){
80057    /* Form 2:  Analyze the database or table named */
80058    iDb = sqlite3FindDb(db, pName1);
80059    if( iDb>=0 ){
80060      analyzeDatabase(pParse, iDb);
80061    }else{
80062      z = sqlite3NameFromToken(db, pName1);
80063      if( z ){
80064        if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
80065          analyzeTable(pParse, pIdx->pTable, pIdx);
80066        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
80067          analyzeTable(pParse, pTab, 0);
80068        }
80069        sqlite3DbFree(db, z);
80070      }
80071    }
80072  }else{
80073    /* Form 3: Analyze the fully qualified table name */
80074    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
80075    if( iDb>=0 ){
80076      zDb = db->aDb[iDb].zName;
80077      z = sqlite3NameFromToken(db, pTableName);
80078      if( z ){
80079        if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
80080          analyzeTable(pParse, pIdx->pTable, pIdx);
80081        }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
80082          analyzeTable(pParse, pTab, 0);
80083        }
80084        sqlite3DbFree(db, z);
80085      }
80086    }
80087  }
80088}
80089
80090/*
80091** Used to pass information from the analyzer reader through to the
80092** callback routine.
80093*/
80094typedef struct analysisInfo analysisInfo;
80095struct analysisInfo {
80096  sqlite3 *db;
80097  const char *zDatabase;
80098};
80099
80100/*
80101** This callback is invoked once for each index when reading the
80102** sqlite_stat1 table.
80103**
80104**     argv[0] = name of the table
80105**     argv[1] = name of the index (might be NULL)
80106**     argv[2] = results of analysis - on integer for each column
80107**
80108** Entries for which argv[1]==NULL simply record the number of rows in
80109** the table.
80110*/
80111static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
80112  analysisInfo *pInfo = (analysisInfo*)pData;
80113  Index *pIndex;
80114  Table *pTable;
80115  int i, c, n;
80116  tRowcnt v;
80117  const char *z;
80118
80119  assert( argc==3 );
80120  UNUSED_PARAMETER2(NotUsed, argc);
80121
80122  if( argv==0 || argv[0]==0 || argv[2]==0 ){
80123    return 0;
80124  }
80125  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
80126  if( pTable==0 ){
80127    return 0;
80128  }
80129  if( argv[1] ){
80130    pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
80131  }else{
80132    pIndex = 0;
80133  }
80134  n = pIndex ? pIndex->nColumn : 0;
80135  z = argv[2];
80136  for(i=0; *z && i<=n; i++){
80137    v = 0;
80138    while( (c=z[0])>='0' && c<='9' ){
80139      v = v*10 + c - '0';
80140      z++;
80141    }
80142    if( i==0 ) pTable->nRowEst = v;
80143    if( pIndex==0 ) break;
80144    pIndex->aiRowEst[i] = v;
80145    if( *z==' ' ) z++;
80146    if( memcmp(z, "unordered", 10)==0 ){
80147      pIndex->bUnordered = 1;
80148      break;
80149    }
80150  }
80151  return 0;
80152}
80153
80154/*
80155** If the Index.aSample variable is not NULL, delete the aSample[] array
80156** and its contents.
80157*/
80158SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
80159#ifdef SQLITE_ENABLE_STAT3
80160  if( pIdx->aSample ){
80161    int j;
80162    for(j=0; j<pIdx->nSample; j++){
80163      IndexSample *p = &pIdx->aSample[j];
80164      if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
80165        sqlite3DbFree(db, p->u.z);
80166      }
80167    }
80168    sqlite3DbFree(db, pIdx->aSample);
80169  }
80170  if( db && db->pnBytesFreed==0 ){
80171    pIdx->nSample = 0;
80172    pIdx->aSample = 0;
80173  }
80174#else
80175  UNUSED_PARAMETER(db);
80176  UNUSED_PARAMETER(pIdx);
80177#endif
80178}
80179
80180#ifdef SQLITE_ENABLE_STAT3
80181/*
80182** Load content from the sqlite_stat3 table into the Index.aSample[]
80183** arrays of all indices.
80184*/
80185static int loadStat3(sqlite3 *db, const char *zDb){
80186  int rc;                       /* Result codes from subroutines */
80187  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
80188  char *zSql;                   /* Text of the SQL statement */
80189  Index *pPrevIdx = 0;          /* Previous index in the loop */
80190  int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
80191  int eType;                    /* Datatype of a sample */
80192  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
80193
80194  assert( db->lookaside.bEnabled==0 );
80195  if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
80196    return SQLITE_OK;
80197  }
80198
80199  zSql = sqlite3MPrintf(db,
80200      "SELECT idx,count(*) FROM %Q.sqlite_stat3"
80201      " GROUP BY idx", zDb);
80202  if( !zSql ){
80203    return SQLITE_NOMEM;
80204  }
80205  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
80206  sqlite3DbFree(db, zSql);
80207  if( rc ) return rc;
80208
80209  while( sqlite3_step(pStmt)==SQLITE_ROW ){
80210    char *zIndex;   /* Index name */
80211    Index *pIdx;    /* Pointer to the index object */
80212    int nSample;    /* Number of samples */
80213
80214    zIndex = (char *)sqlite3_column_text(pStmt, 0);
80215    if( zIndex==0 ) continue;
80216    nSample = sqlite3_column_int(pStmt, 1);
80217    pIdx = sqlite3FindIndex(db, zIndex, zDb);
80218    if( pIdx==0 ) continue;
80219    assert( pIdx->nSample==0 );
80220    pIdx->nSample = nSample;
80221    pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
80222    pIdx->avgEq = pIdx->aiRowEst[1];
80223    if( pIdx->aSample==0 ){
80224      db->mallocFailed = 1;
80225      sqlite3_finalize(pStmt);
80226      return SQLITE_NOMEM;
80227    }
80228  }
80229  rc = sqlite3_finalize(pStmt);
80230  if( rc ) return rc;
80231
80232  zSql = sqlite3MPrintf(db,
80233      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
80234  if( !zSql ){
80235    return SQLITE_NOMEM;
80236  }
80237  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
80238  sqlite3DbFree(db, zSql);
80239  if( rc ) return rc;
80240
80241  while( sqlite3_step(pStmt)==SQLITE_ROW ){
80242    char *zIndex;   /* Index name */
80243    Index *pIdx;    /* Pointer to the index object */
80244    int i;          /* Loop counter */
80245    tRowcnt sumEq;  /* Sum of the nEq values */
80246
80247    zIndex = (char *)sqlite3_column_text(pStmt, 0);
80248    if( zIndex==0 ) continue;
80249    pIdx = sqlite3FindIndex(db, zIndex, zDb);
80250    if( pIdx==0 ) continue;
80251    if( pIdx==pPrevIdx ){
80252      idx++;
80253    }else{
80254      pPrevIdx = pIdx;
80255      idx = 0;
80256    }
80257    assert( idx<pIdx->nSample );
80258    pSample = &pIdx->aSample[idx];
80259    pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
80260    pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
80261    pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
80262    if( idx==pIdx->nSample-1 ){
80263      if( pSample->nDLt>0 ){
80264        for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
80265        pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
80266      }
80267      if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
80268    }
80269    eType = sqlite3_column_type(pStmt, 4);
80270    pSample->eType = (u8)eType;
80271    switch( eType ){
80272      case SQLITE_INTEGER: {
80273        pSample->u.i = sqlite3_column_int64(pStmt, 4);
80274        break;
80275      }
80276      case SQLITE_FLOAT: {
80277        pSample->u.r = sqlite3_column_double(pStmt, 4);
80278        break;
80279      }
80280      case SQLITE_NULL: {
80281        break;
80282      }
80283      default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
80284        const char *z = (const char *)(
80285              (eType==SQLITE_BLOB) ?
80286              sqlite3_column_blob(pStmt, 4):
80287              sqlite3_column_text(pStmt, 4)
80288           );
80289        int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
80290        pSample->nByte = n;
80291        if( n < 1){
80292          pSample->u.z = 0;
80293        }else{
80294          pSample->u.z = sqlite3DbMallocRaw(db, n);
80295          if( pSample->u.z==0 ){
80296            db->mallocFailed = 1;
80297            sqlite3_finalize(pStmt);
80298            return SQLITE_NOMEM;
80299          }
80300          memcpy(pSample->u.z, z, n);
80301        }
80302      }
80303    }
80304  }
80305  return sqlite3_finalize(pStmt);
80306}
80307#endif /* SQLITE_ENABLE_STAT3 */
80308
80309/*
80310** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
80311** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
80312** arrays. The contents of sqlite_stat3 are used to populate the
80313** Index.aSample[] arrays.
80314**
80315** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
80316** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined
80317** during compilation and the sqlite_stat3 table is present, no data is
80318** read from it.
80319**
80320** If SQLITE_ENABLE_STAT3 was defined during compilation and the
80321** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
80322** returned. However, in this case, data is read from the sqlite_stat1
80323** table (if it is present) before returning.
80324**
80325** If an OOM error occurs, this function always sets db->mallocFailed.
80326** This means if the caller does not care about other errors, the return
80327** code may be ignored.
80328*/
80329SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
80330  analysisInfo sInfo;
80331  HashElem *i;
80332  char *zSql;
80333  int rc;
80334
80335  assert( iDb>=0 && iDb<db->nDb );
80336  assert( db->aDb[iDb].pBt!=0 );
80337
80338  /* Clear any prior statistics */
80339  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80340  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
80341    Index *pIdx = sqliteHashData(i);
80342    sqlite3DefaultRowEst(pIdx);
80343#ifdef SQLITE_ENABLE_STAT3
80344    sqlite3DeleteIndexSamples(db, pIdx);
80345    pIdx->aSample = 0;
80346#endif
80347  }
80348
80349  /* Check to make sure the sqlite_stat1 table exists */
80350  sInfo.db = db;
80351  sInfo.zDatabase = db->aDb[iDb].zName;
80352  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
80353    return SQLITE_ERROR;
80354  }
80355
80356  /* Load new statistics out of the sqlite_stat1 table */
80357  zSql = sqlite3MPrintf(db,
80358      "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
80359  if( zSql==0 ){
80360    rc = SQLITE_NOMEM;
80361  }else{
80362    rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
80363    sqlite3DbFree(db, zSql);
80364  }
80365
80366
80367  /* Load the statistics from the sqlite_stat3 table. */
80368#ifdef SQLITE_ENABLE_STAT3
80369  if( rc==SQLITE_OK ){
80370    int lookasideEnabled = db->lookaside.bEnabled;
80371    db->lookaside.bEnabled = 0;
80372    rc = loadStat3(db, sInfo.zDatabase);
80373    db->lookaside.bEnabled = lookasideEnabled;
80374  }
80375#endif
80376
80377  if( rc==SQLITE_NOMEM ){
80378    db->mallocFailed = 1;
80379  }
80380  return rc;
80381}
80382
80383
80384#endif /* SQLITE_OMIT_ANALYZE */
80385
80386/************** End of analyze.c *********************************************/
80387/************** Begin file attach.c ******************************************/
80388/*
80389** 2003 April 6
80390**
80391** The author disclaims copyright to this source code.  In place of
80392** a legal notice, here is a blessing:
80393**
80394**    May you do good and not evil.
80395**    May you find forgiveness for yourself and forgive others.
80396**    May you share freely, never taking more than you give.
80397**
80398*************************************************************************
80399** This file contains code used to implement the ATTACH and DETACH commands.
80400*/
80401
80402#ifndef SQLITE_OMIT_ATTACH
80403/*
80404** Resolve an expression that was part of an ATTACH or DETACH statement. This
80405** is slightly different from resolving a normal SQL expression, because simple
80406** identifiers are treated as strings, not possible column names or aliases.
80407**
80408** i.e. if the parser sees:
80409**
80410**     ATTACH DATABASE abc AS def
80411**
80412** it treats the two expressions as literal strings 'abc' and 'def' instead of
80413** looking for columns of the same name.
80414**
80415** This only applies to the root node of pExpr, so the statement:
80416**
80417**     ATTACH DATABASE abc||def AS 'db2'
80418**
80419** will fail because neither abc or def can be resolved.
80420*/
80421static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
80422{
80423  int rc = SQLITE_OK;
80424  if( pExpr ){
80425    if( pExpr->op!=TK_ID ){
80426      rc = sqlite3ResolveExprNames(pName, pExpr);
80427      if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
80428        sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
80429        return SQLITE_ERROR;
80430      }
80431    }else{
80432      pExpr->op = TK_STRING;
80433    }
80434  }
80435  return rc;
80436}
80437
80438/*
80439** An SQL user-function registered to do the work of an ATTACH statement. The
80440** three arguments to the function come directly from an attach statement:
80441**
80442**     ATTACH DATABASE x AS y KEY z
80443**
80444**     SELECT sqlite_attach(x, y, z)
80445**
80446** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
80447** third argument.
80448*/
80449static void attachFunc(
80450  sqlite3_context *context,
80451  int NotUsed,
80452  sqlite3_value **argv
80453){
80454  int i;
80455  int rc = 0;
80456  sqlite3 *db = sqlite3_context_db_handle(context);
80457  const char *zName;
80458  const char *zFile;
80459  char *zPath = 0;
80460  char *zErr = 0;
80461  unsigned int flags;
80462  Db *aNew;
80463  char *zErrDyn = 0;
80464  sqlite3_vfs *pVfs;
80465
80466  UNUSED_PARAMETER(NotUsed);
80467
80468  zFile = (const char *)sqlite3_value_text(argv[0]);
80469  zName = (const char *)sqlite3_value_text(argv[1]);
80470  if( zFile==0 ) zFile = "";
80471  if( zName==0 ) zName = "";
80472
80473  /* Check for the following errors:
80474  **
80475  **     * Too many attached databases,
80476  **     * Transaction currently open
80477  **     * Specified database name already being used.
80478  */
80479  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
80480    zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
80481      db->aLimit[SQLITE_LIMIT_ATTACHED]
80482    );
80483    goto attach_error;
80484  }
80485  if( !db->autoCommit ){
80486    zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
80487    goto attach_error;
80488  }
80489  for(i=0; i<db->nDb; i++){
80490    char *z = db->aDb[i].zName;
80491    assert( z && zName );
80492    if( sqlite3StrICmp(z, zName)==0 ){
80493      zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
80494      goto attach_error;
80495    }
80496  }
80497
80498  /* Allocate the new entry in the db->aDb[] array and initialise the schema
80499  ** hash tables.
80500  */
80501  if( db->aDb==db->aDbStatic ){
80502    aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
80503    if( aNew==0 ) return;
80504    memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
80505  }else{
80506    aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
80507    if( aNew==0 ) return;
80508  }
80509  db->aDb = aNew;
80510  aNew = &db->aDb[db->nDb];
80511  memset(aNew, 0, sizeof(*aNew));
80512
80513  /* Open the database file. If the btree is successfully opened, use
80514  ** it to obtain the database schema. At this point the schema may
80515  ** or may not be initialised.
80516  */
80517  flags = db->openFlags;
80518  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
80519  if( rc!=SQLITE_OK ){
80520    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
80521    sqlite3_result_error(context, zErr, -1);
80522    sqlite3_free(zErr);
80523    return;
80524  }
80525  assert( pVfs );
80526  flags |= SQLITE_OPEN_MAIN_DB;
80527  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
80528  sqlite3_free( zPath );
80529  db->nDb++;
80530  if( rc==SQLITE_CONSTRAINT ){
80531    rc = SQLITE_ERROR;
80532    zErrDyn = sqlite3MPrintf(db, "database is already attached");
80533  }else if( rc==SQLITE_OK ){
80534    Pager *pPager;
80535    aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
80536    if( !aNew->pSchema ){
80537      rc = SQLITE_NOMEM;
80538    }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
80539      zErrDyn = sqlite3MPrintf(db,
80540        "attached databases must use the same text encoding as main database");
80541      rc = SQLITE_ERROR;
80542    }
80543    pPager = sqlite3BtreePager(aNew->pBt);
80544    sqlite3PagerLockingMode(pPager, db->dfltLockMode);
80545    sqlite3BtreeSecureDelete(aNew->pBt,
80546                             sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
80547  }
80548  aNew->safety_level = 3;
80549  aNew->zName = sqlite3DbStrDup(db, zName);
80550  if( rc==SQLITE_OK && aNew->zName==0 ){
80551    rc = SQLITE_NOMEM;
80552  }
80553
80554
80555#ifdef SQLITE_HAS_CODEC
80556  if( rc==SQLITE_OK ){
80557    extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
80558    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
80559    int nKey;
80560    char *zKey;
80561    int t = sqlite3_value_type(argv[2]);
80562    switch( t ){
80563      case SQLITE_INTEGER:
80564      case SQLITE_FLOAT:
80565        zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
80566        rc = SQLITE_ERROR;
80567        break;
80568
80569      case SQLITE_TEXT:
80570      case SQLITE_BLOB:
80571        nKey = sqlite3_value_bytes(argv[2]);
80572        zKey = (char *)sqlite3_value_blob(argv[2]);
80573        rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80574        break;
80575
80576      case SQLITE_NULL:
80577        /* No key specified.  Use the key from the main database */
80578        sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
80579        if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
80580          rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
80581        }
80582        break;
80583    }
80584  }
80585#endif
80586
80587  /* If the file was opened successfully, read the schema for the new database.
80588  ** If this fails, or if opening the file failed, then close the file and
80589  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
80590  ** we found it.
80591  */
80592  if( rc==SQLITE_OK ){
80593    sqlite3BtreeEnterAll(db);
80594    rc = sqlite3Init(db, &zErrDyn);
80595    sqlite3BtreeLeaveAll(db);
80596  }
80597  if( rc ){
80598    int iDb = db->nDb - 1;
80599    assert( iDb>=2 );
80600    if( db->aDb[iDb].pBt ){
80601      sqlite3BtreeClose(db->aDb[iDb].pBt);
80602      db->aDb[iDb].pBt = 0;
80603      db->aDb[iDb].pSchema = 0;
80604    }
80605    sqlite3ResetInternalSchema(db, -1);
80606    db->nDb = iDb;
80607    if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
80608      db->mallocFailed = 1;
80609      sqlite3DbFree(db, zErrDyn);
80610      zErrDyn = sqlite3MPrintf(db, "out of memory");
80611    }else if( zErrDyn==0 ){
80612      zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
80613    }
80614    goto attach_error;
80615  }
80616
80617  return;
80618
80619attach_error:
80620  /* Return an error if we get here */
80621  if( zErrDyn ){
80622    sqlite3_result_error(context, zErrDyn, -1);
80623    sqlite3DbFree(db, zErrDyn);
80624  }
80625  if( rc ) sqlite3_result_error_code(context, rc);
80626}
80627
80628/*
80629** An SQL user-function registered to do the work of an DETACH statement. The
80630** three arguments to the function come directly from a detach statement:
80631**
80632**     DETACH DATABASE x
80633**
80634**     SELECT sqlite_detach(x)
80635*/
80636static void detachFunc(
80637  sqlite3_context *context,
80638  int NotUsed,
80639  sqlite3_value **argv
80640){
80641  const char *zName = (const char *)sqlite3_value_text(argv[0]);
80642  sqlite3 *db = sqlite3_context_db_handle(context);
80643  int i;
80644  Db *pDb = 0;
80645  char zErr[128];
80646
80647  UNUSED_PARAMETER(NotUsed);
80648
80649  if( zName==0 ) zName = "";
80650  for(i=0; i<db->nDb; i++){
80651    pDb = &db->aDb[i];
80652    if( pDb->pBt==0 ) continue;
80653    if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
80654  }
80655
80656  if( i>=db->nDb ){
80657    sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
80658    goto detach_error;
80659  }
80660  if( i<2 ){
80661    sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
80662    goto detach_error;
80663  }
80664  if( !db->autoCommit ){
80665    sqlite3_snprintf(sizeof(zErr), zErr,
80666                     "cannot DETACH database within transaction");
80667    goto detach_error;
80668  }
80669  if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
80670    sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
80671    goto detach_error;
80672  }
80673
80674  sqlite3BtreeClose(pDb->pBt);
80675  pDb->pBt = 0;
80676  pDb->pSchema = 0;
80677  sqlite3ResetInternalSchema(db, -1);
80678  return;
80679
80680detach_error:
80681  sqlite3_result_error(context, zErr, -1);
80682}
80683
80684/*
80685** This procedure generates VDBE code for a single invocation of either the
80686** sqlite_detach() or sqlite_attach() SQL user functions.
80687*/
80688static void codeAttach(
80689  Parse *pParse,       /* The parser context */
80690  int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
80691  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
80692  Expr *pAuthArg,      /* Expression to pass to authorization callback */
80693  Expr *pFilename,     /* Name of database file */
80694  Expr *pDbname,       /* Name of the database to use internally */
80695  Expr *pKey           /* Database key for encryption extension */
80696){
80697  int rc;
80698  NameContext sName;
80699  Vdbe *v;
80700  sqlite3* db = pParse->db;
80701  int regArgs;
80702
80703  memset(&sName, 0, sizeof(NameContext));
80704  sName.pParse = pParse;
80705
80706  if(
80707      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
80708      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
80709      SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
80710  ){
80711    pParse->nErr++;
80712    goto attach_end;
80713  }
80714
80715#ifndef SQLITE_OMIT_AUTHORIZATION
80716  if( pAuthArg ){
80717    char *zAuthArg;
80718    if( pAuthArg->op==TK_STRING ){
80719      zAuthArg = pAuthArg->u.zToken;
80720    }else{
80721      zAuthArg = 0;
80722    }
80723    rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
80724    if(rc!=SQLITE_OK ){
80725      goto attach_end;
80726    }
80727  }
80728#endif /* SQLITE_OMIT_AUTHORIZATION */
80729
80730
80731  v = sqlite3GetVdbe(pParse);
80732  regArgs = sqlite3GetTempRange(pParse, 4);
80733  sqlite3ExprCode(pParse, pFilename, regArgs);
80734  sqlite3ExprCode(pParse, pDbname, regArgs+1);
80735  sqlite3ExprCode(pParse, pKey, regArgs+2);
80736
80737  assert( v || db->mallocFailed );
80738  if( v ){
80739    sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
80740    assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
80741    sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
80742    sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
80743
80744    /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
80745    ** statement only). For DETACH, set it to false (expire all existing
80746    ** statements).
80747    */
80748    sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
80749  }
80750
80751attach_end:
80752  sqlite3ExprDelete(db, pFilename);
80753  sqlite3ExprDelete(db, pDbname);
80754  sqlite3ExprDelete(db, pKey);
80755}
80756
80757/*
80758** Called by the parser to compile a DETACH statement.
80759**
80760**     DETACH pDbname
80761*/
80762SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
80763  static const FuncDef detach_func = {
80764    1,                /* nArg */
80765    SQLITE_UTF8,      /* iPrefEnc */
80766    0,                /* flags */
80767    0,                /* pUserData */
80768    0,                /* pNext */
80769    detachFunc,       /* xFunc */
80770    0,                /* xStep */
80771    0,                /* xFinalize */
80772    "sqlite_detach",  /* zName */
80773    0,                /* pHash */
80774    0                 /* pDestructor */
80775  };
80776  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
80777}
80778
80779/*
80780** Called by the parser to compile an ATTACH statement.
80781**
80782**     ATTACH p AS pDbname KEY pKey
80783*/
80784SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
80785  static const FuncDef attach_func = {
80786    3,                /* nArg */
80787    SQLITE_UTF8,      /* iPrefEnc */
80788    0,                /* flags */
80789    0,                /* pUserData */
80790    0,                /* pNext */
80791    attachFunc,       /* xFunc */
80792    0,                /* xStep */
80793    0,                /* xFinalize */
80794    "sqlite_attach",  /* zName */
80795    0,                /* pHash */
80796    0                 /* pDestructor */
80797  };
80798  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
80799}
80800#endif /* SQLITE_OMIT_ATTACH */
80801
80802/*
80803** Initialize a DbFixer structure.  This routine must be called prior
80804** to passing the structure to one of the sqliteFixAAAA() routines below.
80805**
80806** The return value indicates whether or not fixation is required.  TRUE
80807** means we do need to fix the database references, FALSE means we do not.
80808*/
80809SQLITE_PRIVATE int sqlite3FixInit(
80810  DbFixer *pFix,      /* The fixer to be initialized */
80811  Parse *pParse,      /* Error messages will be written here */
80812  int iDb,            /* This is the database that must be used */
80813  const char *zType,  /* "view", "trigger", or "index" */
80814  const Token *pName  /* Name of the view, trigger, or index */
80815){
80816  sqlite3 *db;
80817
80818  if( NEVER(iDb<0) || iDb==1 ) return 0;
80819  db = pParse->db;
80820  assert( db->nDb>iDb );
80821  pFix->pParse = pParse;
80822  pFix->zDb = db->aDb[iDb].zName;
80823  pFix->zType = zType;
80824  pFix->pName = pName;
80825  return 1;
80826}
80827
80828/*
80829** The following set of routines walk through the parse tree and assign
80830** a specific database to all table references where the database name
80831** was left unspecified in the original SQL statement.  The pFix structure
80832** must have been initialized by a prior call to sqlite3FixInit().
80833**
80834** These routines are used to make sure that an index, trigger, or
80835** view in one database does not refer to objects in a different database.
80836** (Exception: indices, triggers, and views in the TEMP database are
80837** allowed to refer to anything.)  If a reference is explicitly made
80838** to an object in a different database, an error message is added to
80839** pParse->zErrMsg and these routines return non-zero.  If everything
80840** checks out, these routines return 0.
80841*/
80842SQLITE_PRIVATE int sqlite3FixSrcList(
80843  DbFixer *pFix,       /* Context of the fixation */
80844  SrcList *pList       /* The Source list to check and modify */
80845){
80846  int i;
80847  const char *zDb;
80848  struct SrcList_item *pItem;
80849
80850  if( NEVER(pList==0) ) return 0;
80851  zDb = pFix->zDb;
80852  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
80853    if( pItem->zDatabase==0 ){
80854      pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
80855    }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
80856      sqlite3ErrorMsg(pFix->pParse,
80857         "%s %T cannot reference objects in database %s",
80858         pFix->zType, pFix->pName, pItem->zDatabase);
80859      return 1;
80860    }
80861#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80862    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
80863    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
80864#endif
80865  }
80866  return 0;
80867}
80868#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
80869SQLITE_PRIVATE int sqlite3FixSelect(
80870  DbFixer *pFix,       /* Context of the fixation */
80871  Select *pSelect      /* The SELECT statement to be fixed to one database */
80872){
80873  while( pSelect ){
80874    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
80875      return 1;
80876    }
80877    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
80878      return 1;
80879    }
80880    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
80881      return 1;
80882    }
80883    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
80884      return 1;
80885    }
80886    pSelect = pSelect->pPrior;
80887  }
80888  return 0;
80889}
80890SQLITE_PRIVATE int sqlite3FixExpr(
80891  DbFixer *pFix,     /* Context of the fixation */
80892  Expr *pExpr        /* The expression to be fixed to one database */
80893){
80894  while( pExpr ){
80895    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
80896    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80897      if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
80898    }else{
80899      if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
80900    }
80901    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
80902      return 1;
80903    }
80904    pExpr = pExpr->pLeft;
80905  }
80906  return 0;
80907}
80908SQLITE_PRIVATE int sqlite3FixExprList(
80909  DbFixer *pFix,     /* Context of the fixation */
80910  ExprList *pList    /* The expression to be fixed to one database */
80911){
80912  int i;
80913  struct ExprList_item *pItem;
80914  if( pList==0 ) return 0;
80915  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
80916    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
80917      return 1;
80918    }
80919  }
80920  return 0;
80921}
80922#endif
80923
80924#ifndef SQLITE_OMIT_TRIGGER
80925SQLITE_PRIVATE int sqlite3FixTriggerStep(
80926  DbFixer *pFix,     /* Context of the fixation */
80927  TriggerStep *pStep /* The trigger step be fixed to one database */
80928){
80929  while( pStep ){
80930    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
80931      return 1;
80932    }
80933    if( sqlite3FixExpr(pFix, pStep->pWhere) ){
80934      return 1;
80935    }
80936    if( sqlite3FixExprList(pFix, pStep->pExprList) ){
80937      return 1;
80938    }
80939    pStep = pStep->pNext;
80940  }
80941  return 0;
80942}
80943#endif
80944
80945/************** End of attach.c **********************************************/
80946/************** Begin file auth.c ********************************************/
80947/*
80948** 2003 January 11
80949**
80950** The author disclaims copyright to this source code.  In place of
80951** a legal notice, here is a blessing:
80952**
80953**    May you do good and not evil.
80954**    May you find forgiveness for yourself and forgive others.
80955**    May you share freely, never taking more than you give.
80956**
80957*************************************************************************
80958** This file contains code used to implement the sqlite3_set_authorizer()
80959** API.  This facility is an optional feature of the library.  Embedded
80960** systems that do not need this facility may omit it by recompiling
80961** the library with -DSQLITE_OMIT_AUTHORIZATION=1
80962*/
80963
80964/*
80965** All of the code in this file may be omitted by defining a single
80966** macro.
80967*/
80968#ifndef SQLITE_OMIT_AUTHORIZATION
80969
80970/*
80971** Set or clear the access authorization function.
80972**
80973** The access authorization function is be called during the compilation
80974** phase to verify that the user has read and/or write access permission on
80975** various fields of the database.  The first argument to the auth function
80976** is a copy of the 3rd argument to this routine.  The second argument
80977** to the auth function is one of these constants:
80978**
80979**       SQLITE_CREATE_INDEX
80980**       SQLITE_CREATE_TABLE
80981**       SQLITE_CREATE_TEMP_INDEX
80982**       SQLITE_CREATE_TEMP_TABLE
80983**       SQLITE_CREATE_TEMP_TRIGGER
80984**       SQLITE_CREATE_TEMP_VIEW
80985**       SQLITE_CREATE_TRIGGER
80986**       SQLITE_CREATE_VIEW
80987**       SQLITE_DELETE
80988**       SQLITE_DROP_INDEX
80989**       SQLITE_DROP_TABLE
80990**       SQLITE_DROP_TEMP_INDEX
80991**       SQLITE_DROP_TEMP_TABLE
80992**       SQLITE_DROP_TEMP_TRIGGER
80993**       SQLITE_DROP_TEMP_VIEW
80994**       SQLITE_DROP_TRIGGER
80995**       SQLITE_DROP_VIEW
80996**       SQLITE_INSERT
80997**       SQLITE_PRAGMA
80998**       SQLITE_READ
80999**       SQLITE_SELECT
81000**       SQLITE_TRANSACTION
81001**       SQLITE_UPDATE
81002**
81003** The third and fourth arguments to the auth function are the name of
81004** the table and the column that are being accessed.  The auth function
81005** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
81006** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
81007** means that the SQL statement will never-run - the sqlite3_exec() call
81008** will return with an error.  SQLITE_IGNORE means that the SQL statement
81009** should run but attempts to read the specified column will return NULL
81010** and attempts to write the column will be ignored.
81011**
81012** Setting the auth function to NULL disables this hook.  The default
81013** setting of the auth function is NULL.
81014*/
81015SQLITE_API int sqlite3_set_authorizer(
81016  sqlite3 *db,
81017  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
81018  void *pArg
81019){
81020  sqlite3_mutex_enter(db->mutex);
81021  db->xAuth = xAuth;
81022  db->pAuthArg = pArg;
81023  sqlite3ExpirePreparedStatements(db);
81024  sqlite3_mutex_leave(db->mutex);
81025  return SQLITE_OK;
81026}
81027
81028/*
81029** Write an error message into pParse->zErrMsg that explains that the
81030** user-supplied authorization function returned an illegal value.
81031*/
81032static void sqliteAuthBadReturnCode(Parse *pParse){
81033  sqlite3ErrorMsg(pParse, "authorizer malfunction");
81034  pParse->rc = SQLITE_ERROR;
81035}
81036
81037/*
81038** Invoke the authorization callback for permission to read column zCol from
81039** table zTab in database zDb. This function assumes that an authorization
81040** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
81041**
81042** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
81043** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
81044** is treated as SQLITE_DENY. In this case an error is left in pParse.
81045*/
81046SQLITE_PRIVATE int sqlite3AuthReadCol(
81047  Parse *pParse,                  /* The parser context */
81048  const char *zTab,               /* Table name */
81049  const char *zCol,               /* Column name */
81050  int iDb                         /* Index of containing database. */
81051){
81052  sqlite3 *db = pParse->db;       /* Database handle */
81053  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
81054  int rc;                         /* Auth callback return code */
81055
81056  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
81057  if( rc==SQLITE_DENY ){
81058    if( db->nDb>2 || iDb!=0 ){
81059      sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
81060    }else{
81061      sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
81062    }
81063    pParse->rc = SQLITE_AUTH;
81064  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
81065    sqliteAuthBadReturnCode(pParse);
81066  }
81067  return rc;
81068}
81069
81070/*
81071** The pExpr should be a TK_COLUMN expression.  The table referred to
81072** is in pTabList or else it is the NEW or OLD table of a trigger.
81073** Check to see if it is OK to read this particular column.
81074**
81075** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
81076** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
81077** then generate an error.
81078*/
81079SQLITE_PRIVATE void sqlite3AuthRead(
81080  Parse *pParse,        /* The parser context */
81081  Expr *pExpr,          /* The expression to check authorization on */
81082  Schema *pSchema,      /* The schema of the expression */
81083  SrcList *pTabList     /* All table that pExpr might refer to */
81084){
81085  sqlite3 *db = pParse->db;
81086  Table *pTab = 0;      /* The table being read */
81087  const char *zCol;     /* Name of the column of the table */
81088  int iSrc;             /* Index in pTabList->a[] of table being read */
81089  int iDb;              /* The index of the database the expression refers to */
81090  int iCol;             /* Index of column in table */
81091
81092  if( db->xAuth==0 ) return;
81093  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
81094  if( iDb<0 ){
81095    /* An attempt to read a column out of a subquery or other
81096    ** temporary table. */
81097    return;
81098  }
81099
81100  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
81101  if( pExpr->op==TK_TRIGGER ){
81102    pTab = pParse->pTriggerTab;
81103  }else{
81104    assert( pTabList );
81105    for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
81106      if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
81107        pTab = pTabList->a[iSrc].pTab;
81108        break;
81109      }
81110    }
81111  }
81112  iCol = pExpr->iColumn;
81113  if( NEVER(pTab==0) ) return;
81114
81115  if( iCol>=0 ){
81116    assert( iCol<pTab->nCol );
81117    zCol = pTab->aCol[iCol].zName;
81118  }else if( pTab->iPKey>=0 ){
81119    assert( pTab->iPKey<pTab->nCol );
81120    zCol = pTab->aCol[pTab->iPKey].zName;
81121  }else{
81122    zCol = "ROWID";
81123  }
81124  assert( iDb>=0 && iDb<db->nDb );
81125  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
81126    pExpr->op = TK_NULL;
81127  }
81128}
81129
81130/*
81131** Do an authorization check using the code and arguments given.  Return
81132** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
81133** is returned, then the error count and error message in pParse are
81134** modified appropriately.
81135*/
81136SQLITE_PRIVATE int sqlite3AuthCheck(
81137  Parse *pParse,
81138  int code,
81139  const char *zArg1,
81140  const char *zArg2,
81141  const char *zArg3
81142){
81143  sqlite3 *db = pParse->db;
81144  int rc;
81145
81146  /* Don't do any authorization checks if the database is initialising
81147  ** or if the parser is being invoked from within sqlite3_declare_vtab.
81148  */
81149  if( db->init.busy || IN_DECLARE_VTAB ){
81150    return SQLITE_OK;
81151  }
81152
81153  if( db->xAuth==0 ){
81154    return SQLITE_OK;
81155  }
81156  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
81157  if( rc==SQLITE_DENY ){
81158    sqlite3ErrorMsg(pParse, "not authorized");
81159    pParse->rc = SQLITE_AUTH;
81160  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
81161    rc = SQLITE_DENY;
81162    sqliteAuthBadReturnCode(pParse);
81163  }
81164  return rc;
81165}
81166
81167/*
81168** Push an authorization context.  After this routine is called, the
81169** zArg3 argument to authorization callbacks will be zContext until
81170** popped.  Or if pParse==0, this routine is a no-op.
81171*/
81172SQLITE_PRIVATE void sqlite3AuthContextPush(
81173  Parse *pParse,
81174  AuthContext *pContext,
81175  const char *zContext
81176){
81177  assert( pParse );
81178  pContext->pParse = pParse;
81179  pContext->zAuthContext = pParse->zAuthContext;
81180  pParse->zAuthContext = zContext;
81181}
81182
81183/*
81184** Pop an authorization context that was previously pushed
81185** by sqlite3AuthContextPush
81186*/
81187SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
81188  if( pContext->pParse ){
81189    pContext->pParse->zAuthContext = pContext->zAuthContext;
81190    pContext->pParse = 0;
81191  }
81192}
81193
81194#endif /* SQLITE_OMIT_AUTHORIZATION */
81195
81196/************** End of auth.c ************************************************/
81197/************** Begin file build.c *******************************************/
81198/*
81199** 2001 September 15
81200**
81201** The author disclaims copyright to this source code.  In place of
81202** a legal notice, here is a blessing:
81203**
81204**    May you do good and not evil.
81205**    May you find forgiveness for yourself and forgive others.
81206**    May you share freely, never taking more than you give.
81207**
81208*************************************************************************
81209** This file contains C code routines that are called by the SQLite parser
81210** when syntax rules are reduced.  The routines in this file handle the
81211** following kinds of SQL syntax:
81212**
81213**     CREATE TABLE
81214**     DROP TABLE
81215**     CREATE INDEX
81216**     DROP INDEX
81217**     creating ID lists
81218**     BEGIN TRANSACTION
81219**     COMMIT
81220**     ROLLBACK
81221*/
81222
81223/*
81224** This routine is called when a new SQL statement is beginning to
81225** be parsed.  Initialize the pParse structure as needed.
81226*/
81227SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
81228  pParse->explain = (u8)explainFlag;
81229  pParse->nVar = 0;
81230}
81231
81232#ifndef SQLITE_OMIT_SHARED_CACHE
81233/*
81234** The TableLock structure is only used by the sqlite3TableLock() and
81235** codeTableLocks() functions.
81236*/
81237struct TableLock {
81238  int iDb;             /* The database containing the table to be locked */
81239  int iTab;            /* The root page of the table to be locked */
81240  u8 isWriteLock;      /* True for write lock.  False for a read lock */
81241  const char *zName;   /* Name of the table */
81242};
81243
81244/*
81245** Record the fact that we want to lock a table at run-time.
81246**
81247** The table to be locked has root page iTab and is found in database iDb.
81248** A read or a write lock can be taken depending on isWritelock.
81249**
81250** This routine just records the fact that the lock is desired.  The
81251** code to make the lock occur is generated by a later call to
81252** codeTableLocks() which occurs during sqlite3FinishCoding().
81253*/
81254SQLITE_PRIVATE void sqlite3TableLock(
81255  Parse *pParse,     /* Parsing context */
81256  int iDb,           /* Index of the database containing the table to lock */
81257  int iTab,          /* Root page number of the table to be locked */
81258  u8 isWriteLock,    /* True for a write lock */
81259  const char *zName  /* Name of the table to be locked */
81260){
81261  Parse *pToplevel = sqlite3ParseToplevel(pParse);
81262  int i;
81263  int nBytes;
81264  TableLock *p;
81265  assert( iDb>=0 );
81266
81267  for(i=0; i<pToplevel->nTableLock; i++){
81268    p = &pToplevel->aTableLock[i];
81269    if( p->iDb==iDb && p->iTab==iTab ){
81270      p->isWriteLock = (p->isWriteLock || isWriteLock);
81271      return;
81272    }
81273  }
81274
81275  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
81276  pToplevel->aTableLock =
81277      sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
81278  if( pToplevel->aTableLock ){
81279    p = &pToplevel->aTableLock[pToplevel->nTableLock++];
81280    p->iDb = iDb;
81281    p->iTab = iTab;
81282    p->isWriteLock = isWriteLock;
81283    p->zName = zName;
81284  }else{
81285    pToplevel->nTableLock = 0;
81286    pToplevel->db->mallocFailed = 1;
81287  }
81288}
81289
81290/*
81291** Code an OP_TableLock instruction for each table locked by the
81292** statement (configured by calls to sqlite3TableLock()).
81293*/
81294static void codeTableLocks(Parse *pParse){
81295  int i;
81296  Vdbe *pVdbe;
81297
81298  pVdbe = sqlite3GetVdbe(pParse);
81299  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
81300
81301  for(i=0; i<pParse->nTableLock; i++){
81302    TableLock *p = &pParse->aTableLock[i];
81303    int p1 = p->iDb;
81304    sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
81305                      p->zName, P4_STATIC);
81306  }
81307}
81308#else
81309  #define codeTableLocks(x)
81310#endif
81311
81312/*
81313** This routine is called after a single SQL statement has been
81314** parsed and a VDBE program to execute that statement has been
81315** prepared.  This routine puts the finishing touches on the
81316** VDBE program and resets the pParse structure for the next
81317** parse.
81318**
81319** Note that if an error occurred, it might be the case that
81320** no VDBE code was generated.
81321*/
81322SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
81323  sqlite3 *db;
81324  Vdbe *v;
81325
81326  db = pParse->db;
81327  if( db->mallocFailed ) return;
81328  if( pParse->nested ) return;
81329  if( pParse->nErr ) return;
81330
81331  /* Begin by generating some termination code at the end of the
81332  ** vdbe program
81333  */
81334  v = sqlite3GetVdbe(pParse);
81335  assert( !pParse->isMultiWrite
81336       || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
81337  if( v ){
81338    sqlite3VdbeAddOp0(v, OP_Halt);
81339
81340    /* The cookie mask contains one bit for each database file open.
81341    ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
81342    ** set for each database that is used.  Generate code to start a
81343    ** transaction on each used database and to verify the schema cookie
81344    ** on each used database.
81345    */
81346    if( pParse->cookieGoto>0 ){
81347      yDbMask mask;
81348      int iDb;
81349      sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
81350      for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
81351        if( (mask & pParse->cookieMask)==0 ) continue;
81352        sqlite3VdbeUsesBtree(v, iDb);
81353        sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
81354        if( db->init.busy==0 ){
81355          assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81356          sqlite3VdbeAddOp3(v, OP_VerifyCookie,
81357                            iDb, pParse->cookieValue[iDb],
81358                            db->aDb[iDb].pSchema->iGeneration);
81359        }
81360      }
81361#ifndef SQLITE_OMIT_VIRTUALTABLE
81362      {
81363        int i;
81364        for(i=0; i<pParse->nVtabLock; i++){
81365          char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
81366          sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
81367        }
81368        pParse->nVtabLock = 0;
81369      }
81370#endif
81371
81372      /* Once all the cookies have been verified and transactions opened,
81373      ** obtain the required table-locks. This is a no-op unless the
81374      ** shared-cache feature is enabled.
81375      */
81376      codeTableLocks(pParse);
81377
81378      /* Initialize any AUTOINCREMENT data structures required.
81379      */
81380      sqlite3AutoincrementBegin(pParse);
81381
81382      /* Finally, jump back to the beginning of the executable code. */
81383      sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
81384    }
81385  }
81386
81387
81388  /* Get the VDBE program ready for execution
81389  */
81390  if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
81391#ifdef SQLITE_DEBUG
81392    FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
81393    sqlite3VdbeTrace(v, trace);
81394#endif
81395    assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
81396    /* A minimum of one cursor is required if autoincrement is used
81397    *  See ticket [a696379c1f08866] */
81398    if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
81399    sqlite3VdbeMakeReady(v, pParse);
81400    pParse->rc = SQLITE_DONE;
81401    pParse->colNamesSet = 0;
81402  }else{
81403    pParse->rc = SQLITE_ERROR;
81404  }
81405  pParse->nTab = 0;
81406  pParse->nMem = 0;
81407  pParse->nSet = 0;
81408  pParse->nVar = 0;
81409  pParse->cookieMask = 0;
81410  pParse->cookieGoto = 0;
81411}
81412
81413/*
81414** Run the parser and code generator recursively in order to generate
81415** code for the SQL statement given onto the end of the pParse context
81416** currently under construction.  When the parser is run recursively
81417** this way, the final OP_Halt is not appended and other initialization
81418** and finalization steps are omitted because those are handling by the
81419** outermost parser.
81420**
81421** Not everything is nestable.  This facility is designed to permit
81422** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
81423** care if you decide to try to use this routine for some other purposes.
81424*/
81425SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
81426  va_list ap;
81427  char *zSql;
81428  char *zErrMsg = 0;
81429  sqlite3 *db = pParse->db;
81430# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
81431  char saveBuf[SAVE_SZ];
81432
81433  if( pParse->nErr ) return;
81434  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
81435  va_start(ap, zFormat);
81436  zSql = sqlite3VMPrintf(db, zFormat, ap);
81437  va_end(ap);
81438  if( zSql==0 ){
81439    return;   /* A malloc must have failed */
81440  }
81441  pParse->nested++;
81442  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
81443  memset(&pParse->nVar, 0, SAVE_SZ);
81444  sqlite3RunParser(pParse, zSql, &zErrMsg);
81445  sqlite3DbFree(db, zErrMsg);
81446  sqlite3DbFree(db, zSql);
81447  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
81448  pParse->nested--;
81449}
81450
81451/*
81452** Locate the in-memory structure that describes a particular database
81453** table given the name of that table and (optionally) the name of the
81454** database containing the table.  Return NULL if not found.
81455**
81456** If zDatabase is 0, all databases are searched for the table and the
81457** first matching table is returned.  (No checking for duplicate table
81458** names is done.)  The search order is TEMP first, then MAIN, then any
81459** auxiliary databases added using the ATTACH command.
81460**
81461** See also sqlite3LocateTable().
81462*/
81463SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
81464  Table *p = 0;
81465  int i;
81466  int nName;
81467  assert( zName!=0 );
81468  nName = sqlite3Strlen30(zName);
81469  /* All mutexes are required for schema access.  Make sure we hold them. */
81470  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81471  for(i=OMIT_TEMPDB; i<db->nDb; i++){
81472    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
81473    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
81474    assert( sqlite3SchemaMutexHeld(db, j, 0) );
81475    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
81476    if( p ) break;
81477  }
81478  return p;
81479}
81480
81481/*
81482** Locate the in-memory structure that describes a particular database
81483** table given the name of that table and (optionally) the name of the
81484** database containing the table.  Return NULL if not found.  Also leave an
81485** error message in pParse->zErrMsg.
81486**
81487** The difference between this routine and sqlite3FindTable() is that this
81488** routine leaves an error message in pParse->zErrMsg where
81489** sqlite3FindTable() does not.
81490*/
81491SQLITE_PRIVATE Table *sqlite3LocateTable(
81492  Parse *pParse,         /* context in which to report errors */
81493  int isView,            /* True if looking for a VIEW rather than a TABLE */
81494  const char *zName,     /* Name of the table we are looking for */
81495  const char *zDbase     /* Name of the database.  Might be NULL */
81496){
81497  Table *p;
81498
81499  /* Read the database schema. If an error occurs, leave an error message
81500  ** and code in pParse and return NULL. */
81501  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81502    return 0;
81503  }
81504
81505  p = sqlite3FindTable(pParse->db, zName, zDbase);
81506  if( p==0 ){
81507    const char *zMsg = isView ? "no such view" : "no such table";
81508    if( zDbase ){
81509      sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
81510    }else{
81511      sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
81512    }
81513    pParse->checkSchema = 1;
81514  }
81515  return p;
81516}
81517
81518/*
81519** Locate the in-memory structure that describes
81520** a particular index given the name of that index
81521** and the name of the database that contains the index.
81522** Return NULL if not found.
81523**
81524** If zDatabase is 0, all databases are searched for the
81525** table and the first matching index is returned.  (No checking
81526** for duplicate index names is done.)  The search order is
81527** TEMP first, then MAIN, then any auxiliary databases added
81528** using the ATTACH command.
81529*/
81530SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
81531  Index *p = 0;
81532  int i;
81533  int nName = sqlite3Strlen30(zName);
81534  /* All mutexes are required for schema access.  Make sure we hold them. */
81535  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
81536  for(i=OMIT_TEMPDB; i<db->nDb; i++){
81537    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
81538    Schema *pSchema = db->aDb[j].pSchema;
81539    assert( pSchema );
81540    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
81541    assert( sqlite3SchemaMutexHeld(db, j, 0) );
81542    p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
81543    if( p ) break;
81544  }
81545  return p;
81546}
81547
81548/*
81549** Reclaim the memory used by an index
81550*/
81551static void freeIndex(sqlite3 *db, Index *p){
81552#ifndef SQLITE_OMIT_ANALYZE
81553  sqlite3DeleteIndexSamples(db, p);
81554#endif
81555  sqlite3DbFree(db, p->zColAff);
81556  sqlite3DbFree(db, p);
81557}
81558
81559/*
81560** For the index called zIdxName which is found in the database iDb,
81561** unlike that index from its Table then remove the index from
81562** the index hash table and free all memory structures associated
81563** with the index.
81564*/
81565SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
81566  Index *pIndex;
81567  int len;
81568  Hash *pHash;
81569
81570  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81571  pHash = &db->aDb[iDb].pSchema->idxHash;
81572  len = sqlite3Strlen30(zIdxName);
81573  pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
81574  if( ALWAYS(pIndex) ){
81575    if( pIndex->pTable->pIndex==pIndex ){
81576      pIndex->pTable->pIndex = pIndex->pNext;
81577    }else{
81578      Index *p;
81579      /* Justification of ALWAYS();  The index must be on the list of
81580      ** indices. */
81581      p = pIndex->pTable->pIndex;
81582      while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
81583      if( ALWAYS(p && p->pNext==pIndex) ){
81584        p->pNext = pIndex->pNext;
81585      }
81586    }
81587    freeIndex(db, pIndex);
81588  }
81589  db->flags |= SQLITE_InternChanges;
81590}
81591
81592/*
81593** Erase all schema information from the in-memory hash tables of
81594** a single database.  This routine is called to reclaim memory
81595** before the database closes.  It is also called during a rollback
81596** if there were schema changes during the transaction or if a
81597** schema-cookie mismatch occurs.
81598**
81599** If iDb<0 then reset the internal schema tables for all database
81600** files.  If iDb>=0 then reset the internal schema for only the
81601** single file indicated.
81602*/
81603SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
81604  int i, j;
81605  assert( iDb<db->nDb );
81606
81607  if( iDb>=0 ){
81608    /* Case 1:  Reset the single schema identified by iDb */
81609    Db *pDb = &db->aDb[iDb];
81610    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81611    assert( pDb->pSchema!=0 );
81612    sqlite3SchemaClear(pDb->pSchema);
81613
81614    /* If any database other than TEMP is reset, then also reset TEMP
81615    ** since TEMP might be holding triggers that reference tables in the
81616    ** other database.
81617    */
81618    if( iDb!=1 ){
81619      pDb = &db->aDb[1];
81620      assert( pDb->pSchema!=0 );
81621      sqlite3SchemaClear(pDb->pSchema);
81622    }
81623    return;
81624  }
81625  /* Case 2 (from here to the end): Reset all schemas for all attached
81626  ** databases. */
81627  assert( iDb<0 );
81628  sqlite3BtreeEnterAll(db);
81629  for(i=0; i<db->nDb; i++){
81630    Db *pDb = &db->aDb[i];
81631    if( pDb->pSchema ){
81632      sqlite3SchemaClear(pDb->pSchema);
81633    }
81634  }
81635  db->flags &= ~SQLITE_InternChanges;
81636  sqlite3VtabUnlockList(db);
81637  sqlite3BtreeLeaveAll(db);
81638
81639  /* If one or more of the auxiliary database files has been closed,
81640  ** then remove them from the auxiliary database list.  We take the
81641  ** opportunity to do this here since we have just deleted all of the
81642  ** schema hash tables and therefore do not have to make any changes
81643  ** to any of those tables.
81644  */
81645  for(i=j=2; i<db->nDb; i++){
81646    struct Db *pDb = &db->aDb[i];
81647    if( pDb->pBt==0 ){
81648      sqlite3DbFree(db, pDb->zName);
81649      pDb->zName = 0;
81650      continue;
81651    }
81652    if( j<i ){
81653      db->aDb[j] = db->aDb[i];
81654    }
81655    j++;
81656  }
81657  memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
81658  db->nDb = j;
81659  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
81660    memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
81661    sqlite3DbFree(db, db->aDb);
81662    db->aDb = db->aDbStatic;
81663  }
81664}
81665
81666/*
81667** This routine is called when a commit occurs.
81668*/
81669SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
81670  db->flags &= ~SQLITE_InternChanges;
81671}
81672
81673/*
81674** Delete memory allocated for the column names of a table or view (the
81675** Table.aCol[] array).
81676*/
81677static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
81678  int i;
81679  Column *pCol;
81680  assert( pTable!=0 );
81681  if( (pCol = pTable->aCol)!=0 ){
81682    for(i=0; i<pTable->nCol; i++, pCol++){
81683      sqlite3DbFree(db, pCol->zName);
81684      sqlite3ExprDelete(db, pCol->pDflt);
81685      sqlite3DbFree(db, pCol->zDflt);
81686      sqlite3DbFree(db, pCol->zType);
81687      sqlite3DbFree(db, pCol->zColl);
81688    }
81689    sqlite3DbFree(db, pTable->aCol);
81690  }
81691}
81692
81693/*
81694** Remove the memory data structures associated with the given
81695** Table.  No changes are made to disk by this routine.
81696**
81697** This routine just deletes the data structure.  It does not unlink
81698** the table data structure from the hash table.  But it does destroy
81699** memory structures of the indices and foreign keys associated with
81700** the table.
81701*/
81702SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
81703  Index *pIndex, *pNext;
81704
81705  assert( !pTable || pTable->nRef>0 );
81706
81707  /* Do not delete the table until the reference count reaches zero. */
81708  if( !pTable ) return;
81709  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
81710
81711  /* Delete all indices associated with this table. */
81712  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
81713    pNext = pIndex->pNext;
81714    assert( pIndex->pSchema==pTable->pSchema );
81715    if( !db || db->pnBytesFreed==0 ){
81716      char *zName = pIndex->zName;
81717      TESTONLY ( Index *pOld = ) sqlite3HashInsert(
81718	  &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
81719      );
81720      assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
81721      assert( pOld==pIndex || pOld==0 );
81722    }
81723    freeIndex(db, pIndex);
81724  }
81725
81726  /* Delete any foreign keys attached to this table. */
81727  sqlite3FkDelete(db, pTable);
81728
81729  /* Delete the Table structure itself.
81730  */
81731  sqliteDeleteColumnNames(db, pTable);
81732  sqlite3DbFree(db, pTable->zName);
81733  sqlite3DbFree(db, pTable->zColAff);
81734  sqlite3SelectDelete(db, pTable->pSelect);
81735#ifndef SQLITE_OMIT_CHECK
81736  sqlite3ExprDelete(db, pTable->pCheck);
81737#endif
81738#ifndef SQLITE_OMIT_VIRTUALTABLE
81739  sqlite3VtabClear(db, pTable);
81740#endif
81741  sqlite3DbFree(db, pTable);
81742}
81743
81744/*
81745** Unlink the given table from the hash tables and the delete the
81746** table structure with all its indices and foreign keys.
81747*/
81748SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
81749  Table *p;
81750  Db *pDb;
81751
81752  assert( db!=0 );
81753  assert( iDb>=0 && iDb<db->nDb );
81754  assert( zTabName );
81755  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81756  testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
81757  pDb = &db->aDb[iDb];
81758  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
81759                        sqlite3Strlen30(zTabName),0);
81760  sqlite3DeleteTable(db, p);
81761  db->flags |= SQLITE_InternChanges;
81762}
81763
81764/*
81765** Given a token, return a string that consists of the text of that
81766** token.  Space to hold the returned string
81767** is obtained from sqliteMalloc() and must be freed by the calling
81768** function.
81769**
81770** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
81771** surround the body of the token are removed.
81772**
81773** Tokens are often just pointers into the original SQL text and so
81774** are not \000 terminated and are not persistent.  The returned string
81775** is \000 terminated and is persistent.
81776*/
81777SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
81778  char *zName;
81779  if( pName ){
81780    zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
81781    sqlite3Dequote(zName);
81782  }else{
81783    zName = 0;
81784  }
81785  return zName;
81786}
81787
81788/*
81789** Open the sqlite_master table stored in database number iDb for
81790** writing. The table is opened using cursor 0.
81791*/
81792SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
81793  Vdbe *v = sqlite3GetVdbe(p);
81794  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
81795  sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
81796  sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
81797  if( p->nTab==0 ){
81798    p->nTab = 1;
81799  }
81800}
81801
81802/*
81803** Parameter zName points to a nul-terminated buffer containing the name
81804** of a database ("main", "temp" or the name of an attached db). This
81805** function returns the index of the named database in db->aDb[], or
81806** -1 if the named db cannot be found.
81807*/
81808SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
81809  int i = -1;         /* Database number */
81810  if( zName ){
81811    Db *pDb;
81812    int n = sqlite3Strlen30(zName);
81813    for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
81814      if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
81815          0==sqlite3StrICmp(pDb->zName, zName) ){
81816        break;
81817      }
81818    }
81819  }
81820  return i;
81821}
81822
81823/*
81824** The token *pName contains the name of a database (either "main" or
81825** "temp" or the name of an attached db). This routine returns the
81826** index of the named database in db->aDb[], or -1 if the named db
81827** does not exist.
81828*/
81829SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
81830  int i;                               /* Database number */
81831  char *zName;                         /* Name we are searching for */
81832  zName = sqlite3NameFromToken(db, pName);
81833  i = sqlite3FindDbName(db, zName);
81834  sqlite3DbFree(db, zName);
81835  return i;
81836}
81837
81838/* The table or view or trigger name is passed to this routine via tokens
81839** pName1 and pName2. If the table name was fully qualified, for example:
81840**
81841** CREATE TABLE xxx.yyy (...);
81842**
81843** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81844** the table name is not fully qualified, i.e.:
81845**
81846** CREATE TABLE yyy(...);
81847**
81848** Then pName1 is set to "yyy" and pName2 is "".
81849**
81850** This routine sets the *ppUnqual pointer to point at the token (pName1 or
81851** pName2) that stores the unqualified table name.  The index of the
81852** database "xxx" is returned.
81853*/
81854SQLITE_PRIVATE int sqlite3TwoPartName(
81855  Parse *pParse,      /* Parsing and code generating context */
81856  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
81857  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
81858  Token **pUnqual     /* Write the unqualified object name here */
81859){
81860  int iDb;                    /* Database holding the object */
81861  sqlite3 *db = pParse->db;
81862
81863  if( ALWAYS(pName2!=0) && pName2->n>0 ){
81864    if( db->init.busy ) {
81865      sqlite3ErrorMsg(pParse, "corrupt database");
81866      pParse->nErr++;
81867      return -1;
81868    }
81869    *pUnqual = pName2;
81870    iDb = sqlite3FindDb(db, pName1);
81871    if( iDb<0 ){
81872      sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
81873      pParse->nErr++;
81874      return -1;
81875    }
81876  }else{
81877    assert( db->init.iDb==0 || db->init.busy );
81878    iDb = db->init.iDb;
81879    *pUnqual = pName1;
81880  }
81881  return iDb;
81882}
81883
81884/*
81885** This routine is used to check if the UTF-8 string zName is a legal
81886** unqualified name for a new schema object (table, index, view or
81887** trigger). All names are legal except those that begin with the string
81888** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
81889** is reserved for internal use.
81890*/
81891SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
81892  if( !pParse->db->init.busy && pParse->nested==0
81893          && (pParse->db->flags & SQLITE_WriteSchema)==0
81894          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
81895    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
81896    return SQLITE_ERROR;
81897  }
81898  return SQLITE_OK;
81899}
81900
81901/*
81902** Begin constructing a new table representation in memory.  This is
81903** the first of several action routines that get called in response
81904** to a CREATE TABLE statement.  In particular, this routine is called
81905** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
81906** flag is true if the table should be stored in the auxiliary database
81907** file instead of in the main database file.  This is normally the case
81908** when the "TEMP" or "TEMPORARY" keyword occurs in between
81909** CREATE and TABLE.
81910**
81911** The new table record is initialized and put in pParse->pNewTable.
81912** As more of the CREATE TABLE statement is parsed, additional action
81913** routines will be called to add more information to this record.
81914** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
81915** is called to complete the construction of the new table record.
81916*/
81917SQLITE_PRIVATE void sqlite3StartTable(
81918  Parse *pParse,   /* Parser context */
81919  Token *pName1,   /* First part of the name of the table or view */
81920  Token *pName2,   /* Second part of the name of the table or view */
81921  int isTemp,      /* True if this is a TEMP table */
81922  int isView,      /* True if this is a VIEW */
81923  int isVirtual,   /* True if this is a VIRTUAL table */
81924  int noErr        /* Do nothing if table already exists */
81925){
81926  Table *pTable;
81927  char *zName = 0; /* The name of the new table */
81928  sqlite3 *db = pParse->db;
81929  Vdbe *v;
81930  int iDb;         /* Database number to create the table in */
81931  Token *pName;    /* Unqualified name of the table to create */
81932
81933  /* The table or view name to create is passed to this routine via tokens
81934  ** pName1 and pName2. If the table name was fully qualified, for example:
81935  **
81936  ** CREATE TABLE xxx.yyy (...);
81937  **
81938  ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
81939  ** the table name is not fully qualified, i.e.:
81940  **
81941  ** CREATE TABLE yyy(...);
81942  **
81943  ** Then pName1 is set to "yyy" and pName2 is "".
81944  **
81945  ** The call below sets the pName pointer to point at the token (pName1 or
81946  ** pName2) that stores the unqualified table name. The variable iDb is
81947  ** set to the index of the database that the table or view is to be
81948  ** created in.
81949  */
81950  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
81951  if( iDb<0 ) return;
81952  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
81953    /* If creating a temp table, the name may not be qualified. Unless
81954    ** the database name is "temp" anyway.  */
81955    sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
81956    return;
81957  }
81958  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
81959
81960  pParse->sNameToken = *pName;
81961  zName = sqlite3NameFromToken(db, pName);
81962  if( zName==0 ) return;
81963  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
81964    goto begin_table_error;
81965  }
81966  if( db->init.iDb==1 ) isTemp = 1;
81967#ifndef SQLITE_OMIT_AUTHORIZATION
81968  assert( (isTemp & 1)==isTemp );
81969  {
81970    int code;
81971    char *zDb = db->aDb[iDb].zName;
81972    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
81973      goto begin_table_error;
81974    }
81975    if( isView ){
81976      if( !OMIT_TEMPDB && isTemp ){
81977        code = SQLITE_CREATE_TEMP_VIEW;
81978      }else{
81979        code = SQLITE_CREATE_VIEW;
81980      }
81981    }else{
81982      if( !OMIT_TEMPDB && isTemp ){
81983        code = SQLITE_CREATE_TEMP_TABLE;
81984      }else{
81985        code = SQLITE_CREATE_TABLE;
81986      }
81987    }
81988    if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
81989      goto begin_table_error;
81990    }
81991  }
81992#endif
81993
81994  /* Make sure the new table name does not collide with an existing
81995  ** index or table name in the same database.  Issue an error message if
81996  ** it does. The exception is if the statement being parsed was passed
81997  ** to an sqlite3_declare_vtab() call. In that case only the column names
81998  ** and types will be used, so there is no need to test for namespace
81999  ** collisions.
82000  */
82001  if( !IN_DECLARE_VTAB ){
82002    char *zDb = db->aDb[iDb].zName;
82003    if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82004      goto begin_table_error;
82005    }
82006    pTable = sqlite3FindTable(db, zName, zDb);
82007    if( pTable ){
82008      if( !noErr ){
82009        sqlite3ErrorMsg(pParse, "table %T already exists", pName);
82010      }else{
82011        assert( !db->init.busy );
82012        sqlite3CodeVerifySchema(pParse, iDb);
82013      }
82014      goto begin_table_error;
82015    }
82016    if( sqlite3FindIndex(db, zName, zDb)!=0 ){
82017      sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
82018      goto begin_table_error;
82019    }
82020  }
82021
82022  pTable = sqlite3DbMallocZero(db, sizeof(Table));
82023  if( pTable==0 ){
82024    db->mallocFailed = 1;
82025    pParse->rc = SQLITE_NOMEM;
82026    pParse->nErr++;
82027    goto begin_table_error;
82028  }
82029  pTable->zName = zName;
82030  pTable->iPKey = -1;
82031  pTable->pSchema = db->aDb[iDb].pSchema;
82032  pTable->nRef = 1;
82033  pTable->nRowEst = 1000000;
82034  assert( pParse->pNewTable==0 );
82035  pParse->pNewTable = pTable;
82036
82037  /* If this is the magic sqlite_sequence table used by autoincrement,
82038  ** then record a pointer to this table in the main database structure
82039  ** so that INSERT can find the table easily.
82040  */
82041#ifndef SQLITE_OMIT_AUTOINCREMENT
82042  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
82043    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82044    pTable->pSchema->pSeqTab = pTable;
82045  }
82046#endif
82047
82048  /* Begin generating the code that will insert the table record into
82049  ** the SQLITE_MASTER table.  Note in particular that we must go ahead
82050  ** and allocate the record number for the table entry now.  Before any
82051  ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
82052  ** indices to be created and the table record must come before the
82053  ** indices.  Hence, the record number for the table must be allocated
82054  ** now.
82055  */
82056  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
82057    int j1;
82058    int fileFormat;
82059    int reg1, reg2, reg3;
82060    sqlite3BeginWriteOperation(pParse, 0, iDb);
82061
82062#ifndef SQLITE_OMIT_VIRTUALTABLE
82063    if( isVirtual ){
82064      sqlite3VdbeAddOp0(v, OP_VBegin);
82065    }
82066#endif
82067
82068    /* If the file format and encoding in the database have not been set,
82069    ** set them now.
82070    */
82071    reg1 = pParse->regRowid = ++pParse->nMem;
82072    reg2 = pParse->regRoot = ++pParse->nMem;
82073    reg3 = ++pParse->nMem;
82074    sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
82075    sqlite3VdbeUsesBtree(v, iDb);
82076    j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
82077    fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
82078                  1 : SQLITE_MAX_FILE_FORMAT;
82079    sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
82080    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
82081    sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
82082    sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
82083    sqlite3VdbeJumpHere(v, j1);
82084
82085    /* This just creates a place-holder record in the sqlite_master table.
82086    ** The record created does not contain anything yet.  It will be replaced
82087    ** by the real entry in code generated at sqlite3EndTable().
82088    **
82089    ** The rowid for the new entry is left in register pParse->regRowid.
82090    ** The root page number of the new table is left in reg pParse->regRoot.
82091    ** The rowid and root page number values are needed by the code that
82092    ** sqlite3EndTable will generate.
82093    */
82094#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
82095    if( isView || isVirtual ){
82096      sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
82097    }else
82098#endif
82099    {
82100      sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
82101    }
82102    sqlite3OpenMasterTable(pParse, iDb);
82103    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
82104    sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
82105    sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
82106    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
82107    sqlite3VdbeAddOp0(v, OP_Close);
82108  }
82109
82110  /* Normal (non-error) return. */
82111  return;
82112
82113  /* If an error occurs, we jump here */
82114begin_table_error:
82115  sqlite3DbFree(db, zName);
82116  return;
82117}
82118
82119/*
82120** This macro is used to compare two strings in a case-insensitive manner.
82121** It is slightly faster than calling sqlite3StrICmp() directly, but
82122** produces larger code.
82123**
82124** WARNING: This macro is not compatible with the strcmp() family. It
82125** returns true if the two strings are equal, otherwise false.
82126*/
82127#define STRICMP(x, y) (\
82128sqlite3UpperToLower[*(unsigned char *)(x)]==   \
82129sqlite3UpperToLower[*(unsigned char *)(y)]     \
82130&& sqlite3StrICmp((x)+1,(y)+1)==0 )
82131
82132/*
82133** Add a new column to the table currently being constructed.
82134**
82135** The parser calls this routine once for each column declaration
82136** in a CREATE TABLE statement.  sqlite3StartTable() gets called
82137** first to get things going.  Then this routine is called for each
82138** column.
82139*/
82140SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
82141  Table *p;
82142  int i;
82143  char *z;
82144  Column *pCol;
82145  sqlite3 *db = pParse->db;
82146  if( (p = pParse->pNewTable)==0 ) return;
82147#if SQLITE_MAX_COLUMN
82148  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
82149    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
82150    return;
82151  }
82152#endif
82153  z = sqlite3NameFromToken(db, pName);
82154  if( z==0 ) return;
82155  for(i=0; i<p->nCol; i++){
82156    if( STRICMP(z, p->aCol[i].zName) ){
82157      sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
82158      sqlite3DbFree(db, z);
82159      return;
82160    }
82161  }
82162  if( (p->nCol & 0x7)==0 ){
82163    Column *aNew;
82164    aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
82165    if( aNew==0 ){
82166      sqlite3DbFree(db, z);
82167      return;
82168    }
82169    p->aCol = aNew;
82170  }
82171  pCol = &p->aCol[p->nCol];
82172  memset(pCol, 0, sizeof(p->aCol[0]));
82173  pCol->zName = z;
82174
82175  /* If there is no type specified, columns have the default affinity
82176  ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
82177  ** be called next to set pCol->affinity correctly.
82178  */
82179  pCol->affinity = SQLITE_AFF_NONE;
82180  p->nCol++;
82181}
82182
82183/*
82184** This routine is called by the parser while in the middle of
82185** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
82186** been seen on a column.  This routine sets the notNull flag on
82187** the column currently under construction.
82188*/
82189SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
82190  Table *p;
82191  p = pParse->pNewTable;
82192  if( p==0 || NEVER(p->nCol<1) ) return;
82193  p->aCol[p->nCol-1].notNull = (u8)onError;
82194}
82195
82196/*
82197** Scan the column type name zType (length nType) and return the
82198** associated affinity type.
82199**
82200** This routine does a case-independent search of zType for the
82201** substrings in the following table. If one of the substrings is
82202** found, the corresponding affinity is returned. If zType contains
82203** more than one of the substrings, entries toward the top of
82204** the table take priority. For example, if zType is 'BLOBINT',
82205** SQLITE_AFF_INTEGER is returned.
82206**
82207** Substring     | Affinity
82208** --------------------------------
82209** 'INT'         | SQLITE_AFF_INTEGER
82210** 'CHAR'        | SQLITE_AFF_TEXT
82211** 'CLOB'        | SQLITE_AFF_TEXT
82212** 'TEXT'        | SQLITE_AFF_TEXT
82213** 'BLOB'        | SQLITE_AFF_NONE
82214** 'REAL'        | SQLITE_AFF_REAL
82215** 'FLOA'        | SQLITE_AFF_REAL
82216** 'DOUB'        | SQLITE_AFF_REAL
82217**
82218** If none of the substrings in the above table are found,
82219** SQLITE_AFF_NUMERIC is returned.
82220*/
82221SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
82222  u32 h = 0;
82223  char aff = SQLITE_AFF_NUMERIC;
82224
82225  if( zIn ) while( zIn[0] ){
82226    h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
82227    zIn++;
82228    if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
82229      aff = SQLITE_AFF_TEXT;
82230    }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
82231      aff = SQLITE_AFF_TEXT;
82232    }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
82233      aff = SQLITE_AFF_TEXT;
82234    }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
82235        && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
82236      aff = SQLITE_AFF_NONE;
82237#ifndef SQLITE_OMIT_FLOATING_POINT
82238    }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
82239        && aff==SQLITE_AFF_NUMERIC ){
82240      aff = SQLITE_AFF_REAL;
82241    }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
82242        && aff==SQLITE_AFF_NUMERIC ){
82243      aff = SQLITE_AFF_REAL;
82244    }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
82245        && aff==SQLITE_AFF_NUMERIC ){
82246      aff = SQLITE_AFF_REAL;
82247#endif
82248    }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
82249      aff = SQLITE_AFF_INTEGER;
82250      break;
82251    }
82252  }
82253
82254  return aff;
82255}
82256
82257/*
82258** This routine is called by the parser while in the middle of
82259** parsing a CREATE TABLE statement.  The pFirst token is the first
82260** token in the sequence of tokens that describe the type of the
82261** column currently under construction.   pLast is the last token
82262** in the sequence.  Use this information to construct a string
82263** that contains the typename of the column and store that string
82264** in zType.
82265*/
82266SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
82267  Table *p;
82268  Column *pCol;
82269
82270  p = pParse->pNewTable;
82271  if( p==0 || NEVER(p->nCol<1) ) return;
82272  pCol = &p->aCol[p->nCol-1];
82273  assert( pCol->zType==0 );
82274  pCol->zType = sqlite3NameFromToken(pParse->db, pType);
82275  pCol->affinity = sqlite3AffinityType(pCol->zType);
82276}
82277
82278/*
82279** The expression is the default value for the most recently added column
82280** of the table currently under construction.
82281**
82282** Default value expressions must be constant.  Raise an exception if this
82283** is not the case.
82284**
82285** This routine is called by the parser while in the middle of
82286** parsing a CREATE TABLE statement.
82287*/
82288SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
82289  Table *p;
82290  Column *pCol;
82291  sqlite3 *db = pParse->db;
82292  p = pParse->pNewTable;
82293  if( p!=0 ){
82294    pCol = &(p->aCol[p->nCol-1]);
82295    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
82296      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
82297          pCol->zName);
82298    }else{
82299      /* A copy of pExpr is used instead of the original, as pExpr contains
82300      ** tokens that point to volatile memory. The 'span' of the expression
82301      ** is required by pragma table_info.
82302      */
82303      sqlite3ExprDelete(db, pCol->pDflt);
82304      pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
82305      sqlite3DbFree(db, pCol->zDflt);
82306      pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
82307                                     (int)(pSpan->zEnd - pSpan->zStart));
82308    }
82309  }
82310  sqlite3ExprDelete(db, pSpan->pExpr);
82311}
82312
82313/*
82314** Designate the PRIMARY KEY for the table.  pList is a list of names
82315** of columns that form the primary key.  If pList is NULL, then the
82316** most recently added column of the table is the primary key.
82317**
82318** A table can have at most one primary key.  If the table already has
82319** a primary key (and this is the second primary key) then create an
82320** error.
82321**
82322** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
82323** then we will try to use that column as the rowid.  Set the Table.iPKey
82324** field of the table under construction to be the index of the
82325** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
82326** no INTEGER PRIMARY KEY.
82327**
82328** If the key is not an INTEGER PRIMARY KEY, then create a unique
82329** index for the key.  No index is created for INTEGER PRIMARY KEYs.
82330*/
82331SQLITE_PRIVATE void sqlite3AddPrimaryKey(
82332  Parse *pParse,    /* Parsing context */
82333  ExprList *pList,  /* List of field names to be indexed */
82334  int onError,      /* What to do with a uniqueness conflict */
82335  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
82336  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
82337){
82338  Table *pTab = pParse->pNewTable;
82339  char *zType = 0;
82340  int iCol = -1, i;
82341  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
82342  if( pTab->tabFlags & TF_HasPrimaryKey ){
82343    sqlite3ErrorMsg(pParse,
82344      "table \"%s\" has more than one primary key", pTab->zName);
82345    goto primary_key_exit;
82346  }
82347  pTab->tabFlags |= TF_HasPrimaryKey;
82348  if( pList==0 ){
82349    iCol = pTab->nCol - 1;
82350    pTab->aCol[iCol].isPrimKey = 1;
82351  }else{
82352    for(i=0; i<pList->nExpr; i++){
82353      for(iCol=0; iCol<pTab->nCol; iCol++){
82354        if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
82355          break;
82356        }
82357      }
82358      if( iCol<pTab->nCol ){
82359        pTab->aCol[iCol].isPrimKey = 1;
82360      }
82361    }
82362    if( pList->nExpr>1 ) iCol = -1;
82363  }
82364  if( iCol>=0 && iCol<pTab->nCol ){
82365    zType = pTab->aCol[iCol].zType;
82366  }
82367  if( zType && sqlite3StrICmp(zType, "INTEGER")==0
82368        && sortOrder==SQLITE_SO_ASC ){
82369    pTab->iPKey = iCol;
82370    pTab->keyConf = (u8)onError;
82371    assert( autoInc==0 || autoInc==1 );
82372    pTab->tabFlags |= autoInc*TF_Autoincrement;
82373  }else if( autoInc ){
82374#ifndef SQLITE_OMIT_AUTOINCREMENT
82375    sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
82376       "INTEGER PRIMARY KEY");
82377#endif
82378  }else{
82379    Index *p;
82380    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
82381    if( p ){
82382      p->autoIndex = 2;
82383    }
82384    pList = 0;
82385  }
82386
82387primary_key_exit:
82388  sqlite3ExprListDelete(pParse->db, pList);
82389  return;
82390}
82391
82392/*
82393** Add a new CHECK constraint to the table currently under construction.
82394*/
82395SQLITE_PRIVATE void sqlite3AddCheckConstraint(
82396  Parse *pParse,    /* Parsing context */
82397  Expr *pCheckExpr  /* The check expression */
82398){
82399  sqlite3 *db = pParse->db;
82400#ifndef SQLITE_OMIT_CHECK
82401  Table *pTab = pParse->pNewTable;
82402  if( pTab && !IN_DECLARE_VTAB ){
82403    pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
82404  }else
82405#endif
82406  {
82407    sqlite3ExprDelete(db, pCheckExpr);
82408  }
82409}
82410
82411/*
82412** Set the collation function of the most recently parsed table column
82413** to the CollSeq given.
82414*/
82415SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
82416  Table *p;
82417  int i;
82418  char *zColl;              /* Dequoted name of collation sequence */
82419  sqlite3 *db;
82420
82421  if( (p = pParse->pNewTable)==0 ) return;
82422  i = p->nCol-1;
82423  db = pParse->db;
82424  zColl = sqlite3NameFromToken(db, pToken);
82425  if( !zColl ) return;
82426
82427  if( sqlite3LocateCollSeq(pParse, zColl) ){
82428    Index *pIdx;
82429    p->aCol[i].zColl = zColl;
82430
82431    /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
82432    ** then an index may have been created on this column before the
82433    ** collation type was added. Correct this if it is the case.
82434    */
82435    for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
82436      assert( pIdx->nColumn==1 );
82437      if( pIdx->aiColumn[0]==i ){
82438        pIdx->azColl[0] = p->aCol[i].zColl;
82439      }
82440    }
82441  }else{
82442    sqlite3DbFree(db, zColl);
82443  }
82444}
82445
82446/*
82447** This function returns the collation sequence for database native text
82448** encoding identified by the string zName, length nName.
82449**
82450** If the requested collation sequence is not available, or not available
82451** in the database native encoding, the collation factory is invoked to
82452** request it. If the collation factory does not supply such a sequence,
82453** and the sequence is available in another text encoding, then that is
82454** returned instead.
82455**
82456** If no versions of the requested collations sequence are available, or
82457** another error occurs, NULL is returned and an error message written into
82458** pParse.
82459**
82460** This routine is a wrapper around sqlite3FindCollSeq().  This routine
82461** invokes the collation factory if the named collation cannot be found
82462** and generates an error message.
82463**
82464** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
82465*/
82466SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
82467  sqlite3 *db = pParse->db;
82468  u8 enc = ENC(db);
82469  u8 initbusy = db->init.busy;
82470  CollSeq *pColl;
82471
82472  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
82473  if( !initbusy && (!pColl || !pColl->xCmp) ){
82474    pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
82475    if( !pColl ){
82476      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
82477    }
82478  }
82479
82480  return pColl;
82481}
82482
82483
82484/*
82485** Generate code that will increment the schema cookie.
82486**
82487** The schema cookie is used to determine when the schema for the
82488** database changes.  After each schema change, the cookie value
82489** changes.  When a process first reads the schema it records the
82490** cookie.  Thereafter, whenever it goes to access the database,
82491** it checks the cookie to make sure the schema has not changed
82492** since it was last read.
82493**
82494** This plan is not completely bullet-proof.  It is possible for
82495** the schema to change multiple times and for the cookie to be
82496** set back to prior value.  But schema changes are infrequent
82497** and the probability of hitting the same cookie value is only
82498** 1 chance in 2^32.  So we're safe enough.
82499*/
82500SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
82501  int r1 = sqlite3GetTempReg(pParse);
82502  sqlite3 *db = pParse->db;
82503  Vdbe *v = pParse->pVdbe;
82504  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82505  sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
82506  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
82507  sqlite3ReleaseTempReg(pParse, r1);
82508}
82509
82510/*
82511** Measure the number of characters needed to output the given
82512** identifier.  The number returned includes any quotes used
82513** but does not include the null terminator.
82514**
82515** The estimate is conservative.  It might be larger that what is
82516** really needed.
82517*/
82518static int identLength(const char *z){
82519  int n;
82520  for(n=0; *z; n++, z++){
82521    if( *z=='"' ){ n++; }
82522  }
82523  return n + 2;
82524}
82525
82526/*
82527** The first parameter is a pointer to an output buffer. The second
82528** parameter is a pointer to an integer that contains the offset at
82529** which to write into the output buffer. This function copies the
82530** nul-terminated string pointed to by the third parameter, zSignedIdent,
82531** to the specified offset in the buffer and updates *pIdx to refer
82532** to the first byte after the last byte written before returning.
82533**
82534** If the string zSignedIdent consists entirely of alpha-numeric
82535** characters, does not begin with a digit and is not an SQL keyword,
82536** then it is copied to the output buffer exactly as it is. Otherwise,
82537** it is quoted using double-quotes.
82538*/
82539static void identPut(char *z, int *pIdx, char *zSignedIdent){
82540  unsigned char *zIdent = (unsigned char*)zSignedIdent;
82541  int i, j, needQuote;
82542  i = *pIdx;
82543
82544  for(j=0; zIdent[j]; j++){
82545    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
82546  }
82547  needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
82548  if( !needQuote ){
82549    needQuote = zIdent[j];
82550  }
82551
82552  if( needQuote ) z[i++] = '"';
82553  for(j=0; zIdent[j]; j++){
82554    z[i++] = zIdent[j];
82555    if( zIdent[j]=='"' ) z[i++] = '"';
82556  }
82557  if( needQuote ) z[i++] = '"';
82558  z[i] = 0;
82559  *pIdx = i;
82560}
82561
82562/*
82563** Generate a CREATE TABLE statement appropriate for the given
82564** table.  Memory to hold the text of the statement is obtained
82565** from sqliteMalloc() and must be freed by the calling function.
82566*/
82567static char *createTableStmt(sqlite3 *db, Table *p){
82568  int i, k, n;
82569  char *zStmt;
82570  char *zSep, *zSep2, *zEnd;
82571  Column *pCol;
82572  n = 0;
82573  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
82574    n += identLength(pCol->zName) + 5;
82575  }
82576  n += identLength(p->zName);
82577  if( n<50 ){
82578    zSep = "";
82579    zSep2 = ",";
82580    zEnd = ")";
82581  }else{
82582    zSep = "\n  ";
82583    zSep2 = ",\n  ";
82584    zEnd = "\n)";
82585  }
82586  n += 35 + 6*p->nCol;
82587  zStmt = sqlite3DbMallocRaw(0, n);
82588  if( zStmt==0 ){
82589    db->mallocFailed = 1;
82590    return 0;
82591  }
82592  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
82593  k = sqlite3Strlen30(zStmt);
82594  identPut(zStmt, &k, p->zName);
82595  zStmt[k++] = '(';
82596  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
82597    static const char * const azType[] = {
82598        /* SQLITE_AFF_TEXT    */ " TEXT",
82599        /* SQLITE_AFF_NONE    */ "",
82600        /* SQLITE_AFF_NUMERIC */ " NUM",
82601        /* SQLITE_AFF_INTEGER */ " INT",
82602        /* SQLITE_AFF_REAL    */ " REAL"
82603    };
82604    int len;
82605    const char *zType;
82606
82607    sqlite3_snprintf(n-k, &zStmt[k], zSep);
82608    k += sqlite3Strlen30(&zStmt[k]);
82609    zSep = zSep2;
82610    identPut(zStmt, &k, pCol->zName);
82611    assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
82612    assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
82613    testcase( pCol->affinity==SQLITE_AFF_TEXT );
82614    testcase( pCol->affinity==SQLITE_AFF_NONE );
82615    testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
82616    testcase( pCol->affinity==SQLITE_AFF_INTEGER );
82617    testcase( pCol->affinity==SQLITE_AFF_REAL );
82618
82619    zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
82620    len = sqlite3Strlen30(zType);
82621    assert( pCol->affinity==SQLITE_AFF_NONE
82622            || pCol->affinity==sqlite3AffinityType(zType) );
82623    memcpy(&zStmt[k], zType, len);
82624    k += len;
82625    assert( k<=n );
82626  }
82627  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
82628  return zStmt;
82629}
82630
82631/*
82632** This routine is called to report the final ")" that terminates
82633** a CREATE TABLE statement.
82634**
82635** The table structure that other action routines have been building
82636** is added to the internal hash tables, assuming no errors have
82637** occurred.
82638**
82639** An entry for the table is made in the master table on disk, unless
82640** this is a temporary table or db->init.busy==1.  When db->init.busy==1
82641** it means we are reading the sqlite_master table because we just
82642** connected to the database or because the sqlite_master table has
82643** recently changed, so the entry for this table already exists in
82644** the sqlite_master table.  We do not want to create it again.
82645**
82646** If the pSelect argument is not NULL, it means that this routine
82647** was called to create a table generated from a
82648** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
82649** the new table will match the result set of the SELECT.
82650*/
82651SQLITE_PRIVATE void sqlite3EndTable(
82652  Parse *pParse,          /* Parse context */
82653  Token *pCons,           /* The ',' token after the last column defn. */
82654  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
82655  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
82656){
82657  Table *p;
82658  sqlite3 *db = pParse->db;
82659  int iDb;
82660
82661  if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
82662    return;
82663  }
82664  p = pParse->pNewTable;
82665  if( p==0 ) return;
82666
82667  assert( !db->init.busy || !pSelect );
82668
82669  iDb = sqlite3SchemaToIndex(db, p->pSchema);
82670
82671#ifndef SQLITE_OMIT_CHECK
82672  /* Resolve names in all CHECK constraint expressions.
82673  */
82674  if( p->pCheck ){
82675    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
82676    NameContext sNC;                /* Name context for pParse->pNewTable */
82677
82678    memset(&sNC, 0, sizeof(sNC));
82679    memset(&sSrc, 0, sizeof(sSrc));
82680    sSrc.nSrc = 1;
82681    sSrc.a[0].zName = p->zName;
82682    sSrc.a[0].pTab = p;
82683    sSrc.a[0].iCursor = -1;
82684    sNC.pParse = pParse;
82685    sNC.pSrcList = &sSrc;
82686    sNC.isCheck = 1;
82687    if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
82688      return;
82689    }
82690  }
82691#endif /* !defined(SQLITE_OMIT_CHECK) */
82692
82693  /* If the db->init.busy is 1 it means we are reading the SQL off the
82694  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
82695  ** So do not write to the disk again.  Extract the root page number
82696  ** for the table from the db->init.newTnum field.  (The page number
82697  ** should have been put there by the sqliteOpenCb routine.)
82698  */
82699  if( db->init.busy ){
82700    p->tnum = db->init.newTnum;
82701  }
82702
82703  /* If not initializing, then create a record for the new table
82704  ** in the SQLITE_MASTER table of the database.
82705  **
82706  ** If this is a TEMPORARY table, write the entry into the auxiliary
82707  ** file instead of into the main database file.
82708  */
82709  if( !db->init.busy ){
82710    int n;
82711    Vdbe *v;
82712    char *zType;    /* "view" or "table" */
82713    char *zType2;   /* "VIEW" or "TABLE" */
82714    char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
82715
82716    v = sqlite3GetVdbe(pParse);
82717    if( NEVER(v==0) ) return;
82718
82719    sqlite3VdbeAddOp1(v, OP_Close, 0);
82720
82721    /*
82722    ** Initialize zType for the new view or table.
82723    */
82724    if( p->pSelect==0 ){
82725      /* A regular table */
82726      zType = "table";
82727      zType2 = "TABLE";
82728#ifndef SQLITE_OMIT_VIEW
82729    }else{
82730      /* A view */
82731      zType = "view";
82732      zType2 = "VIEW";
82733#endif
82734    }
82735
82736    /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
82737    ** statement to populate the new table. The root-page number for the
82738    ** new table is in register pParse->regRoot.
82739    **
82740    ** Once the SELECT has been coded by sqlite3Select(), it is in a
82741    ** suitable state to query for the column names and types to be used
82742    ** by the new table.
82743    **
82744    ** A shared-cache write-lock is not required to write to the new table,
82745    ** as a schema-lock must have already been obtained to create it. Since
82746    ** a schema-lock excludes all other database users, the write-lock would
82747    ** be redundant.
82748    */
82749    if( pSelect ){
82750      SelectDest dest;
82751      Table *pSelTab;
82752
82753      assert(pParse->nTab==1);
82754      sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
82755      sqlite3VdbeChangeP5(v, 1);
82756      pParse->nTab = 2;
82757      sqlite3SelectDestInit(&dest, SRT_Table, 1);
82758      sqlite3Select(pParse, pSelect, &dest);
82759      sqlite3VdbeAddOp1(v, OP_Close, 1);
82760      if( pParse->nErr==0 ){
82761        pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
82762        if( pSelTab==0 ) return;
82763        assert( p->aCol==0 );
82764        p->nCol = pSelTab->nCol;
82765        p->aCol = pSelTab->aCol;
82766        pSelTab->nCol = 0;
82767        pSelTab->aCol = 0;
82768        sqlite3DeleteTable(db, pSelTab);
82769      }
82770    }
82771
82772    /* Compute the complete text of the CREATE statement */
82773    if( pSelect ){
82774      zStmt = createTableStmt(db, p);
82775    }else{
82776      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
82777      zStmt = sqlite3MPrintf(db,
82778          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
82779      );
82780    }
82781
82782    /* A slot for the record has already been allocated in the
82783    ** SQLITE_MASTER table.  We just need to update that slot with all
82784    ** the information we've collected.
82785    */
82786    sqlite3NestedParse(pParse,
82787      "UPDATE %Q.%s "
82788         "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
82789       "WHERE rowid=#%d",
82790      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
82791      zType,
82792      p->zName,
82793      p->zName,
82794      pParse->regRoot,
82795      zStmt,
82796      pParse->regRowid
82797    );
82798    sqlite3DbFree(db, zStmt);
82799    sqlite3ChangeCookie(pParse, iDb);
82800
82801#ifndef SQLITE_OMIT_AUTOINCREMENT
82802    /* Check to see if we need to create an sqlite_sequence table for
82803    ** keeping track of autoincrement keys.
82804    */
82805    if( p->tabFlags & TF_Autoincrement ){
82806      Db *pDb = &db->aDb[iDb];
82807      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82808      if( pDb->pSchema->pSeqTab==0 ){
82809        sqlite3NestedParse(pParse,
82810          "CREATE TABLE %Q.sqlite_sequence(name,seq)",
82811          pDb->zName
82812        );
82813      }
82814    }
82815#endif
82816
82817    /* Reparse everything to update our internal data structures */
82818    sqlite3VdbeAddParseSchemaOp(v, iDb,
82819               sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
82820  }
82821
82822
82823  /* Add the table to the in-memory representation of the database.
82824  */
82825  if( db->init.busy ){
82826    Table *pOld;
82827    Schema *pSchema = p->pSchema;
82828    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82829    pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
82830                             sqlite3Strlen30(p->zName),p);
82831    if( pOld ){
82832      assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
82833      db->mallocFailed = 1;
82834      return;
82835    }
82836    pParse->pNewTable = 0;
82837    db->flags |= SQLITE_InternChanges;
82838
82839#ifndef SQLITE_OMIT_ALTERTABLE
82840    if( !p->pSelect ){
82841      const char *zName = (const char *)pParse->sNameToken.z;
82842      int nName;
82843      assert( !pSelect && pCons && pEnd );
82844      if( pCons->z==0 ){
82845        pCons = pEnd;
82846      }
82847      nName = (int)((const char *)pCons->z - zName);
82848      p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
82849    }
82850#endif
82851  }
82852}
82853
82854#ifndef SQLITE_OMIT_VIEW
82855/*
82856** The parser calls this routine in order to create a new VIEW
82857*/
82858SQLITE_PRIVATE void sqlite3CreateView(
82859  Parse *pParse,     /* The parsing context */
82860  Token *pBegin,     /* The CREATE token that begins the statement */
82861  Token *pName1,     /* The token that holds the name of the view */
82862  Token *pName2,     /* The token that holds the name of the view */
82863  Select *pSelect,   /* A SELECT statement that will become the new view */
82864  int isTemp,        /* TRUE for a TEMPORARY view */
82865  int noErr          /* Suppress error messages if VIEW already exists */
82866){
82867  Table *p;
82868  int n;
82869  const char *z;
82870  Token sEnd;
82871  DbFixer sFix;
82872  Token *pName = 0;
82873  int iDb;
82874  sqlite3 *db = pParse->db;
82875
82876  if( pParse->nVar>0 ){
82877    sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
82878    sqlite3SelectDelete(db, pSelect);
82879    return;
82880  }
82881  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
82882  p = pParse->pNewTable;
82883  if( p==0 || pParse->nErr ){
82884    sqlite3SelectDelete(db, pSelect);
82885    return;
82886  }
82887  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
82888  iDb = sqlite3SchemaToIndex(db, p->pSchema);
82889  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
82890    && sqlite3FixSelect(&sFix, pSelect)
82891  ){
82892    sqlite3SelectDelete(db, pSelect);
82893    return;
82894  }
82895
82896  /* Make a copy of the entire SELECT statement that defines the view.
82897  ** This will force all the Expr.token.z values to be dynamically
82898  ** allocated rather than point to the input string - which means that
82899  ** they will persist after the current sqlite3_exec() call returns.
82900  */
82901  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
82902  sqlite3SelectDelete(db, pSelect);
82903  if( db->mallocFailed ){
82904    return;
82905  }
82906  if( !db->init.busy ){
82907    sqlite3ViewGetColumnNames(pParse, p);
82908  }
82909
82910  /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
82911  ** the end.
82912  */
82913  sEnd = pParse->sLastToken;
82914  if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
82915    sEnd.z += sEnd.n;
82916  }
82917  sEnd.n = 0;
82918  n = (int)(sEnd.z - pBegin->z);
82919  z = pBegin->z;
82920  while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
82921  sEnd.z = &z[n-1];
82922  sEnd.n = 1;
82923
82924  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
82925  sqlite3EndTable(pParse, 0, &sEnd, 0);
82926  return;
82927}
82928#endif /* SQLITE_OMIT_VIEW */
82929
82930#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
82931/*
82932** The Table structure pTable is really a VIEW.  Fill in the names of
82933** the columns of the view in the pTable structure.  Return the number
82934** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
82935*/
82936SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
82937  Table *pSelTab;   /* A fake table from which we get the result set */
82938  Select *pSel;     /* Copy of the SELECT that implements the view */
82939  int nErr = 0;     /* Number of errors encountered */
82940  int n;            /* Temporarily holds the number of cursors assigned */
82941  sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
82942  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
82943
82944  assert( pTable );
82945
82946#ifndef SQLITE_OMIT_VIRTUALTABLE
82947  if( sqlite3VtabCallConnect(pParse, pTable) ){
82948    return SQLITE_ERROR;
82949  }
82950  if( IsVirtual(pTable) ) return 0;
82951#endif
82952
82953#ifndef SQLITE_OMIT_VIEW
82954  /* A positive nCol means the columns names for this view are
82955  ** already known.
82956  */
82957  if( pTable->nCol>0 ) return 0;
82958
82959  /* A negative nCol is a special marker meaning that we are currently
82960  ** trying to compute the column names.  If we enter this routine with
82961  ** a negative nCol, it means two or more views form a loop, like this:
82962  **
82963  **     CREATE VIEW one AS SELECT * FROM two;
82964  **     CREATE VIEW two AS SELECT * FROM one;
82965  **
82966  ** Actually, the error above is now caught prior to reaching this point.
82967  ** But the following test is still important as it does come up
82968  ** in the following:
82969  **
82970  **     CREATE TABLE main.ex1(a);
82971  **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
82972  **     SELECT * FROM temp.ex1;
82973  */
82974  if( pTable->nCol<0 ){
82975    sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
82976    return 1;
82977  }
82978  assert( pTable->nCol>=0 );
82979
82980  /* If we get this far, it means we need to compute the table names.
82981  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
82982  ** "*" elements in the results set of the view and will assign cursors
82983  ** to the elements of the FROM clause.  But we do not want these changes
82984  ** to be permanent.  So the computation is done on a copy of the SELECT
82985  ** statement that defines the view.
82986  */
82987  assert( pTable->pSelect );
82988  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
82989  if( pSel ){
82990    u8 enableLookaside = db->lookaside.bEnabled;
82991    n = pParse->nTab;
82992    sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
82993    pTable->nCol = -1;
82994    db->lookaside.bEnabled = 0;
82995#ifndef SQLITE_OMIT_AUTHORIZATION
82996    xAuth = db->xAuth;
82997    db->xAuth = 0;
82998    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
82999    db->xAuth = xAuth;
83000#else
83001    pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
83002#endif
83003    db->lookaside.bEnabled = enableLookaside;
83004    pParse->nTab = n;
83005    if( pSelTab ){
83006      assert( pTable->aCol==0 );
83007      pTable->nCol = pSelTab->nCol;
83008      pTable->aCol = pSelTab->aCol;
83009      pSelTab->nCol = 0;
83010      pSelTab->aCol = 0;
83011      sqlite3DeleteTable(db, pSelTab);
83012      assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
83013      pTable->pSchema->flags |= DB_UnresetViews;
83014    }else{
83015      pTable->nCol = 0;
83016      nErr++;
83017    }
83018    sqlite3SelectDelete(db, pSel);
83019  } else {
83020    nErr++;
83021  }
83022#endif /* SQLITE_OMIT_VIEW */
83023  return nErr;
83024}
83025#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
83026
83027#ifndef SQLITE_OMIT_VIEW
83028/*
83029** Clear the column names from every VIEW in database idx.
83030*/
83031static void sqliteViewResetAll(sqlite3 *db, int idx){
83032  HashElem *i;
83033  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
83034  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
83035  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
83036    Table *pTab = sqliteHashData(i);
83037    if( pTab->pSelect ){
83038      sqliteDeleteColumnNames(db, pTab);
83039      pTab->aCol = 0;
83040      pTab->nCol = 0;
83041    }
83042  }
83043  DbClearProperty(db, idx, DB_UnresetViews);
83044}
83045#else
83046# define sqliteViewResetAll(A,B)
83047#endif /* SQLITE_OMIT_VIEW */
83048
83049/*
83050** This function is called by the VDBE to adjust the internal schema
83051** used by SQLite when the btree layer moves a table root page. The
83052** root-page of a table or index in database iDb has changed from iFrom
83053** to iTo.
83054**
83055** Ticket #1728:  The symbol table might still contain information
83056** on tables and/or indices that are the process of being deleted.
83057** If you are unlucky, one of those deleted indices or tables might
83058** have the same rootpage number as the real table or index that is
83059** being moved.  So we cannot stop searching after the first match
83060** because the first match might be for one of the deleted indices
83061** or tables and not the table/index that is actually being moved.
83062** We must continue looping until all tables and indices with
83063** rootpage==iFrom have been converted to have a rootpage of iTo
83064** in order to be certain that we got the right one.
83065*/
83066#ifndef SQLITE_OMIT_AUTOVACUUM
83067SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
83068  HashElem *pElem;
83069  Hash *pHash;
83070  Db *pDb;
83071
83072  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83073  pDb = &db->aDb[iDb];
83074  pHash = &pDb->pSchema->tblHash;
83075  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
83076    Table *pTab = sqliteHashData(pElem);
83077    if( pTab->tnum==iFrom ){
83078      pTab->tnum = iTo;
83079    }
83080  }
83081  pHash = &pDb->pSchema->idxHash;
83082  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
83083    Index *pIdx = sqliteHashData(pElem);
83084    if( pIdx->tnum==iFrom ){
83085      pIdx->tnum = iTo;
83086    }
83087  }
83088}
83089#endif
83090
83091/*
83092** Write code to erase the table with root-page iTable from database iDb.
83093** Also write code to modify the sqlite_master table and internal schema
83094** if a root-page of another table is moved by the btree-layer whilst
83095** erasing iTable (this can happen with an auto-vacuum database).
83096*/
83097static void destroyRootPage(Parse *pParse, int iTable, int iDb){
83098  Vdbe *v = sqlite3GetVdbe(pParse);
83099  int r1 = sqlite3GetTempReg(pParse);
83100  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
83101  sqlite3MayAbort(pParse);
83102#ifndef SQLITE_OMIT_AUTOVACUUM
83103  /* OP_Destroy stores an in integer r1. If this integer
83104  ** is non-zero, then it is the root page number of a table moved to
83105  ** location iTable. The following code modifies the sqlite_master table to
83106  ** reflect this.
83107  **
83108  ** The "#NNN" in the SQL is a special constant that means whatever value
83109  ** is in register NNN.  See grammar rules associated with the TK_REGISTER
83110  ** token for additional information.
83111  */
83112  sqlite3NestedParse(pParse,
83113     "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
83114     pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
83115#endif
83116  sqlite3ReleaseTempReg(pParse, r1);
83117}
83118
83119/*
83120** Write VDBE code to erase table pTab and all associated indices on disk.
83121** Code to update the sqlite_master tables and internal schema definitions
83122** in case a root-page belonging to another table is moved by the btree layer
83123** is also added (this can happen with an auto-vacuum database).
83124*/
83125static void destroyTable(Parse *pParse, Table *pTab){
83126#ifdef SQLITE_OMIT_AUTOVACUUM
83127  Index *pIdx;
83128  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83129  destroyRootPage(pParse, pTab->tnum, iDb);
83130  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83131    destroyRootPage(pParse, pIdx->tnum, iDb);
83132  }
83133#else
83134  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
83135  ** is not defined), then it is important to call OP_Destroy on the
83136  ** table and index root-pages in order, starting with the numerically
83137  ** largest root-page number. This guarantees that none of the root-pages
83138  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
83139  ** following were coded:
83140  **
83141  ** OP_Destroy 4 0
83142  ** ...
83143  ** OP_Destroy 5 0
83144  **
83145  ** and root page 5 happened to be the largest root-page number in the
83146  ** database, then root page 5 would be moved to page 4 by the
83147  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
83148  ** a free-list page.
83149  */
83150  int iTab = pTab->tnum;
83151  int iDestroyed = 0;
83152
83153  while( 1 ){
83154    Index *pIdx;
83155    int iLargest = 0;
83156
83157    if( iDestroyed==0 || iTab<iDestroyed ){
83158      iLargest = iTab;
83159    }
83160    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83161      int iIdx = pIdx->tnum;
83162      assert( pIdx->pSchema==pTab->pSchema );
83163      if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
83164        iLargest = iIdx;
83165      }
83166    }
83167    if( iLargest==0 ){
83168      return;
83169    }else{
83170      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
83171      destroyRootPage(pParse, iLargest, iDb);
83172      iDestroyed = iLargest;
83173    }
83174  }
83175#endif
83176}
83177
83178/*
83179** Remove entries from the sqlite_statN tables (for N in (1,2,3))
83180** after a DROP INDEX or DROP TABLE command.
83181*/
83182static void sqlite3ClearStatTables(
83183  Parse *pParse,         /* The parsing context */
83184  int iDb,               /* The database number */
83185  const char *zType,     /* "idx" or "tbl" */
83186  const char *zName      /* Name of index or table */
83187){
83188  int i;
83189  const char *zDbName = pParse->db->aDb[iDb].zName;
83190  for(i=1; i<=3; i++){
83191    char zTab[24];
83192    sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
83193    if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
83194      sqlite3NestedParse(pParse,
83195        "DELETE FROM %Q.%s WHERE %s=%Q",
83196        zDbName, zTab, zType, zName
83197      );
83198    }
83199  }
83200}
83201
83202/*
83203** Generate code to drop a table.
83204*/
83205SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
83206  Vdbe *v;
83207  sqlite3 *db = pParse->db;
83208  Trigger *pTrigger;
83209  Db *pDb = &db->aDb[iDb];
83210
83211  v = sqlite3GetVdbe(pParse);
83212  assert( v!=0 );
83213  sqlite3BeginWriteOperation(pParse, 1, iDb);
83214
83215#ifndef SQLITE_OMIT_VIRTUALTABLE
83216  if( IsVirtual(pTab) ){
83217    sqlite3VdbeAddOp0(v, OP_VBegin);
83218  }
83219#endif
83220
83221  /* Drop all triggers associated with the table being dropped. Code
83222  ** is generated to remove entries from sqlite_master and/or
83223  ** sqlite_temp_master if required.
83224  */
83225  pTrigger = sqlite3TriggerList(pParse, pTab);
83226  while( pTrigger ){
83227    assert( pTrigger->pSchema==pTab->pSchema ||
83228        pTrigger->pSchema==db->aDb[1].pSchema );
83229    sqlite3DropTriggerPtr(pParse, pTrigger);
83230    pTrigger = pTrigger->pNext;
83231  }
83232
83233#ifndef SQLITE_OMIT_AUTOINCREMENT
83234  /* Remove any entries of the sqlite_sequence table associated with
83235  ** the table being dropped. This is done before the table is dropped
83236  ** at the btree level, in case the sqlite_sequence table needs to
83237  ** move as a result of the drop (can happen in auto-vacuum mode).
83238  */
83239  if( pTab->tabFlags & TF_Autoincrement ){
83240    sqlite3NestedParse(pParse,
83241      "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
83242      pDb->zName, pTab->zName
83243    );
83244  }
83245#endif
83246
83247  /* Drop all SQLITE_MASTER table and index entries that refer to the
83248  ** table. The program name loops through the master table and deletes
83249  ** every row that refers to a table of the same name as the one being
83250  ** dropped. Triggers are handled seperately because a trigger can be
83251  ** created in the temp database that refers to a table in another
83252  ** database.
83253  */
83254  sqlite3NestedParse(pParse,
83255      "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
83256      pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
83257  if( !isView && !IsVirtual(pTab) ){
83258    destroyTable(pParse, pTab);
83259  }
83260
83261  /* Remove the table entry from SQLite's internal schema and modify
83262  ** the schema cookie.
83263  */
83264  if( IsVirtual(pTab) ){
83265    sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
83266  }
83267  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
83268  sqlite3ChangeCookie(pParse, iDb);
83269  sqliteViewResetAll(db, iDb);
83270}
83271
83272/*
83273** This routine is called to do the work of a DROP TABLE statement.
83274** pName is the name of the table to be dropped.
83275*/
83276SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
83277  Table *pTab;
83278  Vdbe *v;
83279  sqlite3 *db = pParse->db;
83280  int iDb;
83281
83282  if( db->mallocFailed ){
83283    goto exit_drop_table;
83284  }
83285  assert( pParse->nErr==0 );
83286  assert( pName->nSrc==1 );
83287  if( noErr ) db->suppressErr++;
83288  pTab = sqlite3LocateTable(pParse, isView,
83289                            pName->a[0].zName, pName->a[0].zDatabase);
83290  if( noErr ) db->suppressErr--;
83291
83292  if( pTab==0 ){
83293    if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
83294    goto exit_drop_table;
83295  }
83296  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83297  assert( iDb>=0 && iDb<db->nDb );
83298
83299  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
83300  ** it is initialized.
83301  */
83302  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
83303    goto exit_drop_table;
83304  }
83305#ifndef SQLITE_OMIT_AUTHORIZATION
83306  {
83307    int code;
83308    const char *zTab = SCHEMA_TABLE(iDb);
83309    const char *zDb = db->aDb[iDb].zName;
83310    const char *zArg2 = 0;
83311    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
83312      goto exit_drop_table;
83313    }
83314    if( isView ){
83315      if( !OMIT_TEMPDB && iDb==1 ){
83316        code = SQLITE_DROP_TEMP_VIEW;
83317      }else{
83318        code = SQLITE_DROP_VIEW;
83319      }
83320#ifndef SQLITE_OMIT_VIRTUALTABLE
83321    }else if( IsVirtual(pTab) ){
83322      code = SQLITE_DROP_VTABLE;
83323      zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
83324#endif
83325    }else{
83326      if( !OMIT_TEMPDB && iDb==1 ){
83327        code = SQLITE_DROP_TEMP_TABLE;
83328      }else{
83329        code = SQLITE_DROP_TABLE;
83330      }
83331    }
83332    if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
83333      goto exit_drop_table;
83334    }
83335    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
83336      goto exit_drop_table;
83337    }
83338  }
83339#endif
83340  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
83341    && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
83342    sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
83343    goto exit_drop_table;
83344  }
83345
83346#ifndef SQLITE_OMIT_VIEW
83347  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
83348  ** on a table.
83349  */
83350  if( isView && pTab->pSelect==0 ){
83351    sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
83352    goto exit_drop_table;
83353  }
83354  if( !isView && pTab->pSelect ){
83355    sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
83356    goto exit_drop_table;
83357  }
83358#endif
83359
83360  /* Generate code to remove the table from the master table
83361  ** on disk.
83362  */
83363  v = sqlite3GetVdbe(pParse);
83364  if( v ){
83365    sqlite3BeginWriteOperation(pParse, 1, iDb);
83366    sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
83367    sqlite3FkDropTable(pParse, pName, pTab);
83368    sqlite3CodeDropTable(pParse, pTab, iDb, isView);
83369  }
83370
83371exit_drop_table:
83372  sqlite3SrcListDelete(db, pName);
83373}
83374
83375/*
83376** This routine is called to create a new foreign key on the table
83377** currently under construction.  pFromCol determines which columns
83378** in the current table point to the foreign key.  If pFromCol==0 then
83379** connect the key to the last column inserted.  pTo is the name of
83380** the table referred to.  pToCol is a list of tables in the other
83381** pTo table that the foreign key points to.  flags contains all
83382** information about the conflict resolution algorithms specified
83383** in the ON DELETE, ON UPDATE and ON INSERT clauses.
83384**
83385** An FKey structure is created and added to the table currently
83386** under construction in the pParse->pNewTable field.
83387**
83388** The foreign key is set for IMMEDIATE processing.  A subsequent call
83389** to sqlite3DeferForeignKey() might change this to DEFERRED.
83390*/
83391SQLITE_PRIVATE void sqlite3CreateForeignKey(
83392  Parse *pParse,       /* Parsing context */
83393  ExprList *pFromCol,  /* Columns in this table that point to other table */
83394  Token *pTo,          /* Name of the other table */
83395  ExprList *pToCol,    /* Columns in the other table */
83396  int flags            /* Conflict resolution algorithms. */
83397){
83398  sqlite3 *db = pParse->db;
83399#ifndef SQLITE_OMIT_FOREIGN_KEY
83400  FKey *pFKey = 0;
83401  FKey *pNextTo;
83402  Table *p = pParse->pNewTable;
83403  int nByte;
83404  int i;
83405  int nCol;
83406  char *z;
83407
83408  assert( pTo!=0 );
83409  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
83410  if( pFromCol==0 ){
83411    int iCol = p->nCol-1;
83412    if( NEVER(iCol<0) ) goto fk_end;
83413    if( pToCol && pToCol->nExpr!=1 ){
83414      sqlite3ErrorMsg(pParse, "foreign key on %s"
83415         " should reference only one column of table %T",
83416         p->aCol[iCol].zName, pTo);
83417      goto fk_end;
83418    }
83419    nCol = 1;
83420  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
83421    sqlite3ErrorMsg(pParse,
83422        "number of columns in foreign key does not match the number of "
83423        "columns in the referenced table");
83424    goto fk_end;
83425  }else{
83426    nCol = pFromCol->nExpr;
83427  }
83428  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
83429  if( pToCol ){
83430    for(i=0; i<pToCol->nExpr; i++){
83431      nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
83432    }
83433  }
83434  pFKey = sqlite3DbMallocZero(db, nByte );
83435  if( pFKey==0 ){
83436    goto fk_end;
83437  }
83438  pFKey->pFrom = p;
83439  pFKey->pNextFrom = p->pFKey;
83440  z = (char*)&pFKey->aCol[nCol];
83441  pFKey->zTo = z;
83442  memcpy(z, pTo->z, pTo->n);
83443  z[pTo->n] = 0;
83444  sqlite3Dequote(z);
83445  z += pTo->n+1;
83446  pFKey->nCol = nCol;
83447  if( pFromCol==0 ){
83448    pFKey->aCol[0].iFrom = p->nCol-1;
83449  }else{
83450    for(i=0; i<nCol; i++){
83451      int j;
83452      for(j=0; j<p->nCol; j++){
83453        if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
83454          pFKey->aCol[i].iFrom = j;
83455          break;
83456        }
83457      }
83458      if( j>=p->nCol ){
83459        sqlite3ErrorMsg(pParse,
83460          "unknown column \"%s\" in foreign key definition",
83461          pFromCol->a[i].zName);
83462        goto fk_end;
83463      }
83464    }
83465  }
83466  if( pToCol ){
83467    for(i=0; i<nCol; i++){
83468      int n = sqlite3Strlen30(pToCol->a[i].zName);
83469      pFKey->aCol[i].zCol = z;
83470      memcpy(z, pToCol->a[i].zName, n);
83471      z[n] = 0;
83472      z += n+1;
83473    }
83474  }
83475  pFKey->isDeferred = 0;
83476  pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
83477  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
83478
83479  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
83480  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
83481      pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
83482  );
83483  if( pNextTo==pFKey ){
83484    db->mallocFailed = 1;
83485    goto fk_end;
83486  }
83487  if( pNextTo ){
83488    assert( pNextTo->pPrevTo==0 );
83489    pFKey->pNextTo = pNextTo;
83490    pNextTo->pPrevTo = pFKey;
83491  }
83492
83493  /* Link the foreign key to the table as the last step.
83494  */
83495  p->pFKey = pFKey;
83496  pFKey = 0;
83497
83498fk_end:
83499  sqlite3DbFree(db, pFKey);
83500#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
83501  sqlite3ExprListDelete(db, pFromCol);
83502  sqlite3ExprListDelete(db, pToCol);
83503}
83504
83505/*
83506** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
83507** clause is seen as part of a foreign key definition.  The isDeferred
83508** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
83509** The behavior of the most recently created foreign key is adjusted
83510** accordingly.
83511*/
83512SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
83513#ifndef SQLITE_OMIT_FOREIGN_KEY
83514  Table *pTab;
83515  FKey *pFKey;
83516  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
83517  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
83518  pFKey->isDeferred = (u8)isDeferred;
83519#endif
83520}
83521
83522/*
83523** Generate code that will erase and refill index *pIdx.  This is
83524** used to initialize a newly created index or to recompute the
83525** content of an index in response to a REINDEX command.
83526**
83527** if memRootPage is not negative, it means that the index is newly
83528** created.  The register specified by memRootPage contains the
83529** root page number of the index.  If memRootPage is negative, then
83530** the index already exists and must be cleared before being refilled and
83531** the root page number of the index is taken from pIndex->tnum.
83532*/
83533static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
83534  Table *pTab = pIndex->pTable;  /* The table that is indexed */
83535  int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
83536  int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
83537  int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
83538  int addr1;                     /* Address of top of loop */
83539  int addr2;                     /* Address to jump to for next iteration */
83540  int tnum;                      /* Root page of index */
83541  Vdbe *v;                       /* Generate code into this virtual machine */
83542  KeyInfo *pKey;                 /* KeyInfo for index */
83543#ifdef SQLITE_OMIT_MERGE_SORT
83544  int regIdxKey;                 /* Registers containing the index key */
83545#endif
83546  int regRecord;                 /* Register holding assemblied index record */
83547  sqlite3 *db = pParse->db;      /* The database connection */
83548  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
83549
83550#ifndef SQLITE_OMIT_AUTHORIZATION
83551  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
83552      db->aDb[iDb].zName ) ){
83553    return;
83554  }
83555#endif
83556
83557  /* Require a write-lock on the table to perform this operation */
83558  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
83559
83560  v = sqlite3GetVdbe(pParse);
83561  if( v==0 ) return;
83562  if( memRootPage>=0 ){
83563    tnum = memRootPage;
83564  }else{
83565    tnum = pIndex->tnum;
83566    sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
83567  }
83568  pKey = sqlite3IndexKeyinfo(pParse, pIndex);
83569  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
83570                    (char *)pKey, P4_KEYINFO_HANDOFF);
83571  if( memRootPage>=0 ){
83572    sqlite3VdbeChangeP5(v, 1);
83573  }
83574
83575#ifndef SQLITE_OMIT_MERGE_SORT
83576  /* Open the sorter cursor if we are to use one. */
83577  iSorter = pParse->nTab++;
83578  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
83579#else
83580  iSorter = iTab;
83581#endif
83582
83583  /* Open the table. Loop through all rows of the table, inserting index
83584  ** records into the sorter. */
83585  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
83586  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
83587  regRecord = sqlite3GetTempReg(pParse);
83588
83589#ifndef SQLITE_OMIT_MERGE_SORT
83590  sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83591  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
83592  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
83593  sqlite3VdbeJumpHere(v, addr1);
83594  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
83595  if( pIndex->onError!=OE_None ){
83596    int j2 = sqlite3VdbeCurrentAddr(v) + 3;
83597    sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
83598    addr2 = sqlite3VdbeCurrentAddr(v);
83599    sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
83600    sqlite3HaltConstraint(
83601        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC
83602    );
83603  }else{
83604    addr2 = sqlite3VdbeCurrentAddr(v);
83605  }
83606  sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
83607  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
83608  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83609#else
83610  regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
83611  addr2 = addr1 + 1;
83612  if( pIndex->onError!=OE_None ){
83613    const int regRowid = regIdxKey + pIndex->nColumn;
83614    const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
83615    void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
83616
83617    /* The registers accessed by the OP_IsUnique opcode were allocated
83618    ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
83619    ** call above. Just before that function was freed they were released
83620    ** (made available to the compiler for reuse) using
83621    ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
83622    ** opcode use the values stored within seems dangerous. However, since
83623    ** we can be sure that no other temp registers have been allocated
83624    ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
83625    */
83626    sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
83627    sqlite3HaltConstraint(
83628        pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
83629  }
83630  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
83631  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
83632#endif
83633  sqlite3ReleaseTempReg(pParse, regRecord);
83634  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
83635  sqlite3VdbeJumpHere(v, addr1);
83636
83637  sqlite3VdbeAddOp1(v, OP_Close, iTab);
83638  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
83639  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
83640}
83641
83642/*
83643** Create a new index for an SQL table.  pName1.pName2 is the name of the index
83644** and pTblList is the name of the table that is to be indexed.  Both will
83645** be NULL for a primary key or an index that is created to satisfy a
83646** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
83647** as the table to be indexed.  pParse->pNewTable is a table that is
83648** currently being constructed by a CREATE TABLE statement.
83649**
83650** pList is a list of columns to be indexed.  pList will be NULL if this
83651** is a primary key or unique-constraint on the most recent column added
83652** to the table currently under construction.
83653**
83654** If the index is created successfully, return a pointer to the new Index
83655** structure. This is used by sqlite3AddPrimaryKey() to mark the index
83656** as the tables primary key (Index.autoIndex==2).
83657*/
83658SQLITE_PRIVATE Index *sqlite3CreateIndex(
83659  Parse *pParse,     /* All information about this parse */
83660  Token *pName1,     /* First part of index name. May be NULL */
83661  Token *pName2,     /* Second part of index name. May be NULL */
83662  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
83663  ExprList *pList,   /* A list of columns to be indexed */
83664  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
83665  Token *pStart,     /* The CREATE token that begins this statement */
83666  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
83667  int sortOrder,     /* Sort order of primary key when pList==NULL */
83668  int ifNotExist     /* Omit error if index already exists */
83669){
83670  Index *pRet = 0;     /* Pointer to return */
83671  Table *pTab = 0;     /* Table to be indexed */
83672  Index *pIndex = 0;   /* The index to be created */
83673  char *zName = 0;     /* Name of the index */
83674  int nName;           /* Number of characters in zName */
83675  int i, j;
83676  Token nullId;        /* Fake token for an empty ID list */
83677  DbFixer sFix;        /* For assigning database names to pTable */
83678  int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
83679  sqlite3 *db = pParse->db;
83680  Db *pDb;             /* The specific table containing the indexed database */
83681  int iDb;             /* Index of the database that is being written */
83682  Token *pName = 0;    /* Unqualified name of the index to create */
83683  struct ExprList_item *pListItem; /* For looping over pList */
83684  int nCol;
83685  int nExtra = 0;
83686  char *zExtra;
83687
83688  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
83689  assert( pParse->nErr==0 );      /* Never called with prior errors */
83690  if( db->mallocFailed || IN_DECLARE_VTAB ){
83691    goto exit_create_index;
83692  }
83693  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83694    goto exit_create_index;
83695  }
83696
83697  /*
83698  ** Find the table that is to be indexed.  Return early if not found.
83699  */
83700  if( pTblName!=0 ){
83701
83702    /* Use the two-part index name to determine the database
83703    ** to search for the table. 'Fix' the table name to this db
83704    ** before looking up the table.
83705    */
83706    assert( pName1 && pName2 );
83707    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83708    if( iDb<0 ) goto exit_create_index;
83709    assert( pName && pName->z );
83710
83711#ifndef SQLITE_OMIT_TEMPDB
83712    /* If the index name was unqualified, check if the the table
83713    ** is a temp table. If so, set the database to 1. Do not do this
83714    ** if initialising a database schema.
83715    */
83716    if( !db->init.busy ){
83717      pTab = sqlite3SrcListLookup(pParse, pTblName);
83718      if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
83719        iDb = 1;
83720      }
83721    }
83722#endif
83723
83724    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
83725        sqlite3FixSrcList(&sFix, pTblName)
83726    ){
83727      /* Because the parser constructs pTblName from a single identifier,
83728      ** sqlite3FixSrcList can never fail. */
83729      assert(0);
83730    }
83731    pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
83732        pTblName->a[0].zDatabase);
83733    if( !pTab || db->mallocFailed ) goto exit_create_index;
83734    assert( db->aDb[iDb].pSchema==pTab->pSchema );
83735  }else{
83736    assert( pName==0 );
83737    assert( pStart==0 );
83738    pTab = pParse->pNewTable;
83739    if( !pTab ) goto exit_create_index;
83740    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83741  }
83742  pDb = &db->aDb[iDb];
83743
83744  assert( pTab!=0 );
83745  assert( pParse->nErr==0 );
83746  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
83747       && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
83748    sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
83749    goto exit_create_index;
83750  }
83751#ifndef SQLITE_OMIT_VIEW
83752  if( pTab->pSelect ){
83753    sqlite3ErrorMsg(pParse, "views may not be indexed");
83754    goto exit_create_index;
83755  }
83756#endif
83757#ifndef SQLITE_OMIT_VIRTUALTABLE
83758  if( IsVirtual(pTab) ){
83759    sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
83760    goto exit_create_index;
83761  }
83762#endif
83763
83764  /*
83765  ** Find the name of the index.  Make sure there is not already another
83766  ** index or table with the same name.
83767  **
83768  ** Exception:  If we are reading the names of permanent indices from the
83769  ** sqlite_master table (because some other process changed the schema) and
83770  ** one of the index names collides with the name of a temporary table or
83771  ** index, then we will continue to process this index.
83772  **
83773  ** If pName==0 it means that we are
83774  ** dealing with a primary key or UNIQUE constraint.  We have to invent our
83775  ** own name.
83776  */
83777  if( pName ){
83778    zName = sqlite3NameFromToken(db, pName);
83779    if( zName==0 ) goto exit_create_index;
83780    assert( pName->z!=0 );
83781    if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
83782      goto exit_create_index;
83783    }
83784    if( !db->init.busy ){
83785      if( sqlite3FindTable(db, zName, 0)!=0 ){
83786        sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
83787        goto exit_create_index;
83788      }
83789    }
83790    if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
83791      if( !ifNotExist ){
83792        sqlite3ErrorMsg(pParse, "index %s already exists", zName);
83793      }else{
83794        assert( !db->init.busy );
83795        sqlite3CodeVerifySchema(pParse, iDb);
83796      }
83797      goto exit_create_index;
83798    }
83799  }else{
83800    int n;
83801    Index *pLoop;
83802    for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
83803    zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
83804    if( zName==0 ){
83805      goto exit_create_index;
83806    }
83807  }
83808
83809  /* Check for authorization to create an index.
83810  */
83811#ifndef SQLITE_OMIT_AUTHORIZATION
83812  {
83813    const char *zDb = pDb->zName;
83814    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
83815      goto exit_create_index;
83816    }
83817    i = SQLITE_CREATE_INDEX;
83818    if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
83819    if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
83820      goto exit_create_index;
83821    }
83822  }
83823#endif
83824
83825  /* If pList==0, it means this routine was called to make a primary
83826  ** key out of the last column added to the table under construction.
83827  ** So create a fake list to simulate this.
83828  */
83829  if( pList==0 ){
83830    nullId.z = pTab->aCol[pTab->nCol-1].zName;
83831    nullId.n = sqlite3Strlen30((char*)nullId.z);
83832    pList = sqlite3ExprListAppend(pParse, 0, 0);
83833    if( pList==0 ) goto exit_create_index;
83834    sqlite3ExprListSetName(pParse, pList, &nullId, 0);
83835    pList->a[0].sortOrder = (u8)sortOrder;
83836  }
83837
83838  /* Figure out how many bytes of space are required to store explicitly
83839  ** specified collation sequence names.
83840  */
83841  for(i=0; i<pList->nExpr; i++){
83842    Expr *pExpr = pList->a[i].pExpr;
83843    if( pExpr ){
83844      CollSeq *pColl = pExpr->pColl;
83845      /* Either pColl!=0 or there was an OOM failure.  But if an OOM
83846      ** failure we have quit before reaching this point. */
83847      if( ALWAYS(pColl) ){
83848        nExtra += (1 + sqlite3Strlen30(pColl->zName));
83849      }
83850    }
83851  }
83852
83853  /*
83854  ** Allocate the index structure.
83855  */
83856  nName = sqlite3Strlen30(zName);
83857  nCol = pList->nExpr;
83858  pIndex = sqlite3DbMallocZero(db,
83859      ROUND8(sizeof(Index)) +              /* Index structure  */
83860      ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
83861      sizeof(char *)*nCol +                /* Index.azColl     */
83862      sizeof(int)*nCol +                   /* Index.aiColumn   */
83863      sizeof(u8)*nCol +                    /* Index.aSortOrder */
83864      nName + 1 +                          /* Index.zName      */
83865      nExtra                               /* Collation sequence names */
83866  );
83867  if( db->mallocFailed ){
83868    goto exit_create_index;
83869  }
83870  zExtra = (char*)pIndex;
83871  pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
83872  pIndex->azColl = (char**)
83873     ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
83874  assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
83875  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
83876  pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
83877  pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
83878  pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
83879  zExtra = (char *)(&pIndex->zName[nName+1]);
83880  memcpy(pIndex->zName, zName, nName+1);
83881  pIndex->pTable = pTab;
83882  pIndex->nColumn = pList->nExpr;
83883  pIndex->onError = (u8)onError;
83884  pIndex->autoIndex = (u8)(pName==0);
83885  pIndex->pSchema = db->aDb[iDb].pSchema;
83886  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83887
83888  /* Check to see if we should honor DESC requests on index columns
83889  */
83890  if( pDb->pSchema->file_format>=4 ){
83891    sortOrderMask = -1;   /* Honor DESC */
83892  }else{
83893    sortOrderMask = 0;    /* Ignore DESC */
83894  }
83895
83896  /* Scan the names of the columns of the table to be indexed and
83897  ** load the column indices into the Index structure.  Report an error
83898  ** if any column is not found.
83899  **
83900  ** TODO:  Add a test to make sure that the same column is not named
83901  ** more than once within the same index.  Only the first instance of
83902  ** the column will ever be used by the optimizer.  Note that using the
83903  ** same column more than once cannot be an error because that would
83904  ** break backwards compatibility - it needs to be a warning.
83905  */
83906  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
83907    const char *zColName = pListItem->zName;
83908    Column *pTabCol;
83909    int requestedSortOrder;
83910    char *zColl;                   /* Collation sequence name */
83911
83912    for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
83913      if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
83914    }
83915    if( j>=pTab->nCol ){
83916      sqlite3ErrorMsg(pParse, "table %s has no column named %s",
83917        pTab->zName, zColName);
83918      pParse->checkSchema = 1;
83919      goto exit_create_index;
83920    }
83921    pIndex->aiColumn[i] = j;
83922    /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
83923    ** the way the "idxlist" non-terminal is constructed by the parser,
83924    ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
83925    ** must exist or else there must have been an OOM error.  But if there
83926    ** was an OOM error, we would never reach this point. */
83927    if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
83928      int nColl;
83929      zColl = pListItem->pExpr->pColl->zName;
83930      nColl = sqlite3Strlen30(zColl) + 1;
83931      assert( nExtra>=nColl );
83932      memcpy(zExtra, zColl, nColl);
83933      zColl = zExtra;
83934      zExtra += nColl;
83935      nExtra -= nColl;
83936    }else{
83937      zColl = pTab->aCol[j].zColl;
83938      if( !zColl ){
83939        zColl = db->pDfltColl->zName;
83940      }
83941    }
83942    if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
83943      goto exit_create_index;
83944    }
83945    pIndex->azColl[i] = zColl;
83946    requestedSortOrder = pListItem->sortOrder & sortOrderMask;
83947    pIndex->aSortOrder[i] = (u8)requestedSortOrder;
83948  }
83949  sqlite3DefaultRowEst(pIndex);
83950
83951  if( pTab==pParse->pNewTable ){
83952    /* This routine has been called to create an automatic index as a
83953    ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
83954    ** a PRIMARY KEY or UNIQUE clause following the column definitions.
83955    ** i.e. one of:
83956    **
83957    ** CREATE TABLE t(x PRIMARY KEY, y);
83958    ** CREATE TABLE t(x, y, UNIQUE(x, y));
83959    **
83960    ** Either way, check to see if the table already has such an index. If
83961    ** so, don't bother creating this one. This only applies to
83962    ** automatically created indices. Users can do as they wish with
83963    ** explicit indices.
83964    **
83965    ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
83966    ** (and thus suppressing the second one) even if they have different
83967    ** sort orders.
83968    **
83969    ** If there are different collating sequences or if the columns of
83970    ** the constraint occur in different orders, then the constraints are
83971    ** considered distinct and both result in separate indices.
83972    */
83973    Index *pIdx;
83974    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83975      int k;
83976      assert( pIdx->onError!=OE_None );
83977      assert( pIdx->autoIndex );
83978      assert( pIndex->onError!=OE_None );
83979
83980      if( pIdx->nColumn!=pIndex->nColumn ) continue;
83981      for(k=0; k<pIdx->nColumn; k++){
83982        const char *z1;
83983        const char *z2;
83984        if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
83985        z1 = pIdx->azColl[k];
83986        z2 = pIndex->azColl[k];
83987        if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
83988      }
83989      if( k==pIdx->nColumn ){
83990        if( pIdx->onError!=pIndex->onError ){
83991          /* This constraint creates the same index as a previous
83992          ** constraint specified somewhere in the CREATE TABLE statement.
83993          ** However the ON CONFLICT clauses are different. If both this
83994          ** constraint and the previous equivalent constraint have explicit
83995          ** ON CONFLICT clauses this is an error. Otherwise, use the
83996          ** explicitly specified behaviour for the index.
83997          */
83998          if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
83999            sqlite3ErrorMsg(pParse,
84000                "conflicting ON CONFLICT clauses specified", 0);
84001          }
84002          if( pIdx->onError==OE_Default ){
84003            pIdx->onError = pIndex->onError;
84004          }
84005        }
84006        goto exit_create_index;
84007      }
84008    }
84009  }
84010
84011  /* Link the new Index structure to its table and to the other
84012  ** in-memory database structures.
84013  */
84014  if( db->init.busy ){
84015    Index *p;
84016    assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
84017    p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
84018                          pIndex->zName, sqlite3Strlen30(pIndex->zName),
84019                          pIndex);
84020    if( p ){
84021      assert( p==pIndex );  /* Malloc must have failed */
84022      db->mallocFailed = 1;
84023      goto exit_create_index;
84024    }
84025    db->flags |= SQLITE_InternChanges;
84026    if( pTblName!=0 ){
84027      pIndex->tnum = db->init.newTnum;
84028    }
84029  }
84030
84031  /* If the db->init.busy is 0 then create the index on disk.  This
84032  ** involves writing the index into the master table and filling in the
84033  ** index with the current table contents.
84034  **
84035  ** The db->init.busy is 0 when the user first enters a CREATE INDEX
84036  ** command.  db->init.busy is 1 when a database is opened and
84037  ** CREATE INDEX statements are read out of the master table.  In
84038  ** the latter case the index already exists on disk, which is why
84039  ** we don't want to recreate it.
84040  **
84041  ** If pTblName==0 it means this index is generated as a primary key
84042  ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
84043  ** has just been created, it contains no data and the index initialization
84044  ** step can be skipped.
84045  */
84046  else{ /* if( db->init.busy==0 ) */
84047    Vdbe *v;
84048    char *zStmt;
84049    int iMem = ++pParse->nMem;
84050
84051    v = sqlite3GetVdbe(pParse);
84052    if( v==0 ) goto exit_create_index;
84053
84054
84055    /* Create the rootpage for the index
84056    */
84057    sqlite3BeginWriteOperation(pParse, 1, iDb);
84058    sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
84059
84060    /* Gather the complete text of the CREATE INDEX statement into
84061    ** the zStmt variable
84062    */
84063    if( pStart ){
84064      assert( pEnd!=0 );
84065      /* A named index with an explicit CREATE INDEX statement */
84066      zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
84067        onError==OE_None ? "" : " UNIQUE",
84068        (int)(pEnd->z - pName->z) + 1,
84069        pName->z);
84070    }else{
84071      /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
84072      /* zStmt = sqlite3MPrintf(""); */
84073      zStmt = 0;
84074    }
84075
84076    /* Add an entry in sqlite_master for this index
84077    */
84078    sqlite3NestedParse(pParse,
84079        "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
84080        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
84081        pIndex->zName,
84082        pTab->zName,
84083        iMem,
84084        zStmt
84085    );
84086    sqlite3DbFree(db, zStmt);
84087
84088    /* Fill the index with data and reparse the schema. Code an OP_Expire
84089    ** to invalidate all pre-compiled statements.
84090    */
84091    if( pTblName ){
84092      sqlite3RefillIndex(pParse, pIndex, iMem);
84093      sqlite3ChangeCookie(pParse, iDb);
84094      sqlite3VdbeAddParseSchemaOp(v, iDb,
84095         sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
84096      sqlite3VdbeAddOp1(v, OP_Expire, 0);
84097    }
84098  }
84099
84100  /* When adding an index to the list of indices for a table, make
84101  ** sure all indices labeled OE_Replace come after all those labeled
84102  ** OE_Ignore.  This is necessary for the correct constraint check
84103  ** processing (in sqlite3GenerateConstraintChecks()) as part of
84104  ** UPDATE and INSERT statements.
84105  */
84106  if( db->init.busy || pTblName==0 ){
84107    if( onError!=OE_Replace || pTab->pIndex==0
84108         || pTab->pIndex->onError==OE_Replace){
84109      pIndex->pNext = pTab->pIndex;
84110      pTab->pIndex = pIndex;
84111    }else{
84112      Index *pOther = pTab->pIndex;
84113      while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
84114        pOther = pOther->pNext;
84115      }
84116      pIndex->pNext = pOther->pNext;
84117      pOther->pNext = pIndex;
84118    }
84119    pRet = pIndex;
84120    pIndex = 0;
84121  }
84122
84123  /* Clean up before exiting */
84124exit_create_index:
84125  if( pIndex ){
84126    sqlite3DbFree(db, pIndex->zColAff);
84127    sqlite3DbFree(db, pIndex);
84128  }
84129  sqlite3ExprListDelete(db, pList);
84130  sqlite3SrcListDelete(db, pTblName);
84131  sqlite3DbFree(db, zName);
84132  return pRet;
84133}
84134
84135/*
84136** Fill the Index.aiRowEst[] array with default information - information
84137** to be used when we have not run the ANALYZE command.
84138**
84139** aiRowEst[0] is suppose to contain the number of elements in the index.
84140** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
84141** number of rows in the table that match any particular value of the
84142** first column of the index.  aiRowEst[2] is an estimate of the number
84143** of rows that match any particular combiniation of the first 2 columns
84144** of the index.  And so forth.  It must always be the case that
84145*
84146**           aiRowEst[N]<=aiRowEst[N-1]
84147**           aiRowEst[N]>=1
84148**
84149** Apart from that, we have little to go on besides intuition as to
84150** how aiRowEst[] should be initialized.  The numbers generated here
84151** are based on typical values found in actual indices.
84152*/
84153SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
84154  tRowcnt *a = pIdx->aiRowEst;
84155  int i;
84156  tRowcnt n;
84157  assert( a!=0 );
84158  a[0] = pIdx->pTable->nRowEst;
84159  if( a[0]<10 ) a[0] = 10;
84160  n = 10;
84161  for(i=1; i<=pIdx->nColumn; i++){
84162    a[i] = n;
84163    if( n>5 ) n--;
84164  }
84165  if( pIdx->onError!=OE_None ){
84166    a[pIdx->nColumn] = 1;
84167  }
84168}
84169
84170/*
84171** This routine will drop an existing named index.  This routine
84172** implements the DROP INDEX statement.
84173*/
84174SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
84175  Index *pIndex;
84176  Vdbe *v;
84177  sqlite3 *db = pParse->db;
84178  int iDb;
84179
84180  assert( pParse->nErr==0 );   /* Never called with prior errors */
84181  if( db->mallocFailed ){
84182    goto exit_drop_index;
84183  }
84184  assert( pName->nSrc==1 );
84185  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84186    goto exit_drop_index;
84187  }
84188  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
84189  if( pIndex==0 ){
84190    if( !ifExists ){
84191      sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
84192    }else{
84193      sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
84194    }
84195    pParse->checkSchema = 1;
84196    goto exit_drop_index;
84197  }
84198  if( pIndex->autoIndex ){
84199    sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
84200      "or PRIMARY KEY constraint cannot be dropped", 0);
84201    goto exit_drop_index;
84202  }
84203  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
84204#ifndef SQLITE_OMIT_AUTHORIZATION
84205  {
84206    int code = SQLITE_DROP_INDEX;
84207    Table *pTab = pIndex->pTable;
84208    const char *zDb = db->aDb[iDb].zName;
84209    const char *zTab = SCHEMA_TABLE(iDb);
84210    if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
84211      goto exit_drop_index;
84212    }
84213    if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
84214    if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
84215      goto exit_drop_index;
84216    }
84217  }
84218#endif
84219
84220  /* Generate code to remove the index and from the master table */
84221  v = sqlite3GetVdbe(pParse);
84222  if( v ){
84223    sqlite3BeginWriteOperation(pParse, 1, iDb);
84224    sqlite3NestedParse(pParse,
84225       "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
84226       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
84227    );
84228    sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
84229    sqlite3ChangeCookie(pParse, iDb);
84230    destroyRootPage(pParse, pIndex->tnum, iDb);
84231    sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
84232  }
84233
84234exit_drop_index:
84235  sqlite3SrcListDelete(db, pName);
84236}
84237
84238/*
84239** pArray is a pointer to an array of objects.  Each object in the
84240** array is szEntry bytes in size.  This routine allocates a new
84241** object on the end of the array.
84242**
84243** *pnEntry is the number of entries already in use.  *pnAlloc is
84244** the previously allocated size of the array.  initSize is the
84245** suggested initial array size allocation.
84246**
84247** The index of the new entry is returned in *pIdx.
84248**
84249** This routine returns a pointer to the array of objects.  This
84250** might be the same as the pArray parameter or it might be a different
84251** pointer if the array was resized.
84252*/
84253SQLITE_PRIVATE void *sqlite3ArrayAllocate(
84254  sqlite3 *db,      /* Connection to notify of malloc failures */
84255  void *pArray,     /* Array of objects.  Might be reallocated */
84256  int szEntry,      /* Size of each object in the array */
84257  int *pnEntry,     /* Number of objects currently in use */
84258  int *pIdx         /* Write the index of a new slot here */
84259){
84260  char *z;
84261  int n = *pnEntry;
84262  if( (n & (n-1))==0 ){
84263    int sz = (n==0) ? 1 : 2*n;
84264    void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
84265    if( pNew==0 ){
84266      *pIdx = -1;
84267      return pArray;
84268    }
84269    pArray = pNew;
84270  }
84271  z = (char*)pArray;
84272  memset(&z[n * szEntry], 0, szEntry);
84273  *pIdx = n;
84274  ++*pnEntry;
84275  return pArray;
84276}
84277
84278/*
84279** Append a new element to the given IdList.  Create a new IdList if
84280** need be.
84281**
84282** A new IdList is returned, or NULL if malloc() fails.
84283*/
84284SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
84285  int i;
84286  if( pList==0 ){
84287    pList = sqlite3DbMallocZero(db, sizeof(IdList) );
84288    if( pList==0 ) return 0;
84289  }
84290  pList->a = sqlite3ArrayAllocate(
84291      db,
84292      pList->a,
84293      sizeof(pList->a[0]),
84294      &pList->nId,
84295      &i
84296  );
84297  if( i<0 ){
84298    sqlite3IdListDelete(db, pList);
84299    return 0;
84300  }
84301  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
84302  return pList;
84303}
84304
84305/*
84306** Delete an IdList.
84307*/
84308SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
84309  int i;
84310  if( pList==0 ) return;
84311  for(i=0; i<pList->nId; i++){
84312    sqlite3DbFree(db, pList->a[i].zName);
84313  }
84314  sqlite3DbFree(db, pList->a);
84315  sqlite3DbFree(db, pList);
84316}
84317
84318/*
84319** Return the index in pList of the identifier named zId.  Return -1
84320** if not found.
84321*/
84322SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
84323  int i;
84324  if( pList==0 ) return -1;
84325  for(i=0; i<pList->nId; i++){
84326    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
84327  }
84328  return -1;
84329}
84330
84331/*
84332** Expand the space allocated for the given SrcList object by
84333** creating nExtra new slots beginning at iStart.  iStart is zero based.
84334** New slots are zeroed.
84335**
84336** For example, suppose a SrcList initially contains two entries: A,B.
84337** To append 3 new entries onto the end, do this:
84338**
84339**    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
84340**
84341** After the call above it would contain:  A, B, nil, nil, nil.
84342** If the iStart argument had been 1 instead of 2, then the result
84343** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
84344** the iStart value would be 0.  The result then would
84345** be: nil, nil, nil, A, B.
84346**
84347** If a memory allocation fails the SrcList is unchanged.  The
84348** db->mallocFailed flag will be set to true.
84349*/
84350SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
84351  sqlite3 *db,       /* Database connection to notify of OOM errors */
84352  SrcList *pSrc,     /* The SrcList to be enlarged */
84353  int nExtra,        /* Number of new slots to add to pSrc->a[] */
84354  int iStart         /* Index in pSrc->a[] of first new slot */
84355){
84356  int i;
84357
84358  /* Sanity checking on calling parameters */
84359  assert( iStart>=0 );
84360  assert( nExtra>=1 );
84361  assert( pSrc!=0 );
84362  assert( iStart<=pSrc->nSrc );
84363
84364  /* Allocate additional space if needed */
84365  if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
84366    SrcList *pNew;
84367    int nAlloc = pSrc->nSrc+nExtra;
84368    int nGot;
84369    pNew = sqlite3DbRealloc(db, pSrc,
84370               sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
84371    if( pNew==0 ){
84372      assert( db->mallocFailed );
84373      return pSrc;
84374    }
84375    pSrc = pNew;
84376    nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
84377    pSrc->nAlloc = (u16)nGot;
84378  }
84379
84380  /* Move existing slots that come after the newly inserted slots
84381  ** out of the way */
84382  for(i=pSrc->nSrc-1; i>=iStart; i--){
84383    pSrc->a[i+nExtra] = pSrc->a[i];
84384  }
84385  pSrc->nSrc += (i16)nExtra;
84386
84387  /* Zero the newly allocated slots */
84388  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
84389  for(i=iStart; i<iStart+nExtra; i++){
84390    pSrc->a[i].iCursor = -1;
84391  }
84392
84393  /* Return a pointer to the enlarged SrcList */
84394  return pSrc;
84395}
84396
84397
84398/*
84399** Append a new table name to the given SrcList.  Create a new SrcList if
84400** need be.  A new entry is created in the SrcList even if pTable is NULL.
84401**
84402** A SrcList is returned, or NULL if there is an OOM error.  The returned
84403** SrcList might be the same as the SrcList that was input or it might be
84404** a new one.  If an OOM error does occurs, then the prior value of pList
84405** that is input to this routine is automatically freed.
84406**
84407** If pDatabase is not null, it means that the table has an optional
84408** database name prefix.  Like this:  "database.table".  The pDatabase
84409** points to the table name and the pTable points to the database name.
84410** The SrcList.a[].zName field is filled with the table name which might
84411** come from pTable (if pDatabase is NULL) or from pDatabase.
84412** SrcList.a[].zDatabase is filled with the database name from pTable,
84413** or with NULL if no database is specified.
84414**
84415** In other words, if call like this:
84416**
84417**         sqlite3SrcListAppend(D,A,B,0);
84418**
84419** Then B is a table name and the database name is unspecified.  If called
84420** like this:
84421**
84422**         sqlite3SrcListAppend(D,A,B,C);
84423**
84424** Then C is the table name and B is the database name.  If C is defined
84425** then so is B.  In other words, we never have a case where:
84426**
84427**         sqlite3SrcListAppend(D,A,0,C);
84428**
84429** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
84430** before being added to the SrcList.
84431*/
84432SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
84433  sqlite3 *db,        /* Connection to notify of malloc failures */
84434  SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
84435  Token *pTable,      /* Table to append */
84436  Token *pDatabase    /* Database of the table */
84437){
84438  struct SrcList_item *pItem;
84439  assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
84440  if( pList==0 ){
84441    pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
84442    if( pList==0 ) return 0;
84443    pList->nAlloc = 1;
84444  }
84445  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
84446  if( db->mallocFailed ){
84447    sqlite3SrcListDelete(db, pList);
84448    return 0;
84449  }
84450  pItem = &pList->a[pList->nSrc-1];
84451  if( pDatabase && pDatabase->z==0 ){
84452    pDatabase = 0;
84453  }
84454  if( pDatabase ){
84455    Token *pTemp = pDatabase;
84456    pDatabase = pTable;
84457    pTable = pTemp;
84458  }
84459  pItem->zName = sqlite3NameFromToken(db, pTable);
84460  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
84461  return pList;
84462}
84463
84464/*
84465** Assign VdbeCursor index numbers to all tables in a SrcList
84466*/
84467SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
84468  int i;
84469  struct SrcList_item *pItem;
84470  assert(pList || pParse->db->mallocFailed );
84471  if( pList ){
84472    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
84473      if( pItem->iCursor>=0 ) break;
84474      pItem->iCursor = pParse->nTab++;
84475      if( pItem->pSelect ){
84476        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
84477      }
84478    }
84479  }
84480}
84481
84482/*
84483** Delete an entire SrcList including all its substructure.
84484*/
84485SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
84486  int i;
84487  struct SrcList_item *pItem;
84488  if( pList==0 ) return;
84489  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
84490    sqlite3DbFree(db, pItem->zDatabase);
84491    sqlite3DbFree(db, pItem->zName);
84492    sqlite3DbFree(db, pItem->zAlias);
84493    sqlite3DbFree(db, pItem->zIndex);
84494    sqlite3DeleteTable(db, pItem->pTab);
84495    sqlite3SelectDelete(db, pItem->pSelect);
84496    sqlite3ExprDelete(db, pItem->pOn);
84497    sqlite3IdListDelete(db, pItem->pUsing);
84498  }
84499  sqlite3DbFree(db, pList);
84500}
84501
84502/*
84503** This routine is called by the parser to add a new term to the
84504** end of a growing FROM clause.  The "p" parameter is the part of
84505** the FROM clause that has already been constructed.  "p" is NULL
84506** if this is the first term of the FROM clause.  pTable and pDatabase
84507** are the name of the table and database named in the FROM clause term.
84508** pDatabase is NULL if the database name qualifier is missing - the
84509** usual case.  If the term has a alias, then pAlias points to the
84510** alias token.  If the term is a subquery, then pSubquery is the
84511** SELECT statement that the subquery encodes.  The pTable and
84512** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
84513** parameters are the content of the ON and USING clauses.
84514**
84515** Return a new SrcList which encodes is the FROM with the new
84516** term added.
84517*/
84518SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
84519  Parse *pParse,          /* Parsing context */
84520  SrcList *p,             /* The left part of the FROM clause already seen */
84521  Token *pTable,          /* Name of the table to add to the FROM clause */
84522  Token *pDatabase,       /* Name of the database containing pTable */
84523  Token *pAlias,          /* The right-hand side of the AS subexpression */
84524  Select *pSubquery,      /* A subquery used in place of a table name */
84525  Expr *pOn,              /* The ON clause of a join */
84526  IdList *pUsing          /* The USING clause of a join */
84527){
84528  struct SrcList_item *pItem;
84529  sqlite3 *db = pParse->db;
84530  if( !p && (pOn || pUsing) ){
84531    sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
84532      (pOn ? "ON" : "USING")
84533    );
84534    goto append_from_error;
84535  }
84536  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
84537  if( p==0 || NEVER(p->nSrc==0) ){
84538    goto append_from_error;
84539  }
84540  pItem = &p->a[p->nSrc-1];
84541  assert( pAlias!=0 );
84542  if( pAlias->n ){
84543    pItem->zAlias = sqlite3NameFromToken(db, pAlias);
84544  }
84545  pItem->pSelect = pSubquery;
84546  pItem->pOn = pOn;
84547  pItem->pUsing = pUsing;
84548  return p;
84549
84550 append_from_error:
84551  assert( p==0 );
84552  sqlite3ExprDelete(db, pOn);
84553  sqlite3IdListDelete(db, pUsing);
84554  sqlite3SelectDelete(db, pSubquery);
84555  return 0;
84556}
84557
84558/*
84559** Add an INDEXED BY or NOT INDEXED clause to the most recently added
84560** element of the source-list passed as the second argument.
84561*/
84562SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
84563  assert( pIndexedBy!=0 );
84564  if( p && ALWAYS(p->nSrc>0) ){
84565    struct SrcList_item *pItem = &p->a[p->nSrc-1];
84566    assert( pItem->notIndexed==0 && pItem->zIndex==0 );
84567    if( pIndexedBy->n==1 && !pIndexedBy->z ){
84568      /* A "NOT INDEXED" clause was supplied. See parse.y
84569      ** construct "indexed_opt" for details. */
84570      pItem->notIndexed = 1;
84571    }else{
84572      pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
84573    }
84574  }
84575}
84576
84577/*
84578** When building up a FROM clause in the parser, the join operator
84579** is initially attached to the left operand.  But the code generator
84580** expects the join operator to be on the right operand.  This routine
84581** Shifts all join operators from left to right for an entire FROM
84582** clause.
84583**
84584** Example: Suppose the join is like this:
84585**
84586**           A natural cross join B
84587**
84588** The operator is "natural cross join".  The A and B operands are stored
84589** in p->a[0] and p->a[1], respectively.  The parser initially stores the
84590** operator with A.  This routine shifts that operator over to B.
84591*/
84592SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
84593  if( p ){
84594    int i;
84595    assert( p->a || p->nSrc==0 );
84596    for(i=p->nSrc-1; i>0; i--){
84597      p->a[i].jointype = p->a[i-1].jointype;
84598    }
84599    p->a[0].jointype = 0;
84600  }
84601}
84602
84603/*
84604** Begin a transaction
84605*/
84606SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
84607  sqlite3 *db;
84608  Vdbe *v;
84609  int i;
84610
84611  assert( pParse!=0 );
84612  db = pParse->db;
84613  assert( db!=0 );
84614/*  if( db->aDb[0].pBt==0 ) return; */
84615  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
84616    return;
84617  }
84618  v = sqlite3GetVdbe(pParse);
84619  if( !v ) return;
84620  if( type!=TK_DEFERRED ){
84621    for(i=0; i<db->nDb; i++){
84622      sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
84623      sqlite3VdbeUsesBtree(v, i);
84624    }
84625  }
84626  sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
84627}
84628
84629/*
84630** Commit a transaction
84631*/
84632SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
84633  Vdbe *v;
84634
84635  assert( pParse!=0 );
84636  assert( pParse->db!=0 );
84637  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
84638    return;
84639  }
84640  v = sqlite3GetVdbe(pParse);
84641  if( v ){
84642    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
84643  }
84644}
84645
84646/*
84647** Rollback a transaction
84648*/
84649SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
84650  Vdbe *v;
84651
84652  assert( pParse!=0 );
84653  assert( pParse->db!=0 );
84654  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
84655    return;
84656  }
84657  v = sqlite3GetVdbe(pParse);
84658  if( v ){
84659    sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
84660  }
84661}
84662
84663/*
84664** This function is called by the parser when it parses a command to create,
84665** release or rollback an SQL savepoint.
84666*/
84667SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
84668  char *zName = sqlite3NameFromToken(pParse->db, pName);
84669  if( zName ){
84670    Vdbe *v = sqlite3GetVdbe(pParse);
84671#ifndef SQLITE_OMIT_AUTHORIZATION
84672    static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
84673    assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
84674#endif
84675    if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
84676      sqlite3DbFree(pParse->db, zName);
84677      return;
84678    }
84679    sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
84680  }
84681}
84682
84683/*
84684** Make sure the TEMP database is open and available for use.  Return
84685** the number of errors.  Leave any error messages in the pParse structure.
84686*/
84687SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
84688  sqlite3 *db = pParse->db;
84689  if( db->aDb[1].pBt==0 && !pParse->explain ){
84690    int rc;
84691    Btree *pBt;
84692    static const int flags =
84693          SQLITE_OPEN_READWRITE |
84694          SQLITE_OPEN_CREATE |
84695          SQLITE_OPEN_EXCLUSIVE |
84696          SQLITE_OPEN_DELETEONCLOSE |
84697          SQLITE_OPEN_TEMP_DB;
84698
84699    rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
84700    if( rc!=SQLITE_OK ){
84701      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
84702        "file for storing temporary tables");
84703      pParse->rc = rc;
84704      return 1;
84705    }
84706    db->aDb[1].pBt = pBt;
84707    assert( db->aDb[1].pSchema );
84708    if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
84709      db->mallocFailed = 1;
84710      return 1;
84711    }
84712  }
84713  return 0;
84714}
84715
84716/*
84717** Generate VDBE code that will verify the schema cookie and start
84718** a read-transaction for all named database files.
84719**
84720** It is important that all schema cookies be verified and all
84721** read transactions be started before anything else happens in
84722** the VDBE program.  But this routine can be called after much other
84723** code has been generated.  So here is what we do:
84724**
84725** The first time this routine is called, we code an OP_Goto that
84726** will jump to a subroutine at the end of the program.  Then we
84727** record every database that needs its schema verified in the
84728** pParse->cookieMask field.  Later, after all other code has been
84729** generated, the subroutine that does the cookie verifications and
84730** starts the transactions will be coded and the OP_Goto P2 value
84731** will be made to point to that subroutine.  The generation of the
84732** cookie verification subroutine code happens in sqlite3FinishCoding().
84733**
84734** If iDb<0 then code the OP_Goto only - don't set flag to verify the
84735** schema on any databases.  This can be used to position the OP_Goto
84736** early in the code, before we know if any database tables will be used.
84737*/
84738SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
84739  Parse *pToplevel = sqlite3ParseToplevel(pParse);
84740
84741  if( pToplevel->cookieGoto==0 ){
84742    Vdbe *v = sqlite3GetVdbe(pToplevel);
84743    if( v==0 ) return;  /* This only happens if there was a prior error */
84744    pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
84745  }
84746  if( iDb>=0 ){
84747    sqlite3 *db = pToplevel->db;
84748    yDbMask mask;
84749
84750    assert( iDb<db->nDb );
84751    assert( db->aDb[iDb].pBt!=0 || iDb==1 );
84752    assert( iDb<SQLITE_MAX_ATTACHED+2 );
84753    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84754    mask = ((yDbMask)1)<<iDb;
84755    if( (pToplevel->cookieMask & mask)==0 ){
84756      pToplevel->cookieMask |= mask;
84757      pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
84758      if( !OMIT_TEMPDB && iDb==1 ){
84759        sqlite3OpenTempDatabase(pToplevel);
84760      }
84761    }
84762  }
84763}
84764
84765/*
84766** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
84767** attached database. Otherwise, invoke it for the database named zDb only.
84768*/
84769SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
84770  sqlite3 *db = pParse->db;
84771  int i;
84772  for(i=0; i<db->nDb; i++){
84773    Db *pDb = &db->aDb[i];
84774    if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
84775      sqlite3CodeVerifySchema(pParse, i);
84776    }
84777  }
84778}
84779
84780/*
84781** Generate VDBE code that prepares for doing an operation that
84782** might change the database.
84783**
84784** This routine starts a new transaction if we are not already within
84785** a transaction.  If we are already within a transaction, then a checkpoint
84786** is set if the setStatement parameter is true.  A checkpoint should
84787** be set for operations that might fail (due to a constraint) part of
84788** the way through and which will need to undo some writes without having to
84789** rollback the whole transaction.  For operations where all constraints
84790** can be checked before any changes are made to the database, it is never
84791** necessary to undo a write and the checkpoint should not be set.
84792*/
84793SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
84794  Parse *pToplevel = sqlite3ParseToplevel(pParse);
84795  sqlite3CodeVerifySchema(pParse, iDb);
84796  pToplevel->writeMask |= ((yDbMask)1)<<iDb;
84797  pToplevel->isMultiWrite |= setStatement;
84798}
84799
84800/*
84801** Indicate that the statement currently under construction might write
84802** more than one entry (example: deleting one row then inserting another,
84803** inserting multiple rows in a table, or inserting a row and index entries.)
84804** If an abort occurs after some of these writes have completed, then it will
84805** be necessary to undo the completed writes.
84806*/
84807SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
84808  Parse *pToplevel = sqlite3ParseToplevel(pParse);
84809  pToplevel->isMultiWrite = 1;
84810}
84811
84812/*
84813** The code generator calls this routine if is discovers that it is
84814** possible to abort a statement prior to completion.  In order to
84815** perform this abort without corrupting the database, we need to make
84816** sure that the statement is protected by a statement transaction.
84817**
84818** Technically, we only need to set the mayAbort flag if the
84819** isMultiWrite flag was previously set.  There is a time dependency
84820** such that the abort must occur after the multiwrite.  This makes
84821** some statements involving the REPLACE conflict resolution algorithm
84822** go a little faster.  But taking advantage of this time dependency
84823** makes it more difficult to prove that the code is correct (in
84824** particular, it prevents us from writing an effective
84825** implementation of sqlite3AssertMayAbort()) and so we have chosen
84826** to take the safe route and skip the optimization.
84827*/
84828SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
84829  Parse *pToplevel = sqlite3ParseToplevel(pParse);
84830  pToplevel->mayAbort = 1;
84831}
84832
84833/*
84834** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
84835** error. The onError parameter determines which (if any) of the statement
84836** and/or current transaction is rolled back.
84837*/
84838SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
84839  Vdbe *v = sqlite3GetVdbe(pParse);
84840  if( onError==OE_Abort ){
84841    sqlite3MayAbort(pParse);
84842  }
84843  sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
84844}
84845
84846/*
84847** Check to see if pIndex uses the collating sequence pColl.  Return
84848** true if it does and false if it does not.
84849*/
84850#ifndef SQLITE_OMIT_REINDEX
84851static int collationMatch(const char *zColl, Index *pIndex){
84852  int i;
84853  assert( zColl!=0 );
84854  for(i=0; i<pIndex->nColumn; i++){
84855    const char *z = pIndex->azColl[i];
84856    assert( z!=0 );
84857    if( 0==sqlite3StrICmp(z, zColl) ){
84858      return 1;
84859    }
84860  }
84861  return 0;
84862}
84863#endif
84864
84865/*
84866** Recompute all indices of pTab that use the collating sequence pColl.
84867** If pColl==0 then recompute all indices of pTab.
84868*/
84869#ifndef SQLITE_OMIT_REINDEX
84870static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
84871  Index *pIndex;              /* An index associated with pTab */
84872
84873  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
84874    if( zColl==0 || collationMatch(zColl, pIndex) ){
84875      int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84876      sqlite3BeginWriteOperation(pParse, 0, iDb);
84877      sqlite3RefillIndex(pParse, pIndex, -1);
84878    }
84879  }
84880}
84881#endif
84882
84883/*
84884** Recompute all indices of all tables in all databases where the
84885** indices use the collating sequence pColl.  If pColl==0 then recompute
84886** all indices everywhere.
84887*/
84888#ifndef SQLITE_OMIT_REINDEX
84889static void reindexDatabases(Parse *pParse, char const *zColl){
84890  Db *pDb;                    /* A single database */
84891  int iDb;                    /* The database index number */
84892  sqlite3 *db = pParse->db;   /* The database connection */
84893  HashElem *k;                /* For looping over tables in pDb */
84894  Table *pTab;                /* A table in the database */
84895
84896  assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
84897  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
84898    assert( pDb!=0 );
84899    for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
84900      pTab = (Table*)sqliteHashData(k);
84901      reindexTable(pParse, pTab, zColl);
84902    }
84903  }
84904}
84905#endif
84906
84907/*
84908** Generate code for the REINDEX command.
84909**
84910**        REINDEX                            -- 1
84911**        REINDEX  <collation>               -- 2
84912**        REINDEX  ?<database>.?<tablename>  -- 3
84913**        REINDEX  ?<database>.?<indexname>  -- 4
84914**
84915** Form 1 causes all indices in all attached databases to be rebuilt.
84916** Form 2 rebuilds all indices in all databases that use the named
84917** collating function.  Forms 3 and 4 rebuild the named index or all
84918** indices associated with the named table.
84919*/
84920#ifndef SQLITE_OMIT_REINDEX
84921SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
84922  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
84923  char *z;                    /* Name of a table or index */
84924  const char *zDb;            /* Name of the database */
84925  Table *pTab;                /* A table in the database */
84926  Index *pIndex;              /* An index associated with pTab */
84927  int iDb;                    /* The database index number */
84928  sqlite3 *db = pParse->db;   /* The database connection */
84929  Token *pObjName;            /* Name of the table or index to be reindexed */
84930
84931  /* Read the database schema. If an error occurs, leave an error message
84932  ** and code in pParse and return NULL. */
84933  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84934    return;
84935  }
84936
84937  if( pName1==0 ){
84938    reindexDatabases(pParse, 0);
84939    return;
84940  }else if( NEVER(pName2==0) || pName2->z==0 ){
84941    char *zColl;
84942    assert( pName1->z );
84943    zColl = sqlite3NameFromToken(pParse->db, pName1);
84944    if( !zColl ) return;
84945    pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
84946    if( pColl ){
84947      reindexDatabases(pParse, zColl);
84948      sqlite3DbFree(db, zColl);
84949      return;
84950    }
84951    sqlite3DbFree(db, zColl);
84952  }
84953  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
84954  if( iDb<0 ) return;
84955  z = sqlite3NameFromToken(db, pObjName);
84956  if( z==0 ) return;
84957  zDb = db->aDb[iDb].zName;
84958  pTab = sqlite3FindTable(db, z, zDb);
84959  if( pTab ){
84960    reindexTable(pParse, pTab, 0);
84961    sqlite3DbFree(db, z);
84962    return;
84963  }
84964  pIndex = sqlite3FindIndex(db, z, zDb);
84965  sqlite3DbFree(db, z);
84966  if( pIndex ){
84967    sqlite3BeginWriteOperation(pParse, 0, iDb);
84968    sqlite3RefillIndex(pParse, pIndex, -1);
84969    return;
84970  }
84971  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
84972}
84973#endif
84974
84975/*
84976** Return a dynamicly allocated KeyInfo structure that can be used
84977** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
84978**
84979** If successful, a pointer to the new structure is returned. In this case
84980** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
84981** pointer. If an error occurs (out of memory or missing collation
84982** sequence), NULL is returned and the state of pParse updated to reflect
84983** the error.
84984*/
84985SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
84986  int i;
84987  int nCol = pIdx->nColumn;
84988  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
84989  sqlite3 *db = pParse->db;
84990  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
84991
84992  if( pKey ){
84993    pKey->db = pParse->db;
84994    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
84995    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
84996    for(i=0; i<nCol; i++){
84997      char *zColl = pIdx->azColl[i];
84998      assert( zColl );
84999      pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
85000      pKey->aSortOrder[i] = pIdx->aSortOrder[i];
85001    }
85002    pKey->nField = (u16)nCol;
85003  }
85004
85005  if( pParse->nErr ){
85006    sqlite3DbFree(db, pKey);
85007    pKey = 0;
85008  }
85009  return pKey;
85010}
85011
85012/************** End of build.c ***********************************************/
85013/************** Begin file callback.c ****************************************/
85014/*
85015** 2005 May 23
85016**
85017** The author disclaims copyright to this source code.  In place of
85018** a legal notice, here is a blessing:
85019**
85020**    May you do good and not evil.
85021**    May you find forgiveness for yourself and forgive others.
85022**    May you share freely, never taking more than you give.
85023**
85024*************************************************************************
85025**
85026** This file contains functions used to access the internal hash tables
85027** of user defined functions and collation sequences.
85028*/
85029
85030
85031/*
85032** Invoke the 'collation needed' callback to request a collation sequence
85033** in the encoding enc of name zName, length nName.
85034*/
85035static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
85036  assert( !db->xCollNeeded || !db->xCollNeeded16 );
85037  if( db->xCollNeeded ){
85038    char *zExternal = sqlite3DbStrDup(db, zName);
85039    if( !zExternal ) return;
85040    db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
85041    sqlite3DbFree(db, zExternal);
85042  }
85043#ifndef SQLITE_OMIT_UTF16
85044  if( db->xCollNeeded16 ){
85045    char const *zExternal;
85046    sqlite3_value *pTmp = sqlite3ValueNew(db);
85047    sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
85048    zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
85049    if( zExternal ){
85050      db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
85051    }
85052    sqlite3ValueFree(pTmp);
85053  }
85054#endif
85055}
85056
85057/*
85058** This routine is called if the collation factory fails to deliver a
85059** collation function in the best encoding but there may be other versions
85060** of this collation function (for other text encodings) available. Use one
85061** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
85062** possible.
85063*/
85064static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
85065  CollSeq *pColl2;
85066  char *z = pColl->zName;
85067  int i;
85068  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
85069  for(i=0; i<3; i++){
85070    pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
85071    if( pColl2->xCmp!=0 ){
85072      memcpy(pColl, pColl2, sizeof(CollSeq));
85073      pColl->xDel = 0;         /* Do not copy the destructor */
85074      return SQLITE_OK;
85075    }
85076  }
85077  return SQLITE_ERROR;
85078}
85079
85080/*
85081** This function is responsible for invoking the collation factory callback
85082** or substituting a collation sequence of a different encoding when the
85083** requested collation sequence is not available in the desired encoding.
85084**
85085** If it is not NULL, then pColl must point to the database native encoding
85086** collation sequence with name zName, length nName.
85087**
85088** The return value is either the collation sequence to be used in database
85089** db for collation type name zName, length nName, or NULL, if no collation
85090** sequence can be found.
85091**
85092** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
85093*/
85094SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
85095  sqlite3* db,          /* The database connection */
85096  u8 enc,               /* The desired encoding for the collating sequence */
85097  CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
85098  const char *zName     /* Collating sequence name */
85099){
85100  CollSeq *p;
85101
85102  p = pColl;
85103  if( !p ){
85104    p = sqlite3FindCollSeq(db, enc, zName, 0);
85105  }
85106  if( !p || !p->xCmp ){
85107    /* No collation sequence of this type for this encoding is registered.
85108    ** Call the collation factory to see if it can supply us with one.
85109    */
85110    callCollNeeded(db, enc, zName);
85111    p = sqlite3FindCollSeq(db, enc, zName, 0);
85112  }
85113  if( p && !p->xCmp && synthCollSeq(db, p) ){
85114    p = 0;
85115  }
85116  assert( !p || p->xCmp );
85117  return p;
85118}
85119
85120/*
85121** This routine is called on a collation sequence before it is used to
85122** check that it is defined. An undefined collation sequence exists when
85123** a database is loaded that contains references to collation sequences
85124** that have not been defined by sqlite3_create_collation() etc.
85125**
85126** If required, this routine calls the 'collation needed' callback to
85127** request a definition of the collating sequence. If this doesn't work,
85128** an equivalent collating sequence that uses a text encoding different
85129** from the main database is substituted, if one is available.
85130*/
85131SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
85132  if( pColl ){
85133    const char *zName = pColl->zName;
85134    sqlite3 *db = pParse->db;
85135    CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
85136    if( !p ){
85137      sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
85138      pParse->nErr++;
85139      return SQLITE_ERROR;
85140    }
85141    assert( p==pColl );
85142  }
85143  return SQLITE_OK;
85144}
85145
85146
85147
85148/*
85149** Locate and return an entry from the db.aCollSeq hash table. If the entry
85150** specified by zName and nName is not found and parameter 'create' is
85151** true, then create a new entry. Otherwise return NULL.
85152**
85153** Each pointer stored in the sqlite3.aCollSeq hash table contains an
85154** array of three CollSeq structures. The first is the collation sequence
85155** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
85156**
85157** Stored immediately after the three collation sequences is a copy of
85158** the collation sequence name. A pointer to this string is stored in
85159** each collation sequence structure.
85160*/
85161static CollSeq *findCollSeqEntry(
85162  sqlite3 *db,          /* Database connection */
85163  const char *zName,    /* Name of the collating sequence */
85164  int create            /* Create a new entry if true */
85165){
85166  CollSeq *pColl;
85167  int nName = sqlite3Strlen30(zName);
85168  pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
85169
85170  if( 0==pColl && create ){
85171    pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
85172    if( pColl ){
85173      CollSeq *pDel = 0;
85174      pColl[0].zName = (char*)&pColl[3];
85175      pColl[0].enc = SQLITE_UTF8;
85176      pColl[1].zName = (char*)&pColl[3];
85177      pColl[1].enc = SQLITE_UTF16LE;
85178      pColl[2].zName = (char*)&pColl[3];
85179      pColl[2].enc = SQLITE_UTF16BE;
85180      memcpy(pColl[0].zName, zName, nName);
85181      pColl[0].zName[nName] = 0;
85182      pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
85183
85184      /* If a malloc() failure occurred in sqlite3HashInsert(), it will
85185      ** return the pColl pointer to be deleted (because it wasn't added
85186      ** to the hash table).
85187      */
85188      assert( pDel==0 || pDel==pColl );
85189      if( pDel!=0 ){
85190        db->mallocFailed = 1;
85191        sqlite3DbFree(db, pDel);
85192        pColl = 0;
85193      }
85194    }
85195  }
85196  return pColl;
85197}
85198
85199/*
85200** Parameter zName points to a UTF-8 encoded string nName bytes long.
85201** Return the CollSeq* pointer for the collation sequence named zName
85202** for the encoding 'enc' from the database 'db'.
85203**
85204** If the entry specified is not found and 'create' is true, then create a
85205** new entry.  Otherwise return NULL.
85206**
85207** A separate function sqlite3LocateCollSeq() is a wrapper around
85208** this routine.  sqlite3LocateCollSeq() invokes the collation factory
85209** if necessary and generates an error message if the collating sequence
85210** cannot be found.
85211**
85212** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
85213*/
85214SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
85215  sqlite3 *db,
85216  u8 enc,
85217  const char *zName,
85218  int create
85219){
85220  CollSeq *pColl;
85221  if( zName ){
85222    pColl = findCollSeqEntry(db, zName, create);
85223  }else{
85224    pColl = db->pDfltColl;
85225  }
85226  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
85227  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
85228  if( pColl ) pColl += enc-1;
85229  return pColl;
85230}
85231
85232/* During the search for the best function definition, this procedure
85233** is called to test how well the function passed as the first argument
85234** matches the request for a function with nArg arguments in a system
85235** that uses encoding enc. The value returned indicates how well the
85236** request is matched. A higher value indicates a better match.
85237**
85238** The returned value is always between 0 and 6, as follows:
85239**
85240** 0: Not a match, or if nArg<0 and the function is has no implementation.
85241** 1: A variable arguments function that prefers UTF-8 when a UTF-16
85242**    encoding is requested, or vice versa.
85243** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
85244**    requested, or vice versa.
85245** 3: A variable arguments function using the same text encoding.
85246** 4: A function with the exact number of arguments requested that
85247**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
85248** 5: A function with the exact number of arguments requested that
85249**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
85250** 6: An exact match.
85251**
85252*/
85253static int matchQuality(FuncDef *p, int nArg, u8 enc){
85254  int match = 0;
85255  if( p->nArg==-1 || p->nArg==nArg
85256   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
85257  ){
85258    match = 1;
85259    if( p->nArg==nArg || nArg==-1 ){
85260      match = 4;
85261    }
85262    if( enc==p->iPrefEnc ){
85263      match += 2;
85264    }
85265    else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
85266             (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
85267      match += 1;
85268    }
85269  }
85270  return match;
85271}
85272
85273/*
85274** Search a FuncDefHash for a function with the given name.  Return
85275** a pointer to the matching FuncDef if found, or 0 if there is no match.
85276*/
85277static FuncDef *functionSearch(
85278  FuncDefHash *pHash,  /* Hash table to search */
85279  int h,               /* Hash of the name */
85280  const char *zFunc,   /* Name of function */
85281  int nFunc            /* Number of bytes in zFunc */
85282){
85283  FuncDef *p;
85284  for(p=pHash->a[h]; p; p=p->pHash){
85285    if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
85286      return p;
85287    }
85288  }
85289  return 0;
85290}
85291
85292/*
85293** Insert a new FuncDef into a FuncDefHash hash table.
85294*/
85295SQLITE_PRIVATE void sqlite3FuncDefInsert(
85296  FuncDefHash *pHash,  /* The hash table into which to insert */
85297  FuncDef *pDef        /* The function definition to insert */
85298){
85299  FuncDef *pOther;
85300  int nName = sqlite3Strlen30(pDef->zName);
85301  u8 c1 = (u8)pDef->zName[0];
85302  int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
85303  pOther = functionSearch(pHash, h, pDef->zName, nName);
85304  if( pOther ){
85305    assert( pOther!=pDef && pOther->pNext!=pDef );
85306    pDef->pNext = pOther->pNext;
85307    pOther->pNext = pDef;
85308  }else{
85309    pDef->pNext = 0;
85310    pDef->pHash = pHash->a[h];
85311    pHash->a[h] = pDef;
85312  }
85313}
85314
85315
85316
85317/*
85318** Locate a user function given a name, a number of arguments and a flag
85319** indicating whether the function prefers UTF-16 over UTF-8.  Return a
85320** pointer to the FuncDef structure that defines that function, or return
85321** NULL if the function does not exist.
85322**
85323** If the createFlag argument is true, then a new (blank) FuncDef
85324** structure is created and liked into the "db" structure if a
85325** no matching function previously existed.  When createFlag is true
85326** and the nArg parameter is -1, then only a function that accepts
85327** any number of arguments will be returned.
85328**
85329** If createFlag is false and nArg is -1, then the first valid
85330** function found is returned.  A function is valid if either xFunc
85331** or xStep is non-zero.
85332**
85333** If createFlag is false, then a function with the required name and
85334** number of arguments may be returned even if the eTextRep flag does not
85335** match that requested.
85336*/
85337SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
85338  sqlite3 *db,       /* An open database */
85339  const char *zName, /* Name of the function.  Not null-terminated */
85340  int nName,         /* Number of characters in the name */
85341  int nArg,          /* Number of arguments.  -1 means any number */
85342  u8 enc,            /* Preferred text encoding */
85343  int createFlag     /* Create new entry if true and does not otherwise exist */
85344){
85345  FuncDef *p;         /* Iterator variable */
85346  FuncDef *pBest = 0; /* Best match found so far */
85347  int bestScore = 0;  /* Score of best match */
85348  int h;              /* Hash value */
85349
85350
85351  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
85352  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
85353
85354  /* First search for a match amongst the application-defined functions.
85355  */
85356  p = functionSearch(&db->aFunc, h, zName, nName);
85357  while( p ){
85358    int score = matchQuality(p, nArg, enc);
85359    if( score>bestScore ){
85360      pBest = p;
85361      bestScore = score;
85362    }
85363    p = p->pNext;
85364  }
85365
85366  /* If no match is found, search the built-in functions.
85367  **
85368  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
85369  ** functions even if a prior app-defined function was found.  And give
85370  ** priority to built-in functions.
85371  **
85372  ** Except, if createFlag is true, that means that we are trying to
85373  ** install a new function.  Whatever FuncDef structure is returned it will
85374  ** have fields overwritten with new information appropriate for the
85375  ** new function.  But the FuncDefs for built-in functions are read-only.
85376  ** So we must not search for built-ins when creating a new function.
85377  */
85378  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
85379    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
85380    bestScore = 0;
85381    p = functionSearch(pHash, h, zName, nName);
85382    while( p ){
85383      int score = matchQuality(p, nArg, enc);
85384      if( score>bestScore ){
85385        pBest = p;
85386        bestScore = score;
85387      }
85388      p = p->pNext;
85389    }
85390  }
85391
85392  /* If the createFlag parameter is true and the search did not reveal an
85393  ** exact match for the name, number of arguments and encoding, then add a
85394  ** new entry to the hash table and return it.
85395  */
85396  if( createFlag && (bestScore<6 || pBest->nArg!=nArg) &&
85397      (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
85398    pBest->zName = (char *)&pBest[1];
85399    pBest->nArg = (u16)nArg;
85400    pBest->iPrefEnc = enc;
85401    memcpy(pBest->zName, zName, nName);
85402    pBest->zName[nName] = 0;
85403    sqlite3FuncDefInsert(&db->aFunc, pBest);
85404  }
85405
85406  if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
85407    return pBest;
85408  }
85409  return 0;
85410}
85411
85412/*
85413** Free all resources held by the schema structure. The void* argument points
85414** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
85415** pointer itself, it just cleans up subsidiary resources (i.e. the contents
85416** of the schema hash tables).
85417**
85418** The Schema.cache_size variable is not cleared.
85419*/
85420SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
85421  Hash temp1;
85422  Hash temp2;
85423  HashElem *pElem;
85424  Schema *pSchema = (Schema *)p;
85425
85426  temp1 = pSchema->tblHash;
85427  temp2 = pSchema->trigHash;
85428  sqlite3HashInit(&pSchema->trigHash);
85429  sqlite3HashClear(&pSchema->idxHash);
85430  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
85431    sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
85432  }
85433  sqlite3HashClear(&temp2);
85434  sqlite3HashInit(&pSchema->tblHash);
85435  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
85436    Table *pTab = sqliteHashData(pElem);
85437    sqlite3DeleteTable(0, pTab);
85438  }
85439  sqlite3HashClear(&temp1);
85440  sqlite3HashClear(&pSchema->fkeyHash);
85441  pSchema->pSeqTab = 0;
85442  if( pSchema->flags & DB_SchemaLoaded ){
85443    pSchema->iGeneration++;
85444    pSchema->flags &= ~DB_SchemaLoaded;
85445  }
85446}
85447
85448/*
85449** Find and return the schema associated with a BTree.  Create
85450** a new one if necessary.
85451*/
85452SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
85453  Schema * p;
85454  if( pBt ){
85455    p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
85456  }else{
85457    p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
85458  }
85459  if( !p ){
85460    db->mallocFailed = 1;
85461  }else if ( 0==p->file_format ){
85462    sqlite3HashInit(&p->tblHash);
85463    sqlite3HashInit(&p->idxHash);
85464    sqlite3HashInit(&p->trigHash);
85465    sqlite3HashInit(&p->fkeyHash);
85466    p->enc = SQLITE_UTF8;
85467  }
85468  return p;
85469}
85470
85471/************** End of callback.c ********************************************/
85472/************** Begin file delete.c ******************************************/
85473/*
85474** 2001 September 15
85475**
85476** The author disclaims copyright to this source code.  In place of
85477** a legal notice, here is a blessing:
85478**
85479**    May you do good and not evil.
85480**    May you find forgiveness for yourself and forgive others.
85481**    May you share freely, never taking more than you give.
85482**
85483*************************************************************************
85484** This file contains C code routines that are called by the parser
85485** in order to generate code for DELETE FROM statements.
85486*/
85487
85488/*
85489** While a SrcList can in general represent multiple tables and subqueries
85490** (as in the FROM clause of a SELECT statement) in this case it contains
85491** the name of a single table, as one might find in an INSERT, DELETE,
85492** or UPDATE statement.  Look up that table in the symbol table and
85493** return a pointer.  Set an error message and return NULL if the table
85494** name is not found or if any other error occurs.
85495**
85496** The following fields are initialized appropriate in pSrc:
85497**
85498**    pSrc->a[0].pTab       Pointer to the Table object
85499**    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
85500**
85501*/
85502SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
85503  struct SrcList_item *pItem = pSrc->a;
85504  Table *pTab;
85505  assert( pItem && pSrc->nSrc==1 );
85506  pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
85507  sqlite3DeleteTable(pParse->db, pItem->pTab);
85508  pItem->pTab = pTab;
85509  if( pTab ){
85510    pTab->nRef++;
85511  }
85512  if( sqlite3IndexedByLookup(pParse, pItem) ){
85513    pTab = 0;
85514  }
85515  return pTab;
85516}
85517
85518/*
85519** Check to make sure the given table is writable.  If it is not
85520** writable, generate an error message and return 1.  If it is
85521** writable return 0;
85522*/
85523SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
85524  /* A table is not writable under the following circumstances:
85525  **
85526  **   1) It is a virtual table and no implementation of the xUpdate method
85527  **      has been provided, or
85528  **   2) It is a system table (i.e. sqlite_master), this call is not
85529  **      part of a nested parse and writable_schema pragma has not
85530  **      been specified.
85531  **
85532  ** In either case leave an error message in pParse and return non-zero.
85533  */
85534  if( ( IsVirtual(pTab)
85535     && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
85536   || ( (pTab->tabFlags & TF_Readonly)!=0
85537     && (pParse->db->flags & SQLITE_WriteSchema)==0
85538     && pParse->nested==0 )
85539  ){
85540    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
85541    return 1;
85542  }
85543
85544#ifndef SQLITE_OMIT_VIEW
85545  if( !viewOk && pTab->pSelect ){
85546    sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
85547    return 1;
85548  }
85549#endif
85550  return 0;
85551}
85552
85553
85554#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85555/*
85556** Evaluate a view and store its result in an ephemeral table.  The
85557** pWhere argument is an optional WHERE clause that restricts the
85558** set of rows in the view that are to be added to the ephemeral table.
85559*/
85560SQLITE_PRIVATE void sqlite3MaterializeView(
85561  Parse *pParse,       /* Parsing context */
85562  Table *pView,        /* View definition */
85563  Expr *pWhere,        /* Optional WHERE clause to be added */
85564  int iCur             /* Cursor number for ephemerial table */
85565){
85566  SelectDest dest;
85567  Select *pDup;
85568  sqlite3 *db = pParse->db;
85569
85570  pDup = sqlite3SelectDup(db, pView->pSelect, 0);
85571  if( pWhere ){
85572    SrcList *pFrom;
85573
85574    pWhere = sqlite3ExprDup(db, pWhere, 0);
85575    pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
85576    if( pFrom ){
85577      assert( pFrom->nSrc==1 );
85578      pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
85579      pFrom->a[0].pSelect = pDup;
85580      assert( pFrom->a[0].pOn==0 );
85581      assert( pFrom->a[0].pUsing==0 );
85582    }else{
85583      sqlite3SelectDelete(db, pDup);
85584    }
85585    pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
85586  }
85587  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
85588  sqlite3Select(pParse, pDup, &dest);
85589  sqlite3SelectDelete(db, pDup);
85590}
85591#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
85592
85593#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
85594/*
85595** Generate an expression tree to implement the WHERE, ORDER BY,
85596** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
85597**
85598**     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
85599**                            \__________________________/
85600**                               pLimitWhere (pInClause)
85601*/
85602SQLITE_PRIVATE Expr *sqlite3LimitWhere(
85603  Parse *pParse,               /* The parser context */
85604  SrcList *pSrc,               /* the FROM clause -- which tables to scan */
85605  Expr *pWhere,                /* The WHERE clause.  May be null */
85606  ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
85607  Expr *pLimit,                /* The LIMIT clause.  May be null */
85608  Expr *pOffset,               /* The OFFSET clause.  May be null */
85609  char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
85610){
85611  Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
85612  Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
85613  Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
85614  ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
85615  SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
85616  Select *pSelect = NULL;      /* Complete SELECT tree */
85617
85618  /* Check that there isn't an ORDER BY without a LIMIT clause.
85619  */
85620  if( pOrderBy && (pLimit == 0) ) {
85621    sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
85622    goto limit_where_cleanup_2;
85623  }
85624
85625  /* We only need to generate a select expression if there
85626  ** is a limit/offset term to enforce.
85627  */
85628  if( pLimit == 0 ) {
85629    /* if pLimit is null, pOffset will always be null as well. */
85630    assert( pOffset == 0 );
85631    return pWhere;
85632  }
85633
85634  /* Generate a select expression tree to enforce the limit/offset
85635  ** term for the DELETE or UPDATE statement.  For example:
85636  **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85637  ** becomes:
85638  **   DELETE FROM table_a WHERE rowid IN (
85639  **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
85640  **   );
85641  */
85642
85643  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85644  if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
85645  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
85646  if( pEList == 0 ) goto limit_where_cleanup_2;
85647
85648  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
85649  ** and the SELECT subtree. */
85650  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
85651  if( pSelectSrc == 0 ) {
85652    sqlite3ExprListDelete(pParse->db, pEList);
85653    goto limit_where_cleanup_2;
85654  }
85655
85656  /* generate the SELECT expression tree. */
85657  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
85658                             pOrderBy,0,pLimit,pOffset);
85659  if( pSelect == 0 ) return 0;
85660
85661  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
85662  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
85663  if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
85664  pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
85665  if( pInClause == 0 ) goto limit_where_cleanup_1;
85666
85667  pInClause->x.pSelect = pSelect;
85668  pInClause->flags |= EP_xIsSelect;
85669  sqlite3ExprSetHeight(pParse, pInClause);
85670  return pInClause;
85671
85672  /* something went wrong. clean up anything allocated. */
85673limit_where_cleanup_1:
85674  sqlite3SelectDelete(pParse->db, pSelect);
85675  return 0;
85676
85677limit_where_cleanup_2:
85678  sqlite3ExprDelete(pParse->db, pWhere);
85679  sqlite3ExprListDelete(pParse->db, pOrderBy);
85680  sqlite3ExprDelete(pParse->db, pLimit);
85681  sqlite3ExprDelete(pParse->db, pOffset);
85682  return 0;
85683}
85684#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
85685
85686/*
85687** Generate code for a DELETE FROM statement.
85688**
85689**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
85690**                 \________/       \________________/
85691**                  pTabList              pWhere
85692*/
85693SQLITE_PRIVATE void sqlite3DeleteFrom(
85694  Parse *pParse,         /* The parser context */
85695  SrcList *pTabList,     /* The table from which we should delete things */
85696  Expr *pWhere           /* The WHERE clause.  May be null */
85697){
85698  Vdbe *v;               /* The virtual database engine */
85699  Table *pTab;           /* The table from which records will be deleted */
85700  const char *zDb;       /* Name of database holding pTab */
85701  int end, addr = 0;     /* A couple addresses of generated code */
85702  int i;                 /* Loop counter */
85703  WhereInfo *pWInfo;     /* Information about the WHERE clause */
85704  Index *pIdx;           /* For looping over indices of the table */
85705  int iCur;              /* VDBE Cursor number for pTab */
85706  sqlite3 *db;           /* Main database structure */
85707  AuthContext sContext;  /* Authorization context */
85708  NameContext sNC;       /* Name context to resolve expressions in */
85709  int iDb;               /* Database number */
85710  int memCnt = -1;       /* Memory cell used for change counting */
85711  int rcauth;            /* Value returned by authorization callback */
85712
85713#ifndef SQLITE_OMIT_TRIGGER
85714  int isView;                  /* True if attempting to delete from a view */
85715  Trigger *pTrigger;           /* List of table triggers, if required */
85716#endif
85717
85718  memset(&sContext, 0, sizeof(sContext));
85719  db = pParse->db;
85720  if( pParse->nErr || db->mallocFailed ){
85721    goto delete_from_cleanup;
85722  }
85723  assert( pTabList->nSrc==1 );
85724
85725  /* Locate the table which we want to delete.  This table has to be
85726  ** put in an SrcList structure because some of the subroutines we
85727  ** will be calling are designed to work with multiple tables and expect
85728  ** an SrcList* parameter instead of just a Table* parameter.
85729  */
85730  pTab = sqlite3SrcListLookup(pParse, pTabList);
85731  if( pTab==0 )  goto delete_from_cleanup;
85732
85733  /* Figure out if we have any triggers and if the table being
85734  ** deleted from is a view
85735  */
85736#ifndef SQLITE_OMIT_TRIGGER
85737  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
85738  isView = pTab->pSelect!=0;
85739#else
85740# define pTrigger 0
85741# define isView 0
85742#endif
85743#ifdef SQLITE_OMIT_VIEW
85744# undef isView
85745# define isView 0
85746#endif
85747
85748  /* If pTab is really a view, make sure it has been initialized.
85749  */
85750  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85751    goto delete_from_cleanup;
85752  }
85753
85754  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
85755    goto delete_from_cleanup;
85756  }
85757  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
85758  assert( iDb<db->nDb );
85759  zDb = db->aDb[iDb].zName;
85760  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
85761  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
85762  if( rcauth==SQLITE_DENY ){
85763    goto delete_from_cleanup;
85764  }
85765  assert(!isView || pTrigger);
85766
85767  /* Assign  cursor number to the table and all its indices.
85768  */
85769  assert( pTabList->nSrc==1 );
85770  iCur = pTabList->a[0].iCursor = pParse->nTab++;
85771  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85772    pParse->nTab++;
85773  }
85774
85775  /* Start the view context
85776  */
85777  if( isView ){
85778    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
85779  }
85780
85781  /* Begin generating code.
85782  */
85783  v = sqlite3GetVdbe(pParse);
85784  if( v==0 ){
85785    goto delete_from_cleanup;
85786  }
85787  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
85788  sqlite3BeginWriteOperation(pParse, 1, iDb);
85789
85790  /* If we are trying to delete from a view, realize that view into
85791  ** a ephemeral table.
85792  */
85793#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
85794  if( isView ){
85795    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
85796  }
85797#endif
85798
85799  /* Resolve the column names in the WHERE clause.
85800  */
85801  memset(&sNC, 0, sizeof(sNC));
85802  sNC.pParse = pParse;
85803  sNC.pSrcList = pTabList;
85804  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
85805    goto delete_from_cleanup;
85806  }
85807
85808  /* Initialize the counter of the number of rows deleted, if
85809  ** we are counting rows.
85810  */
85811  if( db->flags & SQLITE_CountRows ){
85812    memCnt = ++pParse->nMem;
85813    sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
85814  }
85815
85816#ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
85817  /* Special case: A DELETE without a WHERE clause deletes everything.
85818  ** It is easier just to erase the whole table. Prior to version 3.6.5,
85819  ** this optimization caused the row change count (the value returned by
85820  ** API function sqlite3_count_changes) to be set incorrectly.  */
85821  if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
85822   && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
85823  ){
85824    assert( !isView );
85825    sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
85826                      pTab->zName, P4_STATIC);
85827    for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
85828      assert( pIdx->pSchema==pTab->pSchema );
85829      sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
85830    }
85831  }else
85832#endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
85833  /* The usual case: There is a WHERE clause so we have to scan through
85834  ** the table and pick which records to delete.
85835  */
85836  {
85837    int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
85838    int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
85839    int regRowid;                   /* Actual register containing rowids */
85840
85841    /* Collect rowids of every row to be deleted.
85842    */
85843    sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
85844    pWInfo = sqlite3WhereBegin(
85845        pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK
85846    );
85847    if( pWInfo==0 ) goto delete_from_cleanup;
85848    regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
85849    sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
85850    if( db->flags & SQLITE_CountRows ){
85851      sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
85852    }
85853    sqlite3WhereEnd(pWInfo);
85854
85855    /* Delete every item whose key was written to the list during the
85856    ** database scan.  We have to delete items after the scan is complete
85857    ** because deleting an item can change the scan order.  */
85858    end = sqlite3VdbeMakeLabel(v);
85859
85860    /* Unless this is a view, open cursors for the table we are
85861    ** deleting from and all its indices. If this is a view, then the
85862    ** only effect this statement has is to fire the INSTEAD OF
85863    ** triggers.  */
85864    if( !isView ){
85865      sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
85866    }
85867
85868    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
85869
85870    /* Delete the row */
85871#ifndef SQLITE_OMIT_VIRTUALTABLE
85872    if( IsVirtual(pTab) ){
85873      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
85874      sqlite3VtabMakeWritable(pParse, pTab);
85875      sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
85876      sqlite3VdbeChangeP5(v, OE_Abort);
85877      sqlite3MayAbort(pParse);
85878    }else
85879#endif
85880    {
85881      int count = (pParse->nested==0);    /* True to count changes */
85882      sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
85883    }
85884
85885    /* End of the delete loop */
85886    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
85887    sqlite3VdbeResolveLabel(v, end);
85888
85889    /* Close the cursors open on the table and its indexes. */
85890    if( !isView && !IsVirtual(pTab) ){
85891      for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
85892        sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
85893      }
85894      sqlite3VdbeAddOp1(v, OP_Close, iCur);
85895    }
85896  }
85897
85898  /* Update the sqlite_sequence table by storing the content of the
85899  ** maximum rowid counter values recorded while inserting into
85900  ** autoincrement tables.
85901  */
85902  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
85903    sqlite3AutoincrementEnd(pParse);
85904  }
85905
85906  /* Return the number of rows that were deleted. If this routine is
85907  ** generating code because of a call to sqlite3NestedParse(), do not
85908  ** invoke the callback function.
85909  */
85910  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
85911    sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
85912    sqlite3VdbeSetNumCols(v, 1);
85913    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
85914  }
85915
85916delete_from_cleanup:
85917  sqlite3AuthContextPop(&sContext);
85918  sqlite3SrcListDelete(db, pTabList);
85919  sqlite3ExprDelete(db, pWhere);
85920  return;
85921}
85922/* Make sure "isView" and other macros defined above are undefined. Otherwise
85923** thely may interfere with compilation of other functions in this file
85924** (or in another file, if this file becomes part of the amalgamation).  */
85925#ifdef isView
85926 #undef isView
85927#endif
85928#ifdef pTrigger
85929 #undef pTrigger
85930#endif
85931
85932/*
85933** This routine generates VDBE code that causes a single row of a
85934** single table to be deleted.
85935**
85936** The VDBE must be in a particular state when this routine is called.
85937** These are the requirements:
85938**
85939**   1.  A read/write cursor pointing to pTab, the table containing the row
85940**       to be deleted, must be opened as cursor number $iCur.
85941**
85942**   2.  Read/write cursors for all indices of pTab must be open as
85943**       cursor number base+i for the i-th index.
85944**
85945**   3.  The record number of the row to be deleted must be stored in
85946**       memory cell iRowid.
85947**
85948** This routine generates code to remove both the table record and all
85949** index entries that point to that record.
85950*/
85951SQLITE_PRIVATE void sqlite3GenerateRowDelete(
85952  Parse *pParse,     /* Parsing context */
85953  Table *pTab,       /* Table containing the row to be deleted */
85954  int iCur,          /* Cursor number for the table */
85955  int iRowid,        /* Memory cell that contains the rowid to delete */
85956  int count,         /* If non-zero, increment the row change counter */
85957  Trigger *pTrigger, /* List of triggers to (potentially) fire */
85958  int onconf         /* Default ON CONFLICT policy for triggers */
85959){
85960  Vdbe *v = pParse->pVdbe;        /* Vdbe */
85961  int iOld = 0;                   /* First register in OLD.* array */
85962  int iLabel;                     /* Label resolved to end of generated code */
85963
85964  /* Vdbe is guaranteed to have been allocated by this stage. */
85965  assert( v );
85966
85967  /* Seek cursor iCur to the row to delete. If this row no longer exists
85968  ** (this can happen if a trigger program has already deleted it), do
85969  ** not attempt to delete it or fire any DELETE triggers.  */
85970  iLabel = sqlite3VdbeMakeLabel(v);
85971  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
85972
85973  /* If there are any triggers to fire, allocate a range of registers to
85974  ** use for the old.* references in the triggers.  */
85975  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
85976    u32 mask;                     /* Mask of OLD.* columns in use */
85977    int iCol;                     /* Iterator used while populating OLD.* */
85978
85979    /* TODO: Could use temporary registers here. Also could attempt to
85980    ** avoid copying the contents of the rowid register.  */
85981    mask = sqlite3TriggerColmask(
85982        pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
85983    );
85984    mask |= sqlite3FkOldmask(pParse, pTab);
85985    iOld = pParse->nMem+1;
85986    pParse->nMem += (1 + pTab->nCol);
85987
85988    /* Populate the OLD.* pseudo-table register array. These values will be
85989    ** used by any BEFORE and AFTER triggers that exist.  */
85990    sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
85991    for(iCol=0; iCol<pTab->nCol; iCol++){
85992      if( mask==0xffffffff || mask&(1<<iCol) ){
85993        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
85994      }
85995    }
85996
85997    /* Invoke BEFORE DELETE trigger programs. */
85998    sqlite3CodeRowTrigger(pParse, pTrigger,
85999        TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
86000    );
86001
86002    /* Seek the cursor to the row to be deleted again. It may be that
86003    ** the BEFORE triggers coded above have already removed the row
86004    ** being deleted. Do not attempt to delete the row a second time, and
86005    ** do not fire AFTER triggers.  */
86006    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
86007
86008    /* Do FK processing. This call checks that any FK constraints that
86009    ** refer to this table (i.e. constraints attached to other tables)
86010    ** are not violated by deleting this row.  */
86011    sqlite3FkCheck(pParse, pTab, iOld, 0);
86012  }
86013
86014  /* Delete the index and table entries. Skip this step if pTab is really
86015  ** a view (in which case the only effect of the DELETE statement is to
86016  ** fire the INSTEAD OF triggers).  */
86017  if( pTab->pSelect==0 ){
86018    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
86019    sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
86020    if( count ){
86021      sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
86022    }
86023  }
86024
86025  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
86026  ** handle rows (possibly in other tables) that refer via a foreign key
86027  ** to the row just deleted. */
86028  sqlite3FkActions(pParse, pTab, 0, iOld);
86029
86030  /* Invoke AFTER DELETE trigger programs. */
86031  sqlite3CodeRowTrigger(pParse, pTrigger,
86032      TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
86033  );
86034
86035  /* Jump here if the row had already been deleted before any BEFORE
86036  ** trigger programs were invoked. Or if a trigger program throws a
86037  ** RAISE(IGNORE) exception.  */
86038  sqlite3VdbeResolveLabel(v, iLabel);
86039}
86040
86041/*
86042** This routine generates VDBE code that causes the deletion of all
86043** index entries associated with a single row of a single table.
86044**
86045** The VDBE must be in a particular state when this routine is called.
86046** These are the requirements:
86047**
86048**   1.  A read/write cursor pointing to pTab, the table containing the row
86049**       to be deleted, must be opened as cursor number "iCur".
86050**
86051**   2.  Read/write cursors for all indices of pTab must be open as
86052**       cursor number iCur+i for the i-th index.
86053**
86054**   3.  The "iCur" cursor must be pointing to the row that is to be
86055**       deleted.
86056*/
86057SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
86058  Parse *pParse,     /* Parsing and code generating context */
86059  Table *pTab,       /* Table containing the row to be deleted */
86060  int iCur,          /* Cursor number for the table */
86061  int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
86062){
86063  int i;
86064  Index *pIdx;
86065  int r1;
86066
86067  for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
86068    if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
86069    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
86070    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
86071  }
86072}
86073
86074/*
86075** Generate code that will assemble an index key and put it in register
86076** regOut.  The key with be for index pIdx which is an index on pTab.
86077** iCur is the index of a cursor open on the pTab table and pointing to
86078** the entry that needs indexing.
86079**
86080** Return a register number which is the first in a block of
86081** registers that holds the elements of the index key.  The
86082** block of registers has already been deallocated by the time
86083** this routine returns.
86084*/
86085SQLITE_PRIVATE int sqlite3GenerateIndexKey(
86086  Parse *pParse,     /* Parsing context */
86087  Index *pIdx,       /* The index for which to generate a key */
86088  int iCur,          /* Cursor number for the pIdx->pTable table */
86089  int regOut,        /* Write the new index key to this register */
86090  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
86091){
86092  Vdbe *v = pParse->pVdbe;
86093  int j;
86094  Table *pTab = pIdx->pTable;
86095  int regBase;
86096  int nCol;
86097
86098  nCol = pIdx->nColumn;
86099  regBase = sqlite3GetTempRange(pParse, nCol+1);
86100  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
86101  for(j=0; j<nCol; j++){
86102    int idx = pIdx->aiColumn[j];
86103    if( idx==pTab->iPKey ){
86104      sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
86105    }else{
86106      sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
86107      sqlite3ColumnDefault(v, pTab, idx, -1);
86108    }
86109  }
86110  if( doMakeRec ){
86111    const char *zAff;
86112    if( pTab->pSelect || (pParse->db->flags & SQLITE_IdxRealAsInt)!=0 ){
86113      zAff = 0;
86114    }else{
86115      zAff = sqlite3IndexAffinityStr(v, pIdx);
86116    }
86117    sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
86118    sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
86119  }
86120  sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
86121  return regBase;
86122}
86123
86124/************** End of delete.c **********************************************/
86125/************** Begin file func.c ********************************************/
86126/*
86127** 2002 February 23
86128**
86129** The author disclaims copyright to this source code.  In place of
86130** a legal notice, here is a blessing:
86131**
86132**    May you do good and not evil.
86133**    May you find forgiveness for yourself and forgive others.
86134**    May you share freely, never taking more than you give.
86135**
86136*************************************************************************
86137** This file contains the C functions that implement various SQL
86138** functions of SQLite.
86139**
86140** There is only one exported symbol in this file - the function
86141** sqliteRegisterBuildinFunctions() found at the bottom of the file.
86142** All other code has file scope.
86143*/
86144/* #include <stdlib.h> */
86145/* #include <assert.h> */
86146
86147/*
86148** Return the collating function associated with a function.
86149*/
86150static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
86151  return context->pColl;
86152}
86153
86154/*
86155** Indicate that the accumulator load should be skipped on this
86156** iteration of the aggregate loop.
86157*/
86158static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
86159  context->skipFlag = 1;
86160}
86161
86162/*
86163** Implementation of the non-aggregate min() and max() functions
86164*/
86165static void minmaxFunc(
86166  sqlite3_context *context,
86167  int argc,
86168  sqlite3_value **argv
86169){
86170  int i;
86171  int mask;    /* 0 for min() or 0xffffffff for max() */
86172  int iBest;
86173  CollSeq *pColl;
86174
86175  assert( argc>1 );
86176  mask = sqlite3_user_data(context)==0 ? 0 : -1;
86177  pColl = sqlite3GetFuncCollSeq(context);
86178  assert( pColl );
86179  assert( mask==-1 || mask==0 );
86180  iBest = 0;
86181  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
86182  for(i=1; i<argc; i++){
86183    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
86184    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
86185      testcase( mask==0 );
86186      iBest = i;
86187    }
86188  }
86189  sqlite3_result_value(context, argv[iBest]);
86190}
86191
86192/*
86193** Return the type of the argument.
86194*/
86195static void typeofFunc(
86196  sqlite3_context *context,
86197  int NotUsed,
86198  sqlite3_value **argv
86199){
86200  const char *z = 0;
86201  UNUSED_PARAMETER(NotUsed);
86202  switch( sqlite3_value_type(argv[0]) ){
86203    case SQLITE_INTEGER: z = "integer"; break;
86204    case SQLITE_TEXT:    z = "text";    break;
86205    case SQLITE_FLOAT:   z = "real";    break;
86206    case SQLITE_BLOB:    z = "blob";    break;
86207    default:             z = "null";    break;
86208  }
86209  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
86210}
86211
86212
86213/*
86214** Implementation of the length() function
86215*/
86216static void lengthFunc(
86217  sqlite3_context *context,
86218  int argc,
86219  sqlite3_value **argv
86220){
86221  int len;
86222
86223  assert( argc==1 );
86224  UNUSED_PARAMETER(argc);
86225  switch( sqlite3_value_type(argv[0]) ){
86226    case SQLITE_BLOB:
86227    case SQLITE_INTEGER:
86228    case SQLITE_FLOAT: {
86229      sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
86230      break;
86231    }
86232    case SQLITE_TEXT: {
86233      const unsigned char *z = sqlite3_value_text(argv[0]);
86234      if( z==0 ) return;
86235      len = 0;
86236      while( *z ){
86237        len++;
86238        SQLITE_SKIP_UTF8(z);
86239      }
86240      sqlite3_result_int(context, len);
86241      break;
86242    }
86243    default: {
86244      sqlite3_result_null(context);
86245      break;
86246    }
86247  }
86248}
86249
86250/*
86251** Implementation of the abs() function.
86252**
86253** IMP: R-23979-26855 The abs(X) function returns the absolute value of
86254** the numeric argument X.
86255*/
86256static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86257  assert( argc==1 );
86258  UNUSED_PARAMETER(argc);
86259  switch( sqlite3_value_type(argv[0]) ){
86260    case SQLITE_INTEGER: {
86261      i64 iVal = sqlite3_value_int64(argv[0]);
86262      if( iVal<0 ){
86263        if( (iVal<<1)==0 ){
86264          /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
86265          ** abs(X) throws an integer overflow error since there is no
86266          ** equivalent positive 64-bit two complement value. */
86267          sqlite3_result_error(context, "integer overflow", -1);
86268          return;
86269        }
86270        iVal = -iVal;
86271      }
86272      sqlite3_result_int64(context, iVal);
86273      break;
86274    }
86275    case SQLITE_NULL: {
86276      /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
86277      sqlite3_result_null(context);
86278      break;
86279    }
86280    default: {
86281      /* Because sqlite3_value_double() returns 0.0 if the argument is not
86282      ** something that can be converted into a number, we have:
86283      ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
86284      ** cannot be converted to a numeric value.
86285      */
86286      double rVal = sqlite3_value_double(argv[0]);
86287      if( rVal<0 ) rVal = -rVal;
86288      sqlite3_result_double(context, rVal);
86289      break;
86290    }
86291  }
86292}
86293
86294/*
86295** Implementation of the substr() function.
86296**
86297** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
86298** p1 is 1-indexed.  So substr(x,1,1) returns the first character
86299** of x.  If x is text, then we actually count UTF-8 characters.
86300** If x is a blob, then we count bytes.
86301**
86302** If p1 is negative, then we begin abs(p1) from the end of x[].
86303**
86304** If p2 is negative, return the p2 characters preceeding p1.
86305*/
86306static void substrFunc(
86307  sqlite3_context *context,
86308  int argc,
86309  sqlite3_value **argv
86310){
86311  const unsigned char *z;
86312  const unsigned char *z2;
86313  int len;
86314  int p0type;
86315  i64 p1, p2;
86316  int negP2 = 0;
86317
86318  assert( argc==3 || argc==2 );
86319  if( sqlite3_value_type(argv[1])==SQLITE_NULL
86320   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
86321  ){
86322    return;
86323  }
86324  p0type = sqlite3_value_type(argv[0]);
86325  p1 = sqlite3_value_int(argv[1]);
86326  if( p0type==SQLITE_BLOB ){
86327    len = sqlite3_value_bytes(argv[0]);
86328    z = sqlite3_value_blob(argv[0]);
86329    if( z==0 ) return;
86330    assert( len==sqlite3_value_bytes(argv[0]) );
86331  }else{
86332    z = sqlite3_value_text(argv[0]);
86333    if( z==0 ) return;
86334    len = 0;
86335    if( p1<0 ){
86336      for(z2=z; *z2; len++){
86337        SQLITE_SKIP_UTF8(z2);
86338      }
86339    }
86340  }
86341  if( argc==3 ){
86342    p2 = sqlite3_value_int(argv[2]);
86343    if( p2<0 ){
86344      p2 = -p2;
86345      negP2 = 1;
86346    }
86347  }else{
86348    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
86349  }
86350  if( p1<0 ){
86351    p1 += len;
86352    if( p1<0 ){
86353      p2 += p1;
86354      if( p2<0 ) p2 = 0;
86355      p1 = 0;
86356    }
86357  }else if( p1>0 ){
86358    p1--;
86359  }else if( p2>0 ){
86360    p2--;
86361  }
86362  if( negP2 ){
86363    p1 -= p2;
86364    if( p1<0 ){
86365      p2 += p1;
86366      p1 = 0;
86367    }
86368  }
86369  assert( p1>=0 && p2>=0 );
86370  if( p0type!=SQLITE_BLOB ){
86371    while( *z && p1 ){
86372      SQLITE_SKIP_UTF8(z);
86373      p1--;
86374    }
86375    for(z2=z; *z2 && p2; p2--){
86376      SQLITE_SKIP_UTF8(z2);
86377    }
86378    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
86379  }else{
86380    if( p1+p2>len ){
86381      p2 = len-p1;
86382      if( p2<0 ) p2 = 0;
86383    }
86384    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
86385  }
86386}
86387
86388/*
86389** Implementation of the round() function
86390*/
86391#ifndef SQLITE_OMIT_FLOATING_POINT
86392static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86393  int n = 0;
86394  double r;
86395  char *zBuf;
86396  assert( argc==1 || argc==2 );
86397  if( argc==2 ){
86398    if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
86399    n = sqlite3_value_int(argv[1]);
86400    if( n>30 ) n = 30;
86401    if( n<0 ) n = 0;
86402  }
86403  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
86404  r = sqlite3_value_double(argv[0]);
86405  /* If Y==0 and X will fit in a 64-bit int,
86406  ** handle the rounding directly,
86407  ** otherwise use printf.
86408  */
86409  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
86410    r = (double)((sqlite_int64)(r+0.5));
86411  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
86412    r = -(double)((sqlite_int64)((-r)+0.5));
86413  }else{
86414    zBuf = sqlite3_mprintf("%.*f",n,r);
86415    if( zBuf==0 ){
86416      sqlite3_result_error_nomem(context);
86417      return;
86418    }
86419    sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
86420    sqlite3_free(zBuf);
86421  }
86422  sqlite3_result_double(context, r);
86423}
86424#endif
86425
86426/*
86427** Allocate nByte bytes of space using sqlite3_malloc(). If the
86428** allocation fails, call sqlite3_result_error_nomem() to notify
86429** the database handle that malloc() has failed and return NULL.
86430** If nByte is larger than the maximum string or blob length, then
86431** raise an SQLITE_TOOBIG exception and return NULL.
86432*/
86433static void *contextMalloc(sqlite3_context *context, i64 nByte){
86434  char *z;
86435  sqlite3 *db = sqlite3_context_db_handle(context);
86436  assert( nByte>0 );
86437  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
86438  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
86439  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
86440    sqlite3_result_error_toobig(context);
86441    z = 0;
86442  }else{
86443    z = sqlite3Malloc((int)nByte);
86444    if( !z ){
86445      sqlite3_result_error_nomem(context);
86446    }
86447  }
86448  return z;
86449}
86450
86451/*
86452** Implementation of the upper() and lower() SQL functions.
86453*/
86454static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86455  char *z1;
86456  const char *z2;
86457  int i, n;
86458  UNUSED_PARAMETER(argc);
86459  z2 = (char*)sqlite3_value_text(argv[0]);
86460  n = sqlite3_value_bytes(argv[0]);
86461  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86462  assert( z2==(char*)sqlite3_value_text(argv[0]) );
86463  if( z2 ){
86464    z1 = contextMalloc(context, ((i64)n)+1);
86465    if( z1 ){
86466      for(i=0; i<n; i++){
86467        z1[i] = (char)sqlite3Toupper(z2[i]);
86468      }
86469      sqlite3_result_text(context, z1, n, sqlite3_free);
86470    }
86471  }
86472}
86473static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86474  char *z1;
86475  const char *z2;
86476  int i, n;
86477  UNUSED_PARAMETER(argc);
86478  z2 = (char*)sqlite3_value_text(argv[0]);
86479  n = sqlite3_value_bytes(argv[0]);
86480  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
86481  assert( z2==(char*)sqlite3_value_text(argv[0]) );
86482  if( z2 ){
86483    z1 = contextMalloc(context, ((i64)n)+1);
86484    if( z1 ){
86485      for(i=0; i<n; i++){
86486        z1[i] = sqlite3Tolower(z2[i]);
86487      }
86488      sqlite3_result_text(context, z1, n, sqlite3_free);
86489    }
86490  }
86491}
86492
86493
86494#if 0  /* This function is never used. */
86495/*
86496** The COALESCE() and IFNULL() functions used to be implemented as shown
86497** here.  But now they are implemented as VDBE code so that unused arguments
86498** do not have to be computed.  This legacy implementation is retained as
86499** comment.
86500*/
86501/*
86502** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
86503** All three do the same thing.  They return the first non-NULL
86504** argument.
86505*/
86506static void ifnullFunc(
86507  sqlite3_context *context,
86508  int argc,
86509  sqlite3_value **argv
86510){
86511  int i;
86512  for(i=0; i<argc; i++){
86513    if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
86514      sqlite3_result_value(context, argv[i]);
86515      break;
86516    }
86517  }
86518}
86519#endif /* NOT USED */
86520#define ifnullFunc versionFunc   /* Substitute function - never called */
86521
86522/*
86523** Implementation of random().  Return a random integer.
86524*/
86525static void randomFunc(
86526  sqlite3_context *context,
86527  int NotUsed,
86528  sqlite3_value **NotUsed2
86529){
86530  sqlite_int64 r;
86531  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86532  sqlite3_randomness(sizeof(r), &r);
86533  if( r<0 ){
86534    /* We need to prevent a random number of 0x8000000000000000
86535    ** (or -9223372036854775808) since when you do abs() of that
86536    ** number of you get the same value back again.  To do this
86537    ** in a way that is testable, mask the sign bit off of negative
86538    ** values, resulting in a positive value.  Then take the
86539    ** 2s complement of that positive value.  The end result can
86540    ** therefore be no less than -9223372036854775807.
86541    */
86542    r = -(r & LARGEST_INT64);
86543  }
86544  sqlite3_result_int64(context, r);
86545}
86546
86547/*
86548** Implementation of randomblob(N).  Return a random blob
86549** that is N bytes long.
86550*/
86551static void randomBlob(
86552  sqlite3_context *context,
86553  int argc,
86554  sqlite3_value **argv
86555){
86556  int n;
86557  unsigned char *p;
86558  assert( argc==1 );
86559  UNUSED_PARAMETER(argc);
86560  n = sqlite3_value_int(argv[0]);
86561  if( n<1 ){
86562    n = 1;
86563  }
86564  p = contextMalloc(context, n);
86565  if( p ){
86566    sqlite3_randomness(n, p);
86567    sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
86568  }
86569}
86570
86571/*
86572** Implementation of the last_insert_rowid() SQL function.  The return
86573** value is the same as the sqlite3_last_insert_rowid() API function.
86574*/
86575static void last_insert_rowid(
86576  sqlite3_context *context,
86577  int NotUsed,
86578  sqlite3_value **NotUsed2
86579){
86580  sqlite3 *db = sqlite3_context_db_handle(context);
86581  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86582  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
86583  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
86584  ** function. */
86585  sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
86586}
86587
86588/*
86589** Implementation of the changes() SQL function.
86590**
86591** IMP: R-62073-11209 The changes() SQL function is a wrapper
86592** around the sqlite3_changes() C/C++ function and hence follows the same
86593** rules for counting changes.
86594*/
86595static void changes(
86596  sqlite3_context *context,
86597  int NotUsed,
86598  sqlite3_value **NotUsed2
86599){
86600  sqlite3 *db = sqlite3_context_db_handle(context);
86601  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86602  sqlite3_result_int(context, sqlite3_changes(db));
86603}
86604
86605/*
86606** Implementation of the total_changes() SQL function.  The return value is
86607** the same as the sqlite3_total_changes() API function.
86608*/
86609static void total_changes(
86610  sqlite3_context *context,
86611  int NotUsed,
86612  sqlite3_value **NotUsed2
86613){
86614  sqlite3 *db = sqlite3_context_db_handle(context);
86615  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86616  /* IMP: R-52756-41993 This function is a wrapper around the
86617  ** sqlite3_total_changes() C/C++ interface. */
86618  sqlite3_result_int(context, sqlite3_total_changes(db));
86619}
86620
86621/*
86622** A structure defining how to do GLOB-style comparisons.
86623*/
86624struct compareInfo {
86625  u8 matchAll;
86626  u8 matchOne;
86627  u8 matchSet;
86628  u8 noCase;
86629};
86630
86631/*
86632** For LIKE and GLOB matching on EBCDIC machines, assume that every
86633** character is exactly one byte in size.  Also, all characters are
86634** able to participate in upper-case-to-lower-case mappings in EBCDIC
86635** whereas only characters less than 0x80 do in ASCII.
86636*/
86637#if defined(SQLITE_EBCDIC)
86638# define sqlite3Utf8Read(A,C)  (*(A++))
86639# define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
86640#else
86641# define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
86642#endif
86643
86644static const struct compareInfo globInfo = { '*', '?', '[', 0 };
86645/* The correct SQL-92 behavior is for the LIKE operator to ignore
86646** case.  Thus  'a' LIKE 'A' would be true. */
86647static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
86648/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
86649** is case sensitive causing 'a' LIKE 'A' to be false */
86650static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
86651
86652/*
86653** Compare two UTF-8 strings for equality where the first string can
86654** potentially be a "glob" expression.  Return true (1) if they
86655** are the same and false (0) if they are different.
86656**
86657** Globbing rules:
86658**
86659**      '*'       Matches any sequence of zero or more characters.
86660**
86661**      '?'       Matches exactly one character.
86662**
86663**     [...]      Matches one character from the enclosed list of
86664**                characters.
86665**
86666**     [^...]     Matches one character not in the enclosed list.
86667**
86668** With the [...] and [^...] matching, a ']' character can be included
86669** in the list by making it the first character after '[' or '^'.  A
86670** range of characters can be specified using '-'.  Example:
86671** "[a-z]" matches any single lower-case letter.  To match a '-', make
86672** it the last character in the list.
86673**
86674** This routine is usually quick, but can be N**2 in the worst case.
86675**
86676** Hints: to match '*' or '?', put them in "[]".  Like this:
86677**
86678**         abc[*]xyz        Matches "abc*xyz" only
86679*/
86680static int patternCompare(
86681  const u8 *zPattern,              /* The glob pattern */
86682  const u8 *zString,               /* The string to compare against the glob */
86683  const struct compareInfo *pInfo, /* Information about how to do the compare */
86684  u32 esc                          /* The escape character */
86685){
86686  u32 c, c2;
86687  int invert;
86688  int seen;
86689  u8 matchOne = pInfo->matchOne;
86690  u8 matchAll = pInfo->matchAll;
86691  u8 matchSet = pInfo->matchSet;
86692  u8 noCase = pInfo->noCase;
86693  int prevEscape = 0;     /* True if the previous character was 'escape' */
86694
86695  while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
86696    if( !prevEscape && c==matchAll ){
86697      while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
86698               || c == matchOne ){
86699        if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
86700          return 0;
86701        }
86702      }
86703      if( c==0 ){
86704        return 1;
86705      }else if( c==esc ){
86706        c = sqlite3Utf8Read(zPattern, &zPattern);
86707        if( c==0 ){
86708          return 0;
86709        }
86710      }else if( c==matchSet ){
86711        assert( esc==0 );         /* This is GLOB, not LIKE */
86712        assert( matchSet<0x80 );  /* '[' is a single-byte character */
86713        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
86714          SQLITE_SKIP_UTF8(zString);
86715        }
86716        return *zString!=0;
86717      }
86718      while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
86719        if( noCase ){
86720          GlogUpperToLower(c2);
86721          GlogUpperToLower(c);
86722          while( c2 != 0 && c2 != c ){
86723            c2 = sqlite3Utf8Read(zString, &zString);
86724            GlogUpperToLower(c2);
86725          }
86726        }else{
86727          while( c2 != 0 && c2 != c ){
86728            c2 = sqlite3Utf8Read(zString, &zString);
86729          }
86730        }
86731        if( c2==0 ) return 0;
86732        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
86733      }
86734      return 0;
86735    }else if( !prevEscape && c==matchOne ){
86736      if( sqlite3Utf8Read(zString, &zString)==0 ){
86737        return 0;
86738      }
86739    }else if( c==matchSet ){
86740      u32 prior_c = 0;
86741      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
86742      seen = 0;
86743      invert = 0;
86744      c = sqlite3Utf8Read(zString, &zString);
86745      if( c==0 ) return 0;
86746      c2 = sqlite3Utf8Read(zPattern, &zPattern);
86747      if( c2=='^' ){
86748        invert = 1;
86749        c2 = sqlite3Utf8Read(zPattern, &zPattern);
86750      }
86751      if( c2==']' ){
86752        if( c==']' ) seen = 1;
86753        c2 = sqlite3Utf8Read(zPattern, &zPattern);
86754      }
86755      while( c2 && c2!=']' ){
86756        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
86757          c2 = sqlite3Utf8Read(zPattern, &zPattern);
86758          if( c>=prior_c && c<=c2 ) seen = 1;
86759          prior_c = 0;
86760        }else{
86761          if( c==c2 ){
86762            seen = 1;
86763          }
86764          prior_c = c2;
86765        }
86766        c2 = sqlite3Utf8Read(zPattern, &zPattern);
86767      }
86768      if( c2==0 || (seen ^ invert)==0 ){
86769        return 0;
86770      }
86771    }else if( esc==c && !prevEscape ){
86772      prevEscape = 1;
86773    }else{
86774      c2 = sqlite3Utf8Read(zString, &zString);
86775      if( noCase ){
86776        GlogUpperToLower(c);
86777        GlogUpperToLower(c2);
86778      }
86779      if( c!=c2 ){
86780        return 0;
86781      }
86782      prevEscape = 0;
86783    }
86784  }
86785  return *zString==0;
86786}
86787
86788/*
86789** Count the number of times that the LIKE operator (or GLOB which is
86790** just a variation of LIKE) gets called.  This is used for testing
86791** only.
86792*/
86793#ifdef SQLITE_TEST
86794SQLITE_API int sqlite3_like_count = 0;
86795#endif
86796
86797
86798/*
86799** Implementation of the like() SQL function.  This function implements
86800** the build-in LIKE operator.  The first argument to the function is the
86801** pattern and the second argument is the string.  So, the SQL statements:
86802**
86803**       A LIKE B
86804**
86805** is implemented as like(B,A).
86806**
86807** This same function (with a different compareInfo structure) computes
86808** the GLOB operator.
86809*/
86810static void likeFunc(
86811  sqlite3_context *context,
86812  int argc,
86813  sqlite3_value **argv
86814){
86815  const unsigned char *zA, *zB;
86816  u32 escape = 0;
86817  int nPat;
86818  sqlite3 *db = sqlite3_context_db_handle(context);
86819
86820  zB = sqlite3_value_text(argv[0]);
86821  zA = sqlite3_value_text(argv[1]);
86822
86823  /* Limit the length of the LIKE or GLOB pattern to avoid problems
86824  ** of deep recursion and N*N behavior in patternCompare().
86825  */
86826  nPat = sqlite3_value_bytes(argv[0]);
86827  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
86828  testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
86829  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
86830    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
86831    return;
86832  }
86833  assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
86834
86835  if( argc==3 ){
86836    /* The escape character string must consist of a single UTF-8 character.
86837    ** Otherwise, return an error.
86838    */
86839    const unsigned char *zEsc = sqlite3_value_text(argv[2]);
86840    if( zEsc==0 ) return;
86841    if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
86842      sqlite3_result_error(context,
86843          "ESCAPE expression must be a single character", -1);
86844      return;
86845    }
86846    escape = sqlite3Utf8Read(zEsc, &zEsc);
86847  }
86848  if( zA && zB ){
86849    struct compareInfo *pInfo = sqlite3_user_data(context);
86850#ifdef SQLITE_TEST
86851    sqlite3_like_count++;
86852#endif
86853
86854    sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
86855  }
86856}
86857
86858/*
86859** Implementation of the NULLIF(x,y) function.  The result is the first
86860** argument if the arguments are different.  The result is NULL if the
86861** arguments are equal to each other.
86862*/
86863static void nullifFunc(
86864  sqlite3_context *context,
86865  int NotUsed,
86866  sqlite3_value **argv
86867){
86868  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
86869  UNUSED_PARAMETER(NotUsed);
86870  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
86871    sqlite3_result_value(context, argv[0]);
86872  }
86873}
86874
86875/*
86876** Implementation of the sqlite_version() function.  The result is the version
86877** of the SQLite library that is running.
86878*/
86879static void versionFunc(
86880  sqlite3_context *context,
86881  int NotUsed,
86882  sqlite3_value **NotUsed2
86883){
86884  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86885  /* IMP: R-48699-48617 This function is an SQL wrapper around the
86886  ** sqlite3_libversion() C-interface. */
86887  sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
86888}
86889
86890/*
86891** Implementation of the sqlite_source_id() function. The result is a string
86892** that identifies the particular version of the source code used to build
86893** SQLite.
86894*/
86895static void sourceidFunc(
86896  sqlite3_context *context,
86897  int NotUsed,
86898  sqlite3_value **NotUsed2
86899){
86900  UNUSED_PARAMETER2(NotUsed, NotUsed2);
86901  /* IMP: R-24470-31136 This function is an SQL wrapper around the
86902  ** sqlite3_sourceid() C interface. */
86903  sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
86904}
86905
86906/*
86907** Implementation of the sqlite_log() function.  This is a wrapper around
86908** sqlite3_log().  The return value is NULL.  The function exists purely for
86909** its side-effects.
86910*/
86911static void errlogFunc(
86912  sqlite3_context *context,
86913  int argc,
86914  sqlite3_value **argv
86915){
86916  UNUSED_PARAMETER(argc);
86917  UNUSED_PARAMETER(context);
86918  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
86919}
86920
86921/*
86922** Implementation of the sqlite_compileoption_used() function.
86923** The result is an integer that identifies if the compiler option
86924** was used to build SQLite.
86925*/
86926#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86927static void compileoptionusedFunc(
86928  sqlite3_context *context,
86929  int argc,
86930  sqlite3_value **argv
86931){
86932  const char *zOptName;
86933  assert( argc==1 );
86934  UNUSED_PARAMETER(argc);
86935  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
86936  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
86937  ** function.
86938  */
86939  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
86940    sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
86941  }
86942}
86943#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86944
86945/*
86946** Implementation of the sqlite_compileoption_get() function.
86947** The result is a string that identifies the compiler options
86948** used to build SQLite.
86949*/
86950#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
86951static void compileoptiongetFunc(
86952  sqlite3_context *context,
86953  int argc,
86954  sqlite3_value **argv
86955){
86956  int n;
86957  assert( argc==1 );
86958  UNUSED_PARAMETER(argc);
86959  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
86960  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
86961  */
86962  n = sqlite3_value_int(argv[0]);
86963  sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
86964}
86965#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
86966
86967/* Array for converting from half-bytes (nybbles) into ASCII hex
86968** digits. */
86969static const char hexdigits[] = {
86970  '0', '1', '2', '3', '4', '5', '6', '7',
86971  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
86972};
86973
86974/*
86975** EXPERIMENTAL - This is not an official function.  The interface may
86976** change.  This function may disappear.  Do not write code that depends
86977** on this function.
86978**
86979** Implementation of the QUOTE() function.  This function takes a single
86980** argument.  If the argument is numeric, the return value is the same as
86981** the argument.  If the argument is NULL, the return value is the string
86982** "NULL".  Otherwise, the argument is enclosed in single quotes with
86983** single-quote escapes.
86984*/
86985static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
86986  assert( argc==1 );
86987  UNUSED_PARAMETER(argc);
86988  switch( sqlite3_value_type(argv[0]) ){
86989    case SQLITE_INTEGER:
86990    case SQLITE_FLOAT: {
86991      sqlite3_result_value(context, argv[0]);
86992      break;
86993    }
86994    case SQLITE_BLOB: {
86995      char *zText = 0;
86996      char const *zBlob = sqlite3_value_blob(argv[0]);
86997      int nBlob = sqlite3_value_bytes(argv[0]);
86998      assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
86999      zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
87000      if( zText ){
87001        int i;
87002        for(i=0; i<nBlob; i++){
87003          zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
87004          zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
87005        }
87006        zText[(nBlob*2)+2] = '\'';
87007        zText[(nBlob*2)+3] = '\0';
87008        zText[0] = 'X';
87009        zText[1] = '\'';
87010        sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
87011        sqlite3_free(zText);
87012      }
87013      break;
87014    }
87015    case SQLITE_TEXT: {
87016      int i,j;
87017      u64 n;
87018      const unsigned char *zArg = sqlite3_value_text(argv[0]);
87019      char *z;
87020
87021      if( zArg==0 ) return;
87022      for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
87023      z = contextMalloc(context, ((i64)i)+((i64)n)+3);
87024      if( z ){
87025        z[0] = '\'';
87026        for(i=0, j=1; zArg[i]; i++){
87027          z[j++] = zArg[i];
87028          if( zArg[i]=='\'' ){
87029            z[j++] = '\'';
87030          }
87031        }
87032        z[j++] = '\'';
87033        z[j] = 0;
87034        sqlite3_result_text(context, z, j, sqlite3_free);
87035      }
87036      break;
87037    }
87038    default: {
87039      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
87040      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
87041      break;
87042    }
87043  }
87044}
87045
87046/*
87047** The hex() function.  Interpret the argument as a blob.  Return
87048** a hexadecimal rendering as text.
87049*/
87050static void hexFunc(
87051  sqlite3_context *context,
87052  int argc,
87053  sqlite3_value **argv
87054){
87055  int i, n;
87056  const unsigned char *pBlob;
87057  char *zHex, *z;
87058  assert( argc==1 );
87059  UNUSED_PARAMETER(argc);
87060  pBlob = sqlite3_value_blob(argv[0]);
87061  n = sqlite3_value_bytes(argv[0]);
87062  assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
87063  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
87064  if( zHex ){
87065    for(i=0; i<n; i++, pBlob++){
87066      unsigned char c = *pBlob;
87067      *(z++) = hexdigits[(c>>4)&0xf];
87068      *(z++) = hexdigits[c&0xf];
87069    }
87070    *z = 0;
87071    sqlite3_result_text(context, zHex, n*2, sqlite3_free);
87072  }
87073}
87074
87075/*
87076** The zeroblob(N) function returns a zero-filled blob of size N bytes.
87077*/
87078static void zeroblobFunc(
87079  sqlite3_context *context,
87080  int argc,
87081  sqlite3_value **argv
87082){
87083  i64 n;
87084  sqlite3 *db = sqlite3_context_db_handle(context);
87085  assert( argc==1 );
87086  UNUSED_PARAMETER(argc);
87087  n = sqlite3_value_int64(argv[0]);
87088  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
87089  testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
87090  if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87091    sqlite3_result_error_toobig(context);
87092  }else{
87093    sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
87094  }
87095}
87096
87097/*
87098** The replace() function.  Three arguments are all strings: call
87099** them A, B, and C. The result is also a string which is derived
87100** from A by replacing every occurance of B with C.  The match
87101** must be exact.  Collating sequences are not used.
87102*/
87103static void replaceFunc(
87104  sqlite3_context *context,
87105  int argc,
87106  sqlite3_value **argv
87107){
87108  const unsigned char *zStr;        /* The input string A */
87109  const unsigned char *zPattern;    /* The pattern string B */
87110  const unsigned char *zRep;        /* The replacement string C */
87111  unsigned char *zOut;              /* The output */
87112  int nStr;                /* Size of zStr */
87113  int nPattern;            /* Size of zPattern */
87114  int nRep;                /* Size of zRep */
87115  i64 nOut;                /* Maximum size of zOut */
87116  int loopLimit;           /* Last zStr[] that might match zPattern[] */
87117  int i, j;                /* Loop counters */
87118
87119  assert( argc==3 );
87120  UNUSED_PARAMETER(argc);
87121  zStr = sqlite3_value_text(argv[0]);
87122  if( zStr==0 ) return;
87123  nStr = sqlite3_value_bytes(argv[0]);
87124  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
87125  zPattern = sqlite3_value_text(argv[1]);
87126  if( zPattern==0 ){
87127    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
87128            || sqlite3_context_db_handle(context)->mallocFailed );
87129    return;
87130  }
87131  if( zPattern[0]==0 ){
87132    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
87133    sqlite3_result_value(context, argv[0]);
87134    return;
87135  }
87136  nPattern = sqlite3_value_bytes(argv[1]);
87137  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
87138  zRep = sqlite3_value_text(argv[2]);
87139  if( zRep==0 ) return;
87140  nRep = sqlite3_value_bytes(argv[2]);
87141  assert( zRep==sqlite3_value_text(argv[2]) );
87142  nOut = nStr + 1;
87143  assert( nOut<SQLITE_MAX_LENGTH );
87144  zOut = contextMalloc(context, (i64)nOut);
87145  if( zOut==0 ){
87146    return;
87147  }
87148  loopLimit = nStr - nPattern;
87149  for(i=j=0; i<=loopLimit; i++){
87150    if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
87151      zOut[j++] = zStr[i];
87152    }else{
87153      u8 *zOld;
87154      sqlite3 *db = sqlite3_context_db_handle(context);
87155      nOut += nRep - nPattern;
87156      testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
87157      testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
87158      if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87159        sqlite3_result_error_toobig(context);
87160        sqlite3_free(zOut);
87161        return;
87162      }
87163      zOld = zOut;
87164      zOut = sqlite3_realloc(zOut, (int)nOut);
87165      if( zOut==0 ){
87166        sqlite3_result_error_nomem(context);
87167        sqlite3_free(zOld);
87168        return;
87169      }
87170      memcpy(&zOut[j], zRep, nRep);
87171      j += nRep;
87172      i += nPattern-1;
87173    }
87174  }
87175  assert( j+nStr-i+1==nOut );
87176  memcpy(&zOut[j], &zStr[i], nStr-i);
87177  j += nStr - i;
87178  assert( j<=nOut );
87179  zOut[j] = 0;
87180  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
87181}
87182
87183/*
87184** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
87185** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
87186*/
87187static void trimFunc(
87188  sqlite3_context *context,
87189  int argc,
87190  sqlite3_value **argv
87191){
87192  const unsigned char *zIn;         /* Input string */
87193  const unsigned char *zCharSet;    /* Set of characters to trim */
87194  int nIn;                          /* Number of bytes in input */
87195  int flags;                        /* 1: trimleft  2: trimright  3: trim */
87196  int i;                            /* Loop counter */
87197  unsigned char *aLen = 0;          /* Length of each character in zCharSet */
87198  unsigned char **azChar = 0;       /* Individual characters in zCharSet */
87199  int nChar;                        /* Number of characters in zCharSet */
87200
87201  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
87202    return;
87203  }
87204  zIn = sqlite3_value_text(argv[0]);
87205  if( zIn==0 ) return;
87206  nIn = sqlite3_value_bytes(argv[0]);
87207  assert( zIn==sqlite3_value_text(argv[0]) );
87208  if( argc==1 ){
87209    static const unsigned char lenOne[] = { 1 };
87210    static unsigned char * const azOne[] = { (u8*)" " };
87211    nChar = 1;
87212    aLen = (u8*)lenOne;
87213    azChar = (unsigned char **)azOne;
87214    zCharSet = 0;
87215  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
87216    return;
87217  }else{
87218    const unsigned char *z;
87219    for(z=zCharSet, nChar=0; *z; nChar++){
87220      SQLITE_SKIP_UTF8(z);
87221    }
87222    if( nChar>0 ){
87223      azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
87224      if( azChar==0 ){
87225        return;
87226      }
87227      aLen = (unsigned char*)&azChar[nChar];
87228      for(z=zCharSet, nChar=0; *z; nChar++){
87229        azChar[nChar] = (unsigned char *)z;
87230        SQLITE_SKIP_UTF8(z);
87231        aLen[nChar] = (u8)(z - azChar[nChar]);
87232      }
87233    }
87234  }
87235  if( nChar>0 ){
87236    flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
87237    if( flags & 1 ){
87238      while( nIn>0 ){
87239        int len = 0;
87240        for(i=0; i<nChar; i++){
87241          len = aLen[i];
87242          if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
87243        }
87244        if( i>=nChar ) break;
87245        zIn += len;
87246        nIn -= len;
87247      }
87248    }
87249    if( flags & 2 ){
87250      while( nIn>0 ){
87251        int len = 0;
87252        for(i=0; i<nChar; i++){
87253          len = aLen[i];
87254          if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
87255        }
87256        if( i>=nChar ) break;
87257        nIn -= len;
87258      }
87259    }
87260    if( zCharSet ){
87261      sqlite3_free(azChar);
87262    }
87263  }
87264  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
87265}
87266
87267
87268/* IMP: R-25361-16150 This function is omitted from SQLite by default. It
87269** is only available if the SQLITE_SOUNDEX compile-time option is used
87270** when SQLite is built.
87271*/
87272#ifdef SQLITE_SOUNDEX
87273/*
87274** Compute the soundex encoding of a word.
87275**
87276** IMP: R-59782-00072 The soundex(X) function returns a string that is the
87277** soundex encoding of the string X.
87278*/
87279static void soundexFunc(
87280  sqlite3_context *context,
87281  int argc,
87282  sqlite3_value **argv
87283){
87284  char zResult[8];
87285  const u8 *zIn;
87286  int i, j;
87287  static const unsigned char iCode[] = {
87288    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87289    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87290    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87291    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
87292    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
87293    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
87294    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
87295    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
87296  };
87297  assert( argc==1 );
87298  zIn = (u8*)sqlite3_value_text(argv[0]);
87299  if( zIn==0 ) zIn = (u8*)"";
87300  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
87301  if( zIn[i] ){
87302    u8 prevcode = iCode[zIn[i]&0x7f];
87303    zResult[0] = sqlite3Toupper(zIn[i]);
87304    for(j=1; j<4 && zIn[i]; i++){
87305      int code = iCode[zIn[i]&0x7f];
87306      if( code>0 ){
87307        if( code!=prevcode ){
87308          prevcode = code;
87309          zResult[j++] = code + '0';
87310        }
87311      }else{
87312        prevcode = 0;
87313      }
87314    }
87315    while( j<4 ){
87316      zResult[j++] = '0';
87317    }
87318    zResult[j] = 0;
87319    sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
87320  }else{
87321    /* IMP: R-64894-50321 The string "?000" is returned if the argument
87322    ** is NULL or contains no ASCII alphabetic characters. */
87323    sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
87324  }
87325}
87326#endif /* SQLITE_SOUNDEX */
87327
87328#ifndef SQLITE_OMIT_LOAD_EXTENSION
87329/*
87330** A function that loads a shared-library extension then returns NULL.
87331*/
87332static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
87333  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
87334  const char *zProc;
87335  sqlite3 *db = sqlite3_context_db_handle(context);
87336  char *zErrMsg = 0;
87337
87338  if( argc==2 ){
87339    zProc = (const char *)sqlite3_value_text(argv[1]);
87340  }else{
87341    zProc = 0;
87342  }
87343  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
87344    sqlite3_result_error(context, zErrMsg, -1);
87345    sqlite3_free(zErrMsg);
87346  }
87347}
87348#endif
87349
87350
87351/*
87352** An instance of the following structure holds the context of a
87353** sum() or avg() aggregate computation.
87354*/
87355typedef struct SumCtx SumCtx;
87356struct SumCtx {
87357  double rSum;      /* Floating point sum */
87358  i64 iSum;         /* Integer sum */
87359  i64 cnt;          /* Number of elements summed */
87360  u8 overflow;      /* True if integer overflow seen */
87361  u8 approx;        /* True if non-integer value was input to the sum */
87362};
87363
87364/*
87365** Routines used to compute the sum, average, and total.
87366**
87367** The SUM() function follows the (broken) SQL standard which means
87368** that it returns NULL if it sums over no inputs.  TOTAL returns
87369** 0.0 in that case.  In addition, TOTAL always returns a float where
87370** SUM might return an integer if it never encounters a floating point
87371** value.  TOTAL never fails, but SUM might through an exception if
87372** it overflows an integer.
87373*/
87374static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87375  SumCtx *p;
87376  int type;
87377  assert( argc==1 );
87378  UNUSED_PARAMETER(argc);
87379  p = sqlite3_aggregate_context(context, sizeof(*p));
87380  type = sqlite3_value_numeric_type(argv[0]);
87381  if( p && type!=SQLITE_NULL ){
87382    p->cnt++;
87383    if( type==SQLITE_INTEGER ){
87384      i64 v = sqlite3_value_int64(argv[0]);
87385      p->rSum += v;
87386      if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
87387        p->overflow = 1;
87388      }
87389    }else{
87390      p->rSum += sqlite3_value_double(argv[0]);
87391      p->approx = 1;
87392    }
87393  }
87394}
87395static void sumFinalize(sqlite3_context *context){
87396  SumCtx *p;
87397  p = sqlite3_aggregate_context(context, 0);
87398  if( p && p->cnt>0 ){
87399    if( p->overflow ){
87400      sqlite3_result_error(context,"integer overflow",-1);
87401    }else if( p->approx ){
87402      sqlite3_result_double(context, p->rSum);
87403    }else{
87404      sqlite3_result_int64(context, p->iSum);
87405    }
87406  }
87407}
87408static void avgFinalize(sqlite3_context *context){
87409  SumCtx *p;
87410  p = sqlite3_aggregate_context(context, 0);
87411  if( p && p->cnt>0 ){
87412    sqlite3_result_double(context, p->rSum/(double)p->cnt);
87413  }
87414}
87415static void totalFinalize(sqlite3_context *context){
87416  SumCtx *p;
87417  p = sqlite3_aggregate_context(context, 0);
87418  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
87419  sqlite3_result_double(context, p ? p->rSum : (double)0);
87420}
87421
87422/*
87423** The following structure keeps track of state information for the
87424** count() aggregate function.
87425*/
87426typedef struct CountCtx CountCtx;
87427struct CountCtx {
87428  i64 n;
87429};
87430
87431/*
87432** Routines to implement the count() aggregate function.
87433*/
87434static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
87435  CountCtx *p;
87436  p = sqlite3_aggregate_context(context, sizeof(*p));
87437  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
87438    p->n++;
87439  }
87440
87441#ifndef SQLITE_OMIT_DEPRECATED
87442  /* The sqlite3_aggregate_count() function is deprecated.  But just to make
87443  ** sure it still operates correctly, verify that its count agrees with our
87444  ** internal count when using count(*) and when the total count can be
87445  ** expressed as a 32-bit integer. */
87446  assert( argc==1 || p==0 || p->n>0x7fffffff
87447          || p->n==sqlite3_aggregate_count(context) );
87448#endif
87449}
87450static void countFinalize(sqlite3_context *context){
87451  CountCtx *p;
87452  p = sqlite3_aggregate_context(context, 0);
87453  sqlite3_result_int64(context, p ? p->n : 0);
87454}
87455
87456/*
87457** Routines to implement min() and max() aggregate functions.
87458*/
87459static void minmaxStep(
87460  sqlite3_context *context,
87461  int NotUsed,
87462  sqlite3_value **argv
87463){
87464  Mem *pArg  = (Mem *)argv[0];
87465  Mem *pBest;
87466  UNUSED_PARAMETER(NotUsed);
87467
87468  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
87469  if( !pBest ) return;
87470
87471  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
87472    if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
87473  }else if( pBest->flags ){
87474    int max;
87475    int cmp;
87476    CollSeq *pColl = sqlite3GetFuncCollSeq(context);
87477    /* This step function is used for both the min() and max() aggregates,
87478    ** the only difference between the two being that the sense of the
87479    ** comparison is inverted. For the max() aggregate, the
87480    ** sqlite3_user_data() function returns (void *)-1. For min() it
87481    ** returns (void *)db, where db is the sqlite3* database pointer.
87482    ** Therefore the next statement sets variable 'max' to 1 for the max()
87483    ** aggregate, or 0 for min().
87484    */
87485    max = sqlite3_user_data(context)!=0;
87486    cmp = sqlite3MemCompare(pBest, pArg, pColl);
87487    if( (max && cmp<0) || (!max && cmp>0) ){
87488      sqlite3VdbeMemCopy(pBest, pArg);
87489    }else{
87490      sqlite3SkipAccumulatorLoad(context);
87491    }
87492  }else{
87493    sqlite3VdbeMemCopy(pBest, pArg);
87494  }
87495}
87496static void minMaxFinalize(sqlite3_context *context){
87497  sqlite3_value *pRes;
87498  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
87499  if( pRes ){
87500    if( pRes->flags ){
87501      sqlite3_result_value(context, pRes);
87502    }
87503    sqlite3VdbeMemRelease(pRes);
87504  }
87505}
87506
87507/*
87508** group_concat(EXPR, ?SEPARATOR?)
87509*/
87510static void groupConcatStep(
87511  sqlite3_context *context,
87512  int argc,
87513  sqlite3_value **argv
87514){
87515  const char *zVal;
87516  StrAccum *pAccum;
87517  const char *zSep;
87518  int nVal, nSep;
87519  assert( argc==1 || argc==2 );
87520  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87521  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
87522
87523  if( pAccum ){
87524    sqlite3 *db = sqlite3_context_db_handle(context);
87525    int firstTerm = pAccum->useMalloc==0;
87526    pAccum->useMalloc = 2;
87527    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
87528    if( !firstTerm ){
87529      if( argc==2 ){
87530        zSep = (char*)sqlite3_value_text(argv[1]);
87531        nSep = sqlite3_value_bytes(argv[1]);
87532      }else{
87533        zSep = ",";
87534        nSep = 1;
87535      }
87536      sqlite3StrAccumAppend(pAccum, zSep, nSep);
87537    }
87538    zVal = (char*)sqlite3_value_text(argv[0]);
87539    nVal = sqlite3_value_bytes(argv[0]);
87540    sqlite3StrAccumAppend(pAccum, zVal, nVal);
87541  }
87542}
87543static void groupConcatFinalize(sqlite3_context *context){
87544  StrAccum *pAccum;
87545  pAccum = sqlite3_aggregate_context(context, 0);
87546  if( pAccum ){
87547    if( pAccum->tooBig ){
87548      sqlite3_result_error_toobig(context);
87549    }else if( pAccum->mallocFailed ){
87550      sqlite3_result_error_nomem(context);
87551    }else{
87552      sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
87553                          sqlite3_free);
87554    }
87555  }
87556}
87557
87558/*
87559** This routine does per-connection function registration.  Most
87560** of the built-in functions above are part of the global function set.
87561** This routine only deals with those that are not global.
87562*/
87563SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
87564  int rc = sqlite3_overload_function(db, "MATCH", 2);
87565  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
87566  if( rc==SQLITE_NOMEM ){
87567    db->mallocFailed = 1;
87568  }
87569}
87570
87571/*
87572** Set the LIKEOPT flag on the 2-argument function with the given name.
87573*/
87574static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
87575  FuncDef *pDef;
87576  pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
87577                             2, SQLITE_UTF8, 0);
87578  if( ALWAYS(pDef) ){
87579    pDef->flags = flagVal;
87580  }
87581}
87582
87583/*
87584** Register the built-in LIKE and GLOB functions.  The caseSensitive
87585** parameter determines whether or not the LIKE operator is case
87586** sensitive.  GLOB is always case sensitive.
87587*/
87588SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
87589  struct compareInfo *pInfo;
87590  if( caseSensitive ){
87591    pInfo = (struct compareInfo*)&likeInfoAlt;
87592  }else{
87593    pInfo = (struct compareInfo*)&likeInfoNorm;
87594  }
87595  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87596  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
87597  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
87598      (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
87599  setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
87600  setLikeOptFlag(db, "like",
87601      caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
87602}
87603
87604/*
87605** pExpr points to an expression which implements a function.  If
87606** it is appropriate to apply the LIKE optimization to that function
87607** then set aWc[0] through aWc[2] to the wildcard characters and
87608** return TRUE.  If the function is not a LIKE-style function then
87609** return FALSE.
87610*/
87611SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
87612  FuncDef *pDef;
87613  if( pExpr->op!=TK_FUNCTION
87614   || !pExpr->x.pList
87615   || pExpr->x.pList->nExpr!=2
87616  ){
87617    return 0;
87618  }
87619  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
87620  pDef = sqlite3FindFunction(db, pExpr->u.zToken,
87621                             sqlite3Strlen30(pExpr->u.zToken),
87622                             2, SQLITE_UTF8, 0);
87623  if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
87624    return 0;
87625  }
87626
87627  /* The memcpy() statement assumes that the wildcard characters are
87628  ** the first three statements in the compareInfo structure.  The
87629  ** asserts() that follow verify that assumption
87630  */
87631  memcpy(aWc, pDef->pUserData, 3);
87632  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
87633  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
87634  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
87635  *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
87636  return 1;
87637}
87638
87639/*
87640** All all of the FuncDef structures in the aBuiltinFunc[] array above
87641** to the global function hash table.  This occurs at start-time (as
87642** a consequence of calling sqlite3_initialize()).
87643**
87644** After this routine runs
87645*/
87646SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
87647  /*
87648  ** The following array holds FuncDef structures for all of the functions
87649  ** defined in this file.
87650  **
87651  ** The array cannot be constant since changes are made to the
87652  ** FuncDef.pHash elements at start-time.  The elements of this array
87653  ** are read-only after initialization is complete.
87654  */
87655  static SQLITE_WSD FuncDef aBuiltinFunc[] = {
87656    FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
87657    FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
87658    FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
87659    FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
87660    FUNCTION(trim,               1, 3, 0, trimFunc         ),
87661    FUNCTION(trim,               2, 3, 0, trimFunc         ),
87662    FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
87663    FUNCTION(min,                0, 0, 1, 0                ),
87664    AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
87665    FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
87666    FUNCTION(max,                0, 1, 1, 0                ),
87667    AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
87668    FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
87669    FUNCTION(length,             1, 0, 0, lengthFunc       ),
87670    FUNCTION(substr,             2, 0, 0, substrFunc       ),
87671    FUNCTION(substr,             3, 0, 0, substrFunc       ),
87672    FUNCTION(abs,                1, 0, 0, absFunc          ),
87673#ifndef SQLITE_OMIT_FLOATING_POINT
87674    FUNCTION(round,              1, 0, 0, roundFunc        ),
87675    FUNCTION(round,              2, 0, 0, roundFunc        ),
87676#endif
87677    FUNCTION(upper,              1, 0, 0, upperFunc        ),
87678    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
87679    FUNCTION(coalesce,           1, 0, 0, 0                ),
87680    FUNCTION(coalesce,           0, 0, 0, 0                ),
87681/*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
87682    {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0,0},
87683    FUNCTION(hex,                1, 0, 0, hexFunc          ),
87684/*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
87685    {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0,0},
87686    FUNCTION(random,             0, 0, 0, randomFunc       ),
87687    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
87688    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
87689    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
87690    FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
87691    FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
87692#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87693    FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
87694    FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
87695#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
87696    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
87697    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
87698    FUNCTION(changes,            0, 0, 0, changes          ),
87699    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
87700    FUNCTION(replace,            3, 0, 0, replaceFunc      ),
87701    FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
87702  #ifdef SQLITE_SOUNDEX
87703    FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
87704  #endif
87705  #ifndef SQLITE_OMIT_LOAD_EXTENSION
87706    FUNCTION(load_extension,     1, 0, 0, loadExt          ),
87707    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
87708  #endif
87709    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
87710    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
87711    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
87712 /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
87713    {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
87714    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
87715    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
87716    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
87717
87718    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87719  #ifdef SQLITE_CASE_SENSITIVE_LIKE
87720    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87721    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
87722  #else
87723    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
87724    LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
87725  #endif
87726  };
87727
87728  int i;
87729  FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
87730  FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
87731
87732  for(i=0; i<ArraySize(aBuiltinFunc); i++){
87733    sqlite3FuncDefInsert(pHash, &aFunc[i]);
87734  }
87735  sqlite3RegisterDateTimeFunctions();
87736#ifndef SQLITE_OMIT_ALTERTABLE
87737  sqlite3AlterFunctions();
87738#endif
87739}
87740
87741/************** End of func.c ************************************************/
87742/************** Begin file fkey.c ********************************************/
87743/*
87744**
87745** The author disclaims copyright to this source code.  In place of
87746** a legal notice, here is a blessing:
87747**
87748**    May you do good and not evil.
87749**    May you find forgiveness for yourself and forgive others.
87750**    May you share freely, never taking more than you give.
87751**
87752*************************************************************************
87753** This file contains code used by the compiler to add foreign key
87754** support to compiled SQL statements.
87755*/
87756
87757#ifndef SQLITE_OMIT_FOREIGN_KEY
87758#ifndef SQLITE_OMIT_TRIGGER
87759
87760/*
87761** Deferred and Immediate FKs
87762** --------------------------
87763**
87764** Foreign keys in SQLite come in two flavours: deferred and immediate.
87765** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
87766** is returned and the current statement transaction rolled back. If a
87767** deferred foreign key constraint is violated, no action is taken
87768** immediately. However if the application attempts to commit the
87769** transaction before fixing the constraint violation, the attempt fails.
87770**
87771** Deferred constraints are implemented using a simple counter associated
87772** with the database handle. The counter is set to zero each time a
87773** database transaction is opened. Each time a statement is executed
87774** that causes a foreign key violation, the counter is incremented. Each
87775** time a statement is executed that removes an existing violation from
87776** the database, the counter is decremented. When the transaction is
87777** committed, the commit fails if the current value of the counter is
87778** greater than zero. This scheme has two big drawbacks:
87779**
87780**   * When a commit fails due to a deferred foreign key constraint,
87781**     there is no way to tell which foreign constraint is not satisfied,
87782**     or which row it is not satisfied for.
87783**
87784**   * If the database contains foreign key violations when the
87785**     transaction is opened, this may cause the mechanism to malfunction.
87786**
87787** Despite these problems, this approach is adopted as it seems simpler
87788** than the alternatives.
87789**
87790** INSERT operations:
87791**
87792**   I.1) For each FK for which the table is the child table, search
87793**        the parent table for a match. If none is found increment the
87794**        constraint counter.
87795**
87796**   I.2) For each FK for which the table is the parent table,
87797**        search the child table for rows that correspond to the new
87798**        row in the parent table. Decrement the counter for each row
87799**        found (as the constraint is now satisfied).
87800**
87801** DELETE operations:
87802**
87803**   D.1) For each FK for which the table is the child table,
87804**        search the parent table for a row that corresponds to the
87805**        deleted row in the child table. If such a row is not found,
87806**        decrement the counter.
87807**
87808**   D.2) For each FK for which the table is the parent table, search
87809**        the child table for rows that correspond to the deleted row
87810**        in the parent table. For each found increment the counter.
87811**
87812** UPDATE operations:
87813**
87814**   An UPDATE command requires that all 4 steps above are taken, but only
87815**   for FK constraints for which the affected columns are actually
87816**   modified (values must be compared at runtime).
87817**
87818** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
87819** This simplifies the implementation a bit.
87820**
87821** For the purposes of immediate FK constraints, the OR REPLACE conflict
87822** resolution is considered to delete rows before the new row is inserted.
87823** If a delete caused by OR REPLACE violates an FK constraint, an exception
87824** is thrown, even if the FK constraint would be satisfied after the new
87825** row is inserted.
87826**
87827** Immediate constraints are usually handled similarly. The only difference
87828** is that the counter used is stored as part of each individual statement
87829** object (struct Vdbe). If, after the statement has run, its immediate
87830** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
87831** and the statement transaction is rolled back. An exception is an INSERT
87832** statement that inserts a single row only (no triggers). In this case,
87833** instead of using a counter, an exception is thrown immediately if the
87834** INSERT violates a foreign key constraint. This is necessary as such
87835** an INSERT does not open a statement transaction.
87836**
87837** TODO: How should dropping a table be handled? How should renaming a
87838** table be handled?
87839**
87840**
87841** Query API Notes
87842** ---------------
87843**
87844** Before coding an UPDATE or DELETE row operation, the code-generator
87845** for those two operations needs to know whether or not the operation
87846** requires any FK processing and, if so, which columns of the original
87847** row are required by the FK processing VDBE code (i.e. if FKs were
87848** implemented using triggers, which of the old.* columns would be
87849** accessed). No information is required by the code-generator before
87850** coding an INSERT operation. The functions used by the UPDATE/DELETE
87851** generation code to query for this information are:
87852**
87853**   sqlite3FkRequired() - Test to see if FK processing is required.
87854**   sqlite3FkOldmask()  - Query for the set of required old.* columns.
87855**
87856**
87857** Externally accessible module functions
87858** --------------------------------------
87859**
87860**   sqlite3FkCheck()    - Check for foreign key violations.
87861**   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
87862**   sqlite3FkDelete()   - Delete an FKey structure.
87863*/
87864
87865/*
87866** VDBE Calling Convention
87867** -----------------------
87868**
87869** Example:
87870**
87871**   For the following INSERT statement:
87872**
87873**     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
87874**     INSERT INTO t1 VALUES(1, 2, 3.1);
87875**
87876**   Register (x):        2    (type integer)
87877**   Register (x+1):      1    (type integer)
87878**   Register (x+2):      NULL (type NULL)
87879**   Register (x+3):      3.1  (type real)
87880*/
87881
87882/*
87883** A foreign key constraint requires that the key columns in the parent
87884** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
87885** Given that pParent is the parent table for foreign key constraint pFKey,
87886** search the schema a unique index on the parent key columns.
87887**
87888** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
87889** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
87890** is set to point to the unique index.
87891**
87892** If the parent key consists of a single column (the foreign key constraint
87893** is not a composite foreign key), output variable *paiCol is set to NULL.
87894** Otherwise, it is set to point to an allocated array of size N, where
87895** N is the number of columns in the parent key. The first element of the
87896** array is the index of the child table column that is mapped by the FK
87897** constraint to the parent table column stored in the left-most column
87898** of index *ppIdx. The second element of the array is the index of the
87899** child table column that corresponds to the second left-most column of
87900** *ppIdx, and so on.
87901**
87902** If the required index cannot be found, either because:
87903**
87904**   1) The named parent key columns do not exist, or
87905**
87906**   2) The named parent key columns do exist, but are not subject to a
87907**      UNIQUE or PRIMARY KEY constraint, or
87908**
87909**   3) No parent key columns were provided explicitly as part of the
87910**      foreign key definition, and the parent table does not have a
87911**      PRIMARY KEY, or
87912**
87913**   4) No parent key columns were provided explicitly as part of the
87914**      foreign key definition, and the PRIMARY KEY of the parent table
87915**      consists of a a different number of columns to the child key in
87916**      the child table.
87917**
87918** then non-zero is returned, and a "foreign key mismatch" error loaded
87919** into pParse. If an OOM error occurs, non-zero is returned and the
87920** pParse->db->mallocFailed flag is set.
87921*/
87922static int locateFkeyIndex(
87923  Parse *pParse,                  /* Parse context to store any error in */
87924  Table *pParent,                 /* Parent table of FK constraint pFKey */
87925  FKey *pFKey,                    /* Foreign key to find index for */
87926  Index **ppIdx,                  /* OUT: Unique index on parent table */
87927  int **paiCol                    /* OUT: Map of index columns in pFKey */
87928){
87929  Index *pIdx = 0;                    /* Value to return via *ppIdx */
87930  int *aiCol = 0;                     /* Value to return via *paiCol */
87931  int nCol = pFKey->nCol;             /* Number of columns in parent key */
87932  char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
87933
87934  /* The caller is responsible for zeroing output parameters. */
87935  assert( ppIdx && *ppIdx==0 );
87936  assert( !paiCol || *paiCol==0 );
87937  assert( pParse );
87938
87939  /* If this is a non-composite (single column) foreign key, check if it
87940  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
87941  ** and *paiCol set to zero and return early.
87942  **
87943  ** Otherwise, for a composite foreign key (more than one column), allocate
87944  ** space for the aiCol array (returned via output parameter *paiCol).
87945  ** Non-composite foreign keys do not require the aiCol array.
87946  */
87947  if( nCol==1 ){
87948    /* The FK maps to the IPK if any of the following are true:
87949    **
87950    **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
87951    **      mapped to the primary key of table pParent, or
87952    **   2) The FK is explicitly mapped to a column declared as INTEGER
87953    **      PRIMARY KEY.
87954    */
87955    if( pParent->iPKey>=0 ){
87956      if( !zKey ) return 0;
87957      if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
87958    }
87959  }else if( paiCol ){
87960    assert( nCol>1 );
87961    aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
87962    if( !aiCol ) return 1;
87963    *paiCol = aiCol;
87964  }
87965
87966  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
87967    if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
87968      /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
87969      ** of columns. If each indexed column corresponds to a foreign key
87970      ** column of pFKey, then this index is a winner.  */
87971
87972      if( zKey==0 ){
87973        /* If zKey is NULL, then this foreign key is implicitly mapped to
87974        ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
87975        ** identified by the test (Index.autoIndex==2).  */
87976        if( pIdx->autoIndex==2 ){
87977          if( aiCol ){
87978            int i;
87979            for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
87980          }
87981          break;
87982        }
87983      }else{
87984        /* If zKey is non-NULL, then this foreign key was declared to
87985        ** map to an explicit list of columns in table pParent. Check if this
87986        ** index matches those columns. Also, check that the index uses
87987        ** the default collation sequences for each column. */
87988        int i, j;
87989        for(i=0; i<nCol; i++){
87990          int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
87991          char *zDfltColl;                  /* Def. collation for column */
87992          char *zIdxCol;                    /* Name of indexed column */
87993
87994          /* If the index uses a collation sequence that is different from
87995          ** the default collation sequence for the column, this index is
87996          ** unusable. Bail out early in this case.  */
87997          zDfltColl = pParent->aCol[iCol].zColl;
87998          if( !zDfltColl ){
87999            zDfltColl = "BINARY";
88000          }
88001          if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
88002
88003          zIdxCol = pParent->aCol[iCol].zName;
88004          for(j=0; j<nCol; j++){
88005            if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
88006              if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
88007              break;
88008            }
88009          }
88010          if( j==nCol ) break;
88011        }
88012        if( i==nCol ) break;      /* pIdx is usable */
88013      }
88014    }
88015  }
88016
88017  if( !pIdx ){
88018    if( !pParse->disableTriggers ){
88019      sqlite3ErrorMsg(pParse, "foreign key mismatch");
88020    }
88021    sqlite3DbFree(pParse->db, aiCol);
88022    return 1;
88023  }
88024
88025  *ppIdx = pIdx;
88026  return 0;
88027}
88028
88029/*
88030** This function is called when a row is inserted into or deleted from the
88031** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
88032** on the child table of pFKey, this function is invoked twice for each row
88033** affected - once to "delete" the old row, and then again to "insert" the
88034** new row.
88035**
88036** Each time it is called, this function generates VDBE code to locate the
88037** row in the parent table that corresponds to the row being inserted into
88038** or deleted from the child table. If the parent row can be found, no
88039** special action is taken. Otherwise, if the parent row can *not* be
88040** found in the parent table:
88041**
88042**   Operation | FK type   | Action taken
88043**   --------------------------------------------------------------------------
88044**   INSERT      immediate   Increment the "immediate constraint counter".
88045**
88046**   DELETE      immediate   Decrement the "immediate constraint counter".
88047**
88048**   INSERT      deferred    Increment the "deferred constraint counter".
88049**
88050**   DELETE      deferred    Decrement the "deferred constraint counter".
88051**
88052** These operations are identified in the comment at the top of this file
88053** (fkey.c) as "I.1" and "D.1".
88054*/
88055static void fkLookupParent(
88056  Parse *pParse,        /* Parse context */
88057  int iDb,              /* Index of database housing pTab */
88058  Table *pTab,          /* Parent table of FK pFKey */
88059  Index *pIdx,          /* Unique index on parent key columns in pTab */
88060  FKey *pFKey,          /* Foreign key constraint */
88061  int *aiCol,           /* Map from parent key columns to child table columns */
88062  int regData,          /* Address of array containing child table row */
88063  int nIncr,            /* Increment constraint counter by this */
88064  int isIgnore          /* If true, pretend pTab contains all NULL values */
88065){
88066  int i;                                    /* Iterator variable */
88067  Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
88068  int iCur = pParse->nTab - 1;              /* Cursor number to use */
88069  int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
88070
88071  /* If nIncr is less than zero, then check at runtime if there are any
88072  ** outstanding constraints to resolve. If there are not, there is no need
88073  ** to check if deleting this row resolves any outstanding violations.
88074  **
88075  ** Check if any of the key columns in the child table row are NULL. If
88076  ** any are, then the constraint is considered satisfied. No need to
88077  ** search for a matching row in the parent table.  */
88078  if( nIncr<0 ){
88079    sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
88080  }
88081  for(i=0; i<pFKey->nCol; i++){
88082    int iReg = aiCol[i] + regData + 1;
88083    sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
88084  }
88085
88086  if( isIgnore==0 ){
88087    if( pIdx==0 ){
88088      /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
88089      ** column of the parent table (table pTab).  */
88090      int iMustBeInt;               /* Address of MustBeInt instruction */
88091      int regTemp = sqlite3GetTempReg(pParse);
88092
88093      /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
88094      ** apply the affinity of the parent key). If this fails, then there
88095      ** is no matching parent key. Before using MustBeInt, make a copy of
88096      ** the value. Otherwise, the value inserted into the child key column
88097      ** will have INTEGER affinity applied to it, which may not be correct.  */
88098      sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
88099      iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
88100
88101      /* If the parent table is the same as the child table, and we are about
88102      ** to increment the constraint-counter (i.e. this is an INSERT operation),
88103      ** then check if the row being inserted matches itself. If so, do not
88104      ** increment the constraint-counter.  */
88105      if( pTab==pFKey->pFrom && nIncr==1 ){
88106        sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
88107      }
88108
88109      sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
88110      sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
88111      sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
88112      sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
88113      sqlite3VdbeJumpHere(v, iMustBeInt);
88114      sqlite3ReleaseTempReg(pParse, regTemp);
88115    }else{
88116      int nCol = pFKey->nCol;
88117      int regTemp = sqlite3GetTempRange(pParse, nCol);
88118      int regRec = sqlite3GetTempReg(pParse);
88119      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
88120
88121      sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
88122      sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
88123      for(i=0; i<nCol; i++){
88124        sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
88125      }
88126
88127      /* If the parent table is the same as the child table, and we are about
88128      ** to increment the constraint-counter (i.e. this is an INSERT operation),
88129      ** then check if the row being inserted matches itself. If so, do not
88130      ** increment the constraint-counter.
88131      **
88132      ** If any of the parent-key values are NULL, then the row cannot match
88133      ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
88134      ** of the parent-key values are NULL (at this point it is known that
88135      ** none of the child key values are).
88136      */
88137      if( pTab==pFKey->pFrom && nIncr==1 ){
88138        int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
88139        for(i=0; i<nCol; i++){
88140          int iChild = aiCol[i]+1+regData;
88141          int iParent = pIdx->aiColumn[i]+1+regData;
88142          assert( aiCol[i]!=pTab->iPKey );
88143          if( pIdx->aiColumn[i]==pTab->iPKey ){
88144            /* The parent key is a composite key that includes the IPK column */
88145            iParent = regData;
88146          }
88147          sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
88148          sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
88149        }
88150        sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
88151      }
88152
88153      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
88154      sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
88155      sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
88156
88157      sqlite3ReleaseTempReg(pParse, regRec);
88158      sqlite3ReleaseTempRange(pParse, regTemp, nCol);
88159    }
88160  }
88161
88162  if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88163    /* Special case: If this is an INSERT statement that will insert exactly
88164    ** one row into the table, raise a constraint immediately instead of
88165    ** incrementing a counter. This is necessary as the VM code is being
88166    ** generated for will not open a statement transaction.  */
88167    assert( nIncr==1 );
88168    sqlite3HaltConstraint(
88169        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
88170    );
88171  }else{
88172    if( nIncr>0 && pFKey->isDeferred==0 ){
88173      sqlite3ParseToplevel(pParse)->mayAbort = 1;
88174    }
88175    sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
88176  }
88177
88178  sqlite3VdbeResolveLabel(v, iOk);
88179  sqlite3VdbeAddOp1(v, OP_Close, iCur);
88180}
88181
88182/*
88183** This function is called to generate code executed when a row is deleted
88184** from the parent table of foreign key constraint pFKey and, if pFKey is
88185** deferred, when a row is inserted into the same table. When generating
88186** code for an SQL UPDATE operation, this function may be called twice -
88187** once to "delete" the old row and once to "insert" the new row.
88188**
88189** The code generated by this function scans through the rows in the child
88190** table that correspond to the parent table row being deleted or inserted.
88191** For each child row found, one of the following actions is taken:
88192**
88193**   Operation | FK type   | Action taken
88194**   --------------------------------------------------------------------------
88195**   DELETE      immediate   Increment the "immediate constraint counter".
88196**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
88197**                           throw a "foreign key constraint failed" exception.
88198**
88199**   INSERT      immediate   Decrement the "immediate constraint counter".
88200**
88201**   DELETE      deferred    Increment the "deferred constraint counter".
88202**                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
88203**                           throw a "foreign key constraint failed" exception.
88204**
88205**   INSERT      deferred    Decrement the "deferred constraint counter".
88206**
88207** These operations are identified in the comment at the top of this file
88208** (fkey.c) as "I.2" and "D.2".
88209*/
88210static void fkScanChildren(
88211  Parse *pParse,                  /* Parse context */
88212  SrcList *pSrc,                  /* SrcList containing the table to scan */
88213  Table *pTab,
88214  Index *pIdx,                    /* Foreign key index */
88215  FKey *pFKey,                    /* Foreign key relationship */
88216  int *aiCol,                     /* Map from pIdx cols to child table cols */
88217  int regData,                    /* Referenced table data starts here */
88218  int nIncr                       /* Amount to increment deferred counter by */
88219){
88220  sqlite3 *db = pParse->db;       /* Database handle */
88221  int i;                          /* Iterator variable */
88222  Expr *pWhere = 0;               /* WHERE clause to scan with */
88223  NameContext sNameContext;       /* Context used to resolve WHERE clause */
88224  WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
88225  int iFkIfZero = 0;              /* Address of OP_FkIfZero */
88226  Vdbe *v = sqlite3GetVdbe(pParse);
88227
88228  assert( !pIdx || pIdx->pTable==pTab );
88229
88230  if( nIncr<0 ){
88231    iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
88232  }
88233
88234  /* Create an Expr object representing an SQL expression like:
88235  **
88236  **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
88237  **
88238  ** The collation sequence used for the comparison should be that of
88239  ** the parent key columns. The affinity of the parent key column should
88240  ** be applied to each child key value before the comparison takes place.
88241  */
88242  for(i=0; i<pFKey->nCol; i++){
88243    Expr *pLeft;                  /* Value from parent table row */
88244    Expr *pRight;                 /* Column ref to child table */
88245    Expr *pEq;                    /* Expression (pLeft = pRight) */
88246    int iCol;                     /* Index of column in child table */
88247    const char *zCol;             /* Name of column in child table */
88248
88249    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
88250    if( pLeft ){
88251      /* Set the collation sequence and affinity of the LHS of each TK_EQ
88252      ** expression to the parent key column defaults.  */
88253      if( pIdx ){
88254        Column *pCol;
88255        iCol = pIdx->aiColumn[i];
88256        pCol = &pTab->aCol[iCol];
88257        if( pTab->iPKey==iCol ) iCol = -1;
88258        pLeft->iTable = regData+iCol+1;
88259        pLeft->affinity = pCol->affinity;
88260        pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
88261      }else{
88262        pLeft->iTable = regData;
88263        pLeft->affinity = SQLITE_AFF_INTEGER;
88264      }
88265    }
88266    iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88267    assert( iCol>=0 );
88268    zCol = pFKey->pFrom->aCol[iCol].zName;
88269    pRight = sqlite3Expr(db, TK_ID, zCol);
88270    pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
88271    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88272  }
88273
88274  /* If the child table is the same as the parent table, and this scan
88275  ** is taking place as part of a DELETE operation (operation D.2), omit the
88276  ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
88277  ** clause, where $rowid is the rowid of the row being deleted.  */
88278  if( pTab==pFKey->pFrom && nIncr>0 ){
88279    Expr *pEq;                    /* Expression (pLeft = pRight) */
88280    Expr *pLeft;                  /* Value from parent table row */
88281    Expr *pRight;                 /* Column ref to child table */
88282    pLeft = sqlite3Expr(db, TK_REGISTER, 0);
88283    pRight = sqlite3Expr(db, TK_COLUMN, 0);
88284    if( pLeft && pRight ){
88285      pLeft->iTable = regData;
88286      pLeft->affinity = SQLITE_AFF_INTEGER;
88287      pRight->iTable = pSrc->a[0].iCursor;
88288      pRight->iColumn = -1;
88289    }
88290    pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
88291    pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88292  }
88293
88294  /* Resolve the references in the WHERE clause. */
88295  memset(&sNameContext, 0, sizeof(NameContext));
88296  sNameContext.pSrcList = pSrc;
88297  sNameContext.pParse = pParse;
88298  sqlite3ResolveExprNames(&sNameContext, pWhere);
88299
88300  /* Create VDBE to loop through the entries in pSrc that match the WHERE
88301  ** clause. If the constraint is not deferred, throw an exception for
88302  ** each row found. Otherwise, for deferred constraints, increment the
88303  ** deferred constraint counter by nIncr for each row selected.  */
88304  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0);
88305  if( nIncr>0 && pFKey->isDeferred==0 ){
88306    sqlite3ParseToplevel(pParse)->mayAbort = 1;
88307  }
88308  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
88309  if( pWInfo ){
88310    sqlite3WhereEnd(pWInfo);
88311  }
88312
88313  /* Clean up the WHERE clause constructed above. */
88314  sqlite3ExprDelete(db, pWhere);
88315  if( iFkIfZero ){
88316    sqlite3VdbeJumpHere(v, iFkIfZero);
88317  }
88318}
88319
88320/*
88321** This function returns a pointer to the head of a linked list of FK
88322** constraints for which table pTab is the parent table. For example,
88323** given the following schema:
88324**
88325**   CREATE TABLE t1(a PRIMARY KEY);
88326**   CREATE TABLE t2(b REFERENCES t1(a);
88327**
88328** Calling this function with table "t1" as an argument returns a pointer
88329** to the FKey structure representing the foreign key constraint on table
88330** "t2". Calling this function with "t2" as the argument would return a
88331** NULL pointer (as there are no FK constraints for which t2 is the parent
88332** table).
88333*/
88334SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
88335  int nName = sqlite3Strlen30(pTab->zName);
88336  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
88337}
88338
88339/*
88340** The second argument is a Trigger structure allocated by the
88341** fkActionTrigger() routine. This function deletes the Trigger structure
88342** and all of its sub-components.
88343**
88344** The Trigger structure or any of its sub-components may be allocated from
88345** the lookaside buffer belonging to database handle dbMem.
88346*/
88347static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
88348  if( p ){
88349    TriggerStep *pStep = p->step_list;
88350    sqlite3ExprDelete(dbMem, pStep->pWhere);
88351    sqlite3ExprListDelete(dbMem, pStep->pExprList);
88352    sqlite3SelectDelete(dbMem, pStep->pSelect);
88353    sqlite3ExprDelete(dbMem, p->pWhen);
88354    sqlite3DbFree(dbMem, p);
88355  }
88356}
88357
88358/*
88359** This function is called to generate code that runs when table pTab is
88360** being dropped from the database. The SrcList passed as the second argument
88361** to this function contains a single entry guaranteed to resolve to
88362** table pTab.
88363**
88364** Normally, no code is required. However, if either
88365**
88366**   (a) The table is the parent table of a FK constraint, or
88367**   (b) The table is the child table of a deferred FK constraint and it is
88368**       determined at runtime that there are outstanding deferred FK
88369**       constraint violations in the database,
88370**
88371** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
88372** the table from the database. Triggers are disabled while running this
88373** DELETE, but foreign key actions are not.
88374*/
88375SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
88376  sqlite3 *db = pParse->db;
88377  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
88378    int iSkip = 0;
88379    Vdbe *v = sqlite3GetVdbe(pParse);
88380
88381    assert( v );                  /* VDBE has already been allocated */
88382    if( sqlite3FkReferences(pTab)==0 ){
88383      /* Search for a deferred foreign key constraint for which this table
88384      ** is the child table. If one cannot be found, return without
88385      ** generating any VDBE code. If one can be found, then jump over
88386      ** the entire DELETE if there are no outstanding deferred constraints
88387      ** when this statement is run.  */
88388      FKey *p;
88389      for(p=pTab->pFKey; p; p=p->pNextFrom){
88390        if( p->isDeferred ) break;
88391      }
88392      if( !p ) return;
88393      iSkip = sqlite3VdbeMakeLabel(v);
88394      sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
88395    }
88396
88397    pParse->disableTriggers = 1;
88398    sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
88399    pParse->disableTriggers = 0;
88400
88401    /* If the DELETE has generated immediate foreign key constraint
88402    ** violations, halt the VDBE and return an error at this point, before
88403    ** any modifications to the schema are made. This is because statement
88404    ** transactions are not able to rollback schema changes.  */
88405    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
88406    sqlite3HaltConstraint(
88407        pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
88408    );
88409
88410    if( iSkip ){
88411      sqlite3VdbeResolveLabel(v, iSkip);
88412    }
88413  }
88414}
88415
88416/*
88417** This function is called when inserting, deleting or updating a row of
88418** table pTab to generate VDBE code to perform foreign key constraint
88419** processing for the operation.
88420**
88421** For a DELETE operation, parameter regOld is passed the index of the
88422** first register in an array of (pTab->nCol+1) registers containing the
88423** rowid of the row being deleted, followed by each of the column values
88424** of the row being deleted, from left to right. Parameter regNew is passed
88425** zero in this case.
88426**
88427** For an INSERT operation, regOld is passed zero and regNew is passed the
88428** first register of an array of (pTab->nCol+1) registers containing the new
88429** row data.
88430**
88431** For an UPDATE operation, this function is called twice. Once before
88432** the original record is deleted from the table using the calling convention
88433** described for DELETE. Then again after the original record is deleted
88434** but before the new record is inserted using the INSERT convention.
88435*/
88436SQLITE_PRIVATE void sqlite3FkCheck(
88437  Parse *pParse,                  /* Parse context */
88438  Table *pTab,                    /* Row is being deleted from this table */
88439  int regOld,                     /* Previous row data is stored here */
88440  int regNew                      /* New row data is stored here */
88441){
88442  sqlite3 *db = pParse->db;       /* Database handle */
88443  FKey *pFKey;                    /* Used to iterate through FKs */
88444  int iDb;                        /* Index of database containing pTab */
88445  const char *zDb;                /* Name of database containing pTab */
88446  int isIgnoreErrors = pParse->disableTriggers;
88447
88448  /* Exactly one of regOld and regNew should be non-zero. */
88449  assert( (regOld==0)!=(regNew==0) );
88450
88451  /* If foreign-keys are disabled, this function is a no-op. */
88452  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
88453
88454  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
88455  zDb = db->aDb[iDb].zName;
88456
88457  /* Loop through all the foreign key constraints for which pTab is the
88458  ** child table (the table that the foreign key definition is part of).  */
88459  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
88460    Table *pTo;                   /* Parent table of foreign key pFKey */
88461    Index *pIdx = 0;              /* Index on key columns in pTo */
88462    int *aiFree = 0;
88463    int *aiCol;
88464    int iCol;
88465    int i;
88466    int isIgnore = 0;
88467
88468    /* Find the parent table of this foreign key. Also find a unique index
88469    ** on the parent key columns in the parent table. If either of these
88470    ** schema items cannot be located, set an error in pParse and return
88471    ** early.  */
88472    if( pParse->disableTriggers ){
88473      pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
88474    }else{
88475      pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
88476    }
88477    if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
88478      assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
88479      if( !isIgnoreErrors || db->mallocFailed ) return;
88480      if( pTo==0 ){
88481        /* If isIgnoreErrors is true, then a table is being dropped. In this
88482        ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
88483        ** before actually dropping it in order to check FK constraints.
88484        ** If the parent table of an FK constraint on the current table is
88485        ** missing, behave as if it is empty. i.e. decrement the relevant
88486        ** FK counter for each row of the current table with non-NULL keys.
88487        */
88488        Vdbe *v = sqlite3GetVdbe(pParse);
88489        int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
88490        for(i=0; i<pFKey->nCol; i++){
88491          int iReg = pFKey->aCol[i].iFrom + regOld + 1;
88492          sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
88493        }
88494        sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
88495      }
88496      continue;
88497    }
88498    assert( pFKey->nCol==1 || (aiFree && pIdx) );
88499
88500    if( aiFree ){
88501      aiCol = aiFree;
88502    }else{
88503      iCol = pFKey->aCol[0].iFrom;
88504      aiCol = &iCol;
88505    }
88506    for(i=0; i<pFKey->nCol; i++){
88507      if( aiCol[i]==pTab->iPKey ){
88508        aiCol[i] = -1;
88509      }
88510#ifndef SQLITE_OMIT_AUTHORIZATION
88511      /* Request permission to read the parent key columns. If the
88512      ** authorization callback returns SQLITE_IGNORE, behave as if any
88513      ** values read from the parent table are NULL. */
88514      if( db->xAuth ){
88515        int rcauth;
88516        char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
88517        rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
88518        isIgnore = (rcauth==SQLITE_IGNORE);
88519      }
88520#endif
88521    }
88522
88523    /* Take a shared-cache advisory read-lock on the parent table. Allocate
88524    ** a cursor to use to search the unique index on the parent key columns
88525    ** in the parent table.  */
88526    sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
88527    pParse->nTab++;
88528
88529    if( regOld!=0 ){
88530      /* A row is being removed from the child table. Search for the parent.
88531      ** If the parent does not exist, removing the child row resolves an
88532      ** outstanding foreign key constraint violation. */
88533      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
88534    }
88535    if( regNew!=0 ){
88536      /* A row is being added to the child table. If a parent row cannot
88537      ** be found, adding the child row has violated the FK constraint. */
88538      fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
88539    }
88540
88541    sqlite3DbFree(db, aiFree);
88542  }
88543
88544  /* Loop through all the foreign key constraints that refer to this table */
88545  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88546    Index *pIdx = 0;              /* Foreign key index for pFKey */
88547    SrcList *pSrc;
88548    int *aiCol = 0;
88549
88550    if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
88551      assert( regOld==0 && regNew!=0 );
88552      /* Inserting a single row into a parent table cannot cause an immediate
88553      ** foreign key violation. So do nothing in this case.  */
88554      continue;
88555    }
88556
88557    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
88558      if( !isIgnoreErrors || db->mallocFailed ) return;
88559      continue;
88560    }
88561    assert( aiCol || pFKey->nCol==1 );
88562
88563    /* Create a SrcList structure containing a single table (the table
88564    ** the foreign key that refers to this table is attached to). This
88565    ** is required for the sqlite3WhereXXX() interface.  */
88566    pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
88567    if( pSrc ){
88568      struct SrcList_item *pItem = pSrc->a;
88569      pItem->pTab = pFKey->pFrom;
88570      pItem->zName = pFKey->pFrom->zName;
88571      pItem->pTab->nRef++;
88572      pItem->iCursor = pParse->nTab++;
88573
88574      if( regNew!=0 ){
88575        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
88576      }
88577      if( regOld!=0 ){
88578        /* If there is a RESTRICT action configured for the current operation
88579        ** on the parent table of this FK, then throw an exception
88580        ** immediately if the FK constraint is violated, even if this is a
88581        ** deferred trigger. That's what RESTRICT means. To defer checking
88582        ** the constraint, the FK should specify NO ACTION (represented
88583        ** using OE_None). NO ACTION is the default.  */
88584        fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
88585      }
88586      pItem->zName = 0;
88587      sqlite3SrcListDelete(db, pSrc);
88588    }
88589    sqlite3DbFree(db, aiCol);
88590  }
88591}
88592
88593#define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
88594
88595/*
88596** This function is called before generating code to update or delete a
88597** row contained in table pTab.
88598*/
88599SQLITE_PRIVATE u32 sqlite3FkOldmask(
88600  Parse *pParse,                  /* Parse context */
88601  Table *pTab                     /* Table being modified */
88602){
88603  u32 mask = 0;
88604  if( pParse->db->flags&SQLITE_ForeignKeys ){
88605    FKey *p;
88606    int i;
88607    for(p=pTab->pFKey; p; p=p->pNextFrom){
88608      for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
88609    }
88610    for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88611      Index *pIdx = 0;
88612      locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
88613      if( pIdx ){
88614        for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
88615      }
88616    }
88617  }
88618  return mask;
88619}
88620
88621/*
88622** This function is called before generating code to update or delete a
88623** row contained in table pTab. If the operation is a DELETE, then
88624** parameter aChange is passed a NULL value. For an UPDATE, aChange points
88625** to an array of size N, where N is the number of columns in table pTab.
88626** If the i'th column is not modified by the UPDATE, then the corresponding
88627** entry in the aChange[] array is set to -1. If the column is modified,
88628** the value is 0 or greater. Parameter chngRowid is set to true if the
88629** UPDATE statement modifies the rowid fields of the table.
88630**
88631** If any foreign key processing will be required, this function returns
88632** true. If there is no foreign key related processing, this function
88633** returns false.
88634*/
88635SQLITE_PRIVATE int sqlite3FkRequired(
88636  Parse *pParse,                  /* Parse context */
88637  Table *pTab,                    /* Table being modified */
88638  int *aChange,                   /* Non-NULL for UPDATE operations */
88639  int chngRowid                   /* True for UPDATE that affects rowid */
88640){
88641  if( pParse->db->flags&SQLITE_ForeignKeys ){
88642    if( !aChange ){
88643      /* A DELETE operation. Foreign key processing is required if the
88644      ** table in question is either the child or parent table for any
88645      ** foreign key constraint.  */
88646      return (sqlite3FkReferences(pTab) || pTab->pFKey);
88647    }else{
88648      /* This is an UPDATE. Foreign key processing is only required if the
88649      ** operation modifies one or more child or parent key columns. */
88650      int i;
88651      FKey *p;
88652
88653      /* Check if any child key columns are being modified. */
88654      for(p=pTab->pFKey; p; p=p->pNextFrom){
88655        for(i=0; i<p->nCol; i++){
88656          int iChildKey = p->aCol[i].iFrom;
88657          if( aChange[iChildKey]>=0 ) return 1;
88658          if( iChildKey==pTab->iPKey && chngRowid ) return 1;
88659        }
88660      }
88661
88662      /* Check if any parent key columns are being modified. */
88663      for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
88664        for(i=0; i<p->nCol; i++){
88665          char *zKey = p->aCol[i].zCol;
88666          int iKey;
88667          for(iKey=0; iKey<pTab->nCol; iKey++){
88668            Column *pCol = &pTab->aCol[iKey];
88669            if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
88670              if( aChange[iKey]>=0 ) return 1;
88671              if( iKey==pTab->iPKey && chngRowid ) return 1;
88672            }
88673          }
88674        }
88675      }
88676    }
88677  }
88678  return 0;
88679}
88680
88681/*
88682** This function is called when an UPDATE or DELETE operation is being
88683** compiled on table pTab, which is the parent table of foreign-key pFKey.
88684** If the current operation is an UPDATE, then the pChanges parameter is
88685** passed a pointer to the list of columns being modified. If it is a
88686** DELETE, pChanges is passed a NULL pointer.
88687**
88688** It returns a pointer to a Trigger structure containing a trigger
88689** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
88690** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
88691** returned (these actions require no special handling by the triggers
88692** sub-system, code for them is created by fkScanChildren()).
88693**
88694** For example, if pFKey is the foreign key and pTab is table "p" in
88695** the following schema:
88696**
88697**   CREATE TABLE p(pk PRIMARY KEY);
88698**   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
88699**
88700** then the returned trigger structure is equivalent to:
88701**
88702**   CREATE TRIGGER ... DELETE ON p BEGIN
88703**     DELETE FROM c WHERE ck = old.pk;
88704**   END;
88705**
88706** The returned pointer is cached as part of the foreign key object. It
88707** is eventually freed along with the rest of the foreign key object by
88708** sqlite3FkDelete().
88709*/
88710static Trigger *fkActionTrigger(
88711  Parse *pParse,                  /* Parse context */
88712  Table *pTab,                    /* Table being updated or deleted from */
88713  FKey *pFKey,                    /* Foreign key to get action for */
88714  ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
88715){
88716  sqlite3 *db = pParse->db;       /* Database handle */
88717  int action;                     /* One of OE_None, OE_Cascade etc. */
88718  Trigger *pTrigger;              /* Trigger definition to return */
88719  int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
88720
88721  action = pFKey->aAction[iAction];
88722  pTrigger = pFKey->apTrigger[iAction];
88723
88724  if( action!=OE_None && !pTrigger ){
88725    u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
88726    char const *zFrom;            /* Name of child table */
88727    int nFrom;                    /* Length in bytes of zFrom */
88728    Index *pIdx = 0;              /* Parent key index for this FK */
88729    int *aiCol = 0;               /* child table cols -> parent key cols */
88730    TriggerStep *pStep = 0;        /* First (only) step of trigger program */
88731    Expr *pWhere = 0;             /* WHERE clause of trigger step */
88732    ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
88733    Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
88734    int i;                        /* Iterator variable */
88735    Expr *pWhen = 0;              /* WHEN clause for the trigger */
88736
88737    if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
88738    assert( aiCol || pFKey->nCol==1 );
88739
88740    for(i=0; i<pFKey->nCol; i++){
88741      Token tOld = { "old", 3 };  /* Literal "old" token */
88742      Token tNew = { "new", 3 };  /* Literal "new" token */
88743      Token tFromCol;             /* Name of column in child table */
88744      Token tToCol;               /* Name of column in parent table */
88745      int iFromCol;               /* Idx of column in child table */
88746      Expr *pEq;                  /* tFromCol = OLD.tToCol */
88747
88748      iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
88749      assert( iFromCol>=0 );
88750      tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
88751      tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
88752
88753      tToCol.n = sqlite3Strlen30(tToCol.z);
88754      tFromCol.n = sqlite3Strlen30(tFromCol.z);
88755
88756      /* Create the expression "OLD.zToCol = zFromCol". It is important
88757      ** that the "OLD.zToCol" term is on the LHS of the = operator, so
88758      ** that the affinity and collation sequence associated with the
88759      ** parent table are used for the comparison. */
88760      pEq = sqlite3PExpr(pParse, TK_EQ,
88761          sqlite3PExpr(pParse, TK_DOT,
88762            sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88763            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88764          , 0),
88765          sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
88766      , 0);
88767      pWhere = sqlite3ExprAnd(db, pWhere, pEq);
88768
88769      /* For ON UPDATE, construct the next term of the WHEN clause.
88770      ** The final WHEN clause will be like this:
88771      **
88772      **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
88773      */
88774      if( pChanges ){
88775        pEq = sqlite3PExpr(pParse, TK_IS,
88776            sqlite3PExpr(pParse, TK_DOT,
88777              sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
88778              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88779              0),
88780            sqlite3PExpr(pParse, TK_DOT,
88781              sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88782              sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
88783              0),
88784            0);
88785        pWhen = sqlite3ExprAnd(db, pWhen, pEq);
88786      }
88787
88788      if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
88789        Expr *pNew;
88790        if( action==OE_Cascade ){
88791          pNew = sqlite3PExpr(pParse, TK_DOT,
88792            sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
88793            sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
88794          , 0);
88795        }else if( action==OE_SetDflt ){
88796          Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
88797          if( pDflt ){
88798            pNew = sqlite3ExprDup(db, pDflt, 0);
88799          }else{
88800            pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88801          }
88802        }else{
88803          pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
88804        }
88805        pList = sqlite3ExprListAppend(pParse, pList, pNew);
88806        sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
88807      }
88808    }
88809    sqlite3DbFree(db, aiCol);
88810
88811    zFrom = pFKey->pFrom->zName;
88812    nFrom = sqlite3Strlen30(zFrom);
88813
88814    if( action==OE_Restrict ){
88815      Token tFrom;
88816      Expr *pRaise;
88817
88818      tFrom.z = zFrom;
88819      tFrom.n = nFrom;
88820      pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
88821      if( pRaise ){
88822        pRaise->affinity = OE_Abort;
88823      }
88824      pSelect = sqlite3SelectNew(pParse,
88825          sqlite3ExprListAppend(pParse, 0, pRaise),
88826          sqlite3SrcListAppend(db, 0, &tFrom, 0),
88827          pWhere,
88828          0, 0, 0, 0, 0, 0
88829      );
88830      pWhere = 0;
88831    }
88832
88833    /* Disable lookaside memory allocation */
88834    enableLookaside = db->lookaside.bEnabled;
88835    db->lookaside.bEnabled = 0;
88836
88837    pTrigger = (Trigger *)sqlite3DbMallocZero(db,
88838        sizeof(Trigger) +         /* struct Trigger */
88839        sizeof(TriggerStep) +     /* Single step in trigger program */
88840        nFrom + 1                 /* Space for pStep->target.z */
88841    );
88842    if( pTrigger ){
88843      pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
88844      pStep->target.z = (char *)&pStep[1];
88845      pStep->target.n = nFrom;
88846      memcpy((char *)pStep->target.z, zFrom, nFrom);
88847
88848      pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
88849      pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
88850      pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
88851      if( pWhen ){
88852        pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
88853        pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
88854      }
88855    }
88856
88857    /* Re-enable the lookaside buffer, if it was disabled earlier. */
88858    db->lookaside.bEnabled = enableLookaside;
88859
88860    sqlite3ExprDelete(db, pWhere);
88861    sqlite3ExprDelete(db, pWhen);
88862    sqlite3ExprListDelete(db, pList);
88863    sqlite3SelectDelete(db, pSelect);
88864    if( db->mallocFailed==1 ){
88865      fkTriggerDelete(db, pTrigger);
88866      return 0;
88867    }
88868    assert( pStep!=0 );
88869
88870    switch( action ){
88871      case OE_Restrict:
88872        pStep->op = TK_SELECT;
88873        break;
88874      case OE_Cascade:
88875        if( !pChanges ){
88876          pStep->op = TK_DELETE;
88877          break;
88878        }
88879      default:
88880        pStep->op = TK_UPDATE;
88881    }
88882    pStep->pTrig = pTrigger;
88883    pTrigger->pSchema = pTab->pSchema;
88884    pTrigger->pTabSchema = pTab->pSchema;
88885    pFKey->apTrigger[iAction] = pTrigger;
88886    pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
88887  }
88888
88889  return pTrigger;
88890}
88891
88892/*
88893** This function is called when deleting or updating a row to implement
88894** any required CASCADE, SET NULL or SET DEFAULT actions.
88895*/
88896SQLITE_PRIVATE void sqlite3FkActions(
88897  Parse *pParse,                  /* Parse context */
88898  Table *pTab,                    /* Table being updated or deleted from */
88899  ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
88900  int regOld                      /* Address of array containing old row */
88901){
88902  /* If foreign-key support is enabled, iterate through all FKs that
88903  ** refer to table pTab. If there is an action associated with the FK
88904  ** for this operation (either update or delete), invoke the associated
88905  ** trigger sub-program.  */
88906  if( pParse->db->flags&SQLITE_ForeignKeys ){
88907    FKey *pFKey;                  /* Iterator variable */
88908    for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
88909      Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
88910      if( pAction ){
88911        sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
88912      }
88913    }
88914  }
88915}
88916
88917#endif /* ifndef SQLITE_OMIT_TRIGGER */
88918
88919/*
88920** Free all memory associated with foreign key definitions attached to
88921** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
88922** hash table.
88923*/
88924SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
88925  FKey *pFKey;                    /* Iterator variable */
88926  FKey *pNext;                    /* Copy of pFKey->pNextFrom */
88927
88928  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
88929  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
88930
88931    /* Remove the FK from the fkeyHash hash table. */
88932    if( !db || db->pnBytesFreed==0 ){
88933      if( pFKey->pPrevTo ){
88934        pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
88935      }else{
88936        void *p = (void *)pFKey->pNextTo;
88937        const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
88938        sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
88939      }
88940      if( pFKey->pNextTo ){
88941        pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
88942      }
88943    }
88944
88945    /* EV: R-30323-21917 Each foreign key constraint in SQLite is
88946    ** classified as either immediate or deferred.
88947    */
88948    assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
88949
88950    /* Delete any triggers created to implement actions for this FK. */
88951#ifndef SQLITE_OMIT_TRIGGER
88952    fkTriggerDelete(db, pFKey->apTrigger[0]);
88953    fkTriggerDelete(db, pFKey->apTrigger[1]);
88954#endif
88955
88956    pNext = pFKey->pNextFrom;
88957    sqlite3DbFree(db, pFKey);
88958  }
88959}
88960#endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
88961
88962/************** End of fkey.c ************************************************/
88963/************** Begin file insert.c ******************************************/
88964/*
88965** 2001 September 15
88966**
88967** The author disclaims copyright to this source code.  In place of
88968** a legal notice, here is a blessing:
88969**
88970**    May you do good and not evil.
88971**    May you find forgiveness for yourself and forgive others.
88972**    May you share freely, never taking more than you give.
88973**
88974*************************************************************************
88975** This file contains C code routines that are called by the parser
88976** to handle INSERT statements in SQLite.
88977*/
88978
88979/*
88980** Generate code that will open a table for reading.
88981*/
88982SQLITE_PRIVATE void sqlite3OpenTable(
88983  Parse *p,       /* Generate code into this VDBE */
88984  int iCur,       /* The cursor number of the table */
88985  int iDb,        /* The database index in sqlite3.aDb[] */
88986  Table *pTab,    /* The table to be opened */
88987  int opcode      /* OP_OpenRead or OP_OpenWrite */
88988){
88989  Vdbe *v;
88990  if( IsVirtual(pTab) ) return;
88991  v = sqlite3GetVdbe(p);
88992  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
88993  sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
88994  sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
88995  sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
88996  VdbeComment((v, "%s", pTab->zName));
88997}
88998
88999/*
89000** Return a pointer to the column affinity string associated with index
89001** pIdx. A column affinity string has one character for each column in
89002** the table, according to the affinity of the column:
89003**
89004**  Character      Column affinity
89005**  ------------------------------
89006**  'a'            TEXT
89007**  'b'            NONE
89008**  'c'            NUMERIC
89009**  'd'            INTEGER
89010**  'e'            REAL
89011**
89012** An extra 'd' is appended to the end of the string to cover the
89013** rowid that appears as the last column in every index.
89014**
89015** Memory for the buffer containing the column index affinity string
89016** is managed along with the rest of the Index structure. It will be
89017** released when sqlite3DeleteIndex() is called.
89018*/
89019SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
89020  if( !pIdx->zColAff ){
89021    /* The first time a column affinity string for a particular index is
89022    ** required, it is allocated and populated here. It is then stored as
89023    ** a member of the Index structure for subsequent use.
89024    **
89025    ** The column affinity string will eventually be deleted by
89026    ** sqliteDeleteIndex() when the Index structure itself is cleaned
89027    ** up.
89028    */
89029    int n;
89030    Table *pTab = pIdx->pTable;
89031    sqlite3 *db = sqlite3VdbeDb(v);
89032    pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
89033    if( !pIdx->zColAff ){
89034      db->mallocFailed = 1;
89035      return 0;
89036    }
89037    for(n=0; n<pIdx->nColumn; n++){
89038      pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
89039    }
89040    pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
89041    pIdx->zColAff[n] = 0;
89042  }
89043
89044  return pIdx->zColAff;
89045}
89046
89047/*
89048** Set P4 of the most recently inserted opcode to a column affinity
89049** string for table pTab. A column affinity string has one character
89050** for each column indexed by the index, according to the affinity of the
89051** column:
89052**
89053**  Character      Column affinity
89054**  ------------------------------
89055**  'a'            TEXT
89056**  'b'            NONE
89057**  'c'            NUMERIC
89058**  'd'            INTEGER
89059**  'e'            REAL
89060*/
89061SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
89062  /* The first time a column affinity string for a particular table
89063  ** is required, it is allocated and populated here. It is then
89064  ** stored as a member of the Table structure for subsequent use.
89065  **
89066  ** The column affinity string will eventually be deleted by
89067  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
89068  */
89069  if( !pTab->zColAff ){
89070    char *zColAff;
89071    int i;
89072    sqlite3 *db = sqlite3VdbeDb(v);
89073
89074    zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
89075    if( !zColAff ){
89076      db->mallocFailed = 1;
89077      return;
89078    }
89079
89080    for(i=0; i<pTab->nCol; i++){
89081      zColAff[i] = pTab->aCol[i].affinity;
89082    }
89083    zColAff[pTab->nCol] = '\0';
89084
89085    pTab->zColAff = zColAff;
89086  }
89087
89088  sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
89089}
89090
89091/*
89092** Return non-zero if the table pTab in database iDb or any of its indices
89093** have been opened at any point in the VDBE program beginning at location
89094** iStartAddr throught the end of the program.  This is used to see if
89095** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can
89096** run without using temporary table for the results of the SELECT.
89097*/
89098static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
89099  Vdbe *v = sqlite3GetVdbe(p);
89100  int i;
89101  int iEnd = sqlite3VdbeCurrentAddr(v);
89102#ifndef SQLITE_OMIT_VIRTUALTABLE
89103  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
89104#endif
89105
89106  for(i=iStartAddr; i<iEnd; i++){
89107    VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
89108    assert( pOp!=0 );
89109    if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
89110      Index *pIndex;
89111      int tnum = pOp->p2;
89112      if( tnum==pTab->tnum ){
89113        return 1;
89114      }
89115      for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
89116        if( tnum==pIndex->tnum ){
89117          return 1;
89118        }
89119      }
89120    }
89121#ifndef SQLITE_OMIT_VIRTUALTABLE
89122    if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
89123      assert( pOp->p4.pVtab!=0 );
89124      assert( pOp->p4type==P4_VTAB );
89125      return 1;
89126    }
89127#endif
89128  }
89129  return 0;
89130}
89131
89132#ifndef SQLITE_OMIT_AUTOINCREMENT
89133/*
89134** Locate or create an AutoincInfo structure associated with table pTab
89135** which is in database iDb.  Return the register number for the register
89136** that holds the maximum rowid.
89137**
89138** There is at most one AutoincInfo structure per table even if the
89139** same table is autoincremented multiple times due to inserts within
89140** triggers.  A new AutoincInfo structure is created if this is the
89141** first use of table pTab.  On 2nd and subsequent uses, the original
89142** AutoincInfo structure is used.
89143**
89144** Three memory locations are allocated:
89145**
89146**   (1)  Register to hold the name of the pTab table.
89147**   (2)  Register to hold the maximum ROWID of pTab.
89148**   (3)  Register to hold the rowid in sqlite_sequence of pTab
89149**
89150** The 2nd register is the one that is returned.  That is all the
89151** insert routine needs to know about.
89152*/
89153static int autoIncBegin(
89154  Parse *pParse,      /* Parsing context */
89155  int iDb,            /* Index of the database holding pTab */
89156  Table *pTab         /* The table we are writing to */
89157){
89158  int memId = 0;      /* Register holding maximum rowid */
89159  if( pTab->tabFlags & TF_Autoincrement ){
89160    Parse *pToplevel = sqlite3ParseToplevel(pParse);
89161    AutoincInfo *pInfo;
89162
89163    pInfo = pToplevel->pAinc;
89164    while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
89165    if( pInfo==0 ){
89166      pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
89167      if( pInfo==0 ) return 0;
89168      pInfo->pNext = pToplevel->pAinc;
89169      pToplevel->pAinc = pInfo;
89170      pInfo->pTab = pTab;
89171      pInfo->iDb = iDb;
89172      pToplevel->nMem++;                  /* Register to hold name of table */
89173      pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
89174      pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
89175    }
89176    memId = pInfo->regCtr;
89177  }
89178  return memId;
89179}
89180
89181/*
89182** This routine generates code that will initialize all of the
89183** register used by the autoincrement tracker.
89184*/
89185SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
89186  AutoincInfo *p;            /* Information about an AUTOINCREMENT */
89187  sqlite3 *db = pParse->db;  /* The database connection */
89188  Db *pDb;                   /* Database only autoinc table */
89189  int memId;                 /* Register holding max rowid */
89190  int addr;                  /* A VDBE address */
89191  Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
89192
89193  /* This routine is never called during trigger-generation.  It is
89194  ** only called from the top-level */
89195  assert( pParse->pTriggerTab==0 );
89196  assert( pParse==sqlite3ParseToplevel(pParse) );
89197
89198  assert( v );   /* We failed long ago if this is not so */
89199  for(p = pParse->pAinc; p; p = p->pNext){
89200    pDb = &db->aDb[p->iDb];
89201    memId = p->regCtr;
89202    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
89203    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
89204    sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
89205    addr = sqlite3VdbeCurrentAddr(v);
89206    sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
89207    sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
89208    sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
89209    sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
89210    sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
89211    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
89212    sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
89213    sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
89214    sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
89215    sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
89216    sqlite3VdbeAddOp0(v, OP_Close);
89217  }
89218}
89219
89220/*
89221** Update the maximum rowid for an autoincrement calculation.
89222**
89223** This routine should be called when the top of the stack holds a
89224** new rowid that is about to be inserted.  If that new rowid is
89225** larger than the maximum rowid in the memId memory cell, then the
89226** memory cell is updated.  The stack is unchanged.
89227*/
89228static void autoIncStep(Parse *pParse, int memId, int regRowid){
89229  if( memId>0 ){
89230    sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
89231  }
89232}
89233
89234/*
89235** This routine generates the code needed to write autoincrement
89236** maximum rowid values back into the sqlite_sequence register.
89237** Every statement that might do an INSERT into an autoincrement
89238** table (either directly or through triggers) needs to call this
89239** routine just before the "exit" code.
89240*/
89241SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
89242  AutoincInfo *p;
89243  Vdbe *v = pParse->pVdbe;
89244  sqlite3 *db = pParse->db;
89245
89246  assert( v );
89247  for(p = pParse->pAinc; p; p = p->pNext){
89248    Db *pDb = &db->aDb[p->iDb];
89249    int j1, j2, j3, j4, j5;
89250    int iRec;
89251    int memId = p->regCtr;
89252
89253    iRec = sqlite3GetTempReg(pParse);
89254    assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
89255    sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
89256    j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
89257    j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
89258    j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
89259    j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
89260    sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
89261    sqlite3VdbeJumpHere(v, j2);
89262    sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
89263    j5 = sqlite3VdbeAddOp0(v, OP_Goto);
89264    sqlite3VdbeJumpHere(v, j4);
89265    sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
89266    sqlite3VdbeJumpHere(v, j1);
89267    sqlite3VdbeJumpHere(v, j5);
89268    sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
89269    sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
89270    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
89271    sqlite3VdbeAddOp0(v, OP_Close);
89272    sqlite3ReleaseTempReg(pParse, iRec);
89273  }
89274}
89275#else
89276/*
89277** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
89278** above are all no-ops
89279*/
89280# define autoIncBegin(A,B,C) (0)
89281# define autoIncStep(A,B,C)
89282#endif /* SQLITE_OMIT_AUTOINCREMENT */
89283
89284
89285/* Forward declaration */
89286static int xferOptimization(
89287  Parse *pParse,        /* Parser context */
89288  Table *pDest,         /* The table we are inserting into */
89289  Select *pSelect,      /* A SELECT statement to use as the data source */
89290  int onError,          /* How to handle constraint errors */
89291  int iDbDest           /* The database of pDest */
89292);
89293
89294/*
89295** This routine is call to handle SQL of the following forms:
89296**
89297**    insert into TABLE (IDLIST) values(EXPRLIST)
89298**    insert into TABLE (IDLIST) select
89299**
89300** The IDLIST following the table name is always optional.  If omitted,
89301** then a list of all columns for the table is substituted.  The IDLIST
89302** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
89303**
89304** The pList parameter holds EXPRLIST in the first form of the INSERT
89305** statement above, and pSelect is NULL.  For the second form, pList is
89306** NULL and pSelect is a pointer to the select statement used to generate
89307** data for the insert.
89308**
89309** The code generated follows one of four templates.  For a simple
89310** select with data coming from a VALUES clause, the code executes
89311** once straight down through.  Pseudo-code follows (we call this
89312** the "1st template"):
89313**
89314**         open write cursor to <table> and its indices
89315**         puts VALUES clause expressions onto the stack
89316**         write the resulting record into <table>
89317**         cleanup
89318**
89319** The three remaining templates assume the statement is of the form
89320**
89321**   INSERT INTO <table> SELECT ...
89322**
89323** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
89324** in other words if the SELECT pulls all columns from a single table
89325** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
89326** if <table2> and <table1> are distinct tables but have identical
89327** schemas, including all the same indices, then a special optimization
89328** is invoked that copies raw records from <table2> over to <table1>.
89329** See the xferOptimization() function for the implementation of this
89330** template.  This is the 2nd template.
89331**
89332**         open a write cursor to <table>
89333**         open read cursor on <table2>
89334**         transfer all records in <table2> over to <table>
89335**         close cursors
89336**         foreach index on <table>
89337**           open a write cursor on the <table> index
89338**           open a read cursor on the corresponding <table2> index
89339**           transfer all records from the read to the write cursors
89340**           close cursors
89341**         end foreach
89342**
89343** The 3rd template is for when the second template does not apply
89344** and the SELECT clause does not read from <table> at any time.
89345** The generated code follows this template:
89346**
89347**         EOF <- 0
89348**         X <- A
89349**         goto B
89350**      A: setup for the SELECT
89351**         loop over the rows in the SELECT
89352**           load values into registers R..R+n
89353**           yield X
89354**         end loop
89355**         cleanup after the SELECT
89356**         EOF <- 1
89357**         yield X
89358**         goto A
89359**      B: open write cursor to <table> and its indices
89360**      C: yield X
89361**         if EOF goto D
89362**         insert the select result into <table> from R..R+n
89363**         goto C
89364**      D: cleanup
89365**
89366** The 4th template is used if the insert statement takes its
89367** values from a SELECT but the data is being inserted into a table
89368** that is also read as part of the SELECT.  In the third form,
89369** we have to use a intermediate table to store the results of
89370** the select.  The template is like this:
89371**
89372**         EOF <- 0
89373**         X <- A
89374**         goto B
89375**      A: setup for the SELECT
89376**         loop over the tables in the SELECT
89377**           load value into register R..R+n
89378**           yield X
89379**         end loop
89380**         cleanup after the SELECT
89381**         EOF <- 1
89382**         yield X
89383**         halt-error
89384**      B: open temp table
89385**      L: yield X
89386**         if EOF goto M
89387**         insert row from R..R+n into temp table
89388**         goto L
89389**      M: open write cursor to <table> and its indices
89390**         rewind temp table
89391**      C: loop over rows of intermediate table
89392**           transfer values form intermediate table into <table>
89393**         end loop
89394**      D: cleanup
89395*/
89396SQLITE_PRIVATE void sqlite3Insert(
89397  Parse *pParse,        /* Parser context */
89398  SrcList *pTabList,    /* Name of table into which we are inserting */
89399  ExprList *pList,      /* List of values to be inserted */
89400  Select *pSelect,      /* A SELECT statement to use as the data source */
89401  IdList *pColumn,      /* Column names corresponding to IDLIST. */
89402  int onError           /* How to handle constraint errors */
89403){
89404  sqlite3 *db;          /* The main database structure */
89405  Table *pTab;          /* The table to insert into.  aka TABLE */
89406  char *zTab;           /* Name of the table into which we are inserting */
89407  const char *zDb;      /* Name of the database holding this table */
89408  int i, j, idx;        /* Loop counters */
89409  Vdbe *v;              /* Generate code into this virtual machine */
89410  Index *pIdx;          /* For looping over indices of the table */
89411  int nColumn;          /* Number of columns in the data */
89412  int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
89413  int baseCur = 0;      /* VDBE Cursor number for pTab */
89414  int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
89415  int endOfLoop;        /* Label for the end of the insertion loop */
89416  int useTempTable = 0; /* Store SELECT results in intermediate table */
89417  int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
89418  int addrInsTop = 0;   /* Jump to label "D" */
89419  int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
89420  int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
89421  SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
89422  int iDb;              /* Index of database holding TABLE */
89423  Db *pDb;              /* The database containing table being inserted into */
89424  int appendFlag = 0;   /* True if the insert is likely to be an append */
89425
89426  /* Register allocations */
89427  int regFromSelect = 0;/* Base register for data coming from SELECT */
89428  int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
89429  int regRowCount = 0;  /* Memory cell used for the row counter */
89430  int regIns;           /* Block of regs holding rowid+data being inserted */
89431  int regRowid;         /* registers holding insert rowid */
89432  int regData;          /* register holding first column to insert */
89433  int regEof = 0;       /* Register recording end of SELECT data */
89434  int *aRegIdx = 0;     /* One register allocated to each index */
89435
89436#ifndef SQLITE_OMIT_TRIGGER
89437  int isView;                 /* True if attempting to insert into a view */
89438  Trigger *pTrigger;          /* List of triggers on pTab, if required */
89439  int tmask;                  /* Mask of trigger times */
89440#endif
89441
89442  db = pParse->db;
89443  memset(&dest, 0, sizeof(dest));
89444  if( pParse->nErr || db->mallocFailed ){
89445    goto insert_cleanup;
89446  }
89447
89448  /* Locate the table into which we will be inserting new information.
89449  */
89450  assert( pTabList->nSrc==1 );
89451  zTab = pTabList->a[0].zName;
89452  if( NEVER(zTab==0) ) goto insert_cleanup;
89453  pTab = sqlite3SrcListLookup(pParse, pTabList);
89454  if( pTab==0 ){
89455    goto insert_cleanup;
89456  }
89457  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89458  assert( iDb<db->nDb );
89459  pDb = &db->aDb[iDb];
89460  zDb = pDb->zName;
89461  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
89462    goto insert_cleanup;
89463  }
89464
89465  /* Figure out if we have any triggers and if the table being
89466  ** inserted into is a view
89467  */
89468#ifndef SQLITE_OMIT_TRIGGER
89469  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
89470  isView = pTab->pSelect!=0;
89471#else
89472# define pTrigger 0
89473# define tmask 0
89474# define isView 0
89475#endif
89476#ifdef SQLITE_OMIT_VIEW
89477# undef isView
89478# define isView 0
89479#endif
89480  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
89481
89482  /* If pTab is really a view, make sure it has been initialized.
89483  ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
89484  ** module table).
89485  */
89486  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
89487    goto insert_cleanup;
89488  }
89489
89490  /* Ensure that:
89491  *  (a) the table is not read-only,
89492  *  (b) that if it is a view then ON INSERT triggers exist
89493  */
89494  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
89495    goto insert_cleanup;
89496  }
89497
89498  /* Allocate a VDBE
89499  */
89500  v = sqlite3GetVdbe(pParse);
89501  if( v==0 ) goto insert_cleanup;
89502  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
89503  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
89504
89505#ifndef SQLITE_OMIT_XFER_OPT
89506  /* If the statement is of the form
89507  **
89508  **       INSERT INTO <table1> SELECT * FROM <table2>;
89509  **
89510  ** Then special optimizations can be applied that make the transfer
89511  ** very fast and which reduce fragmentation of indices.
89512  **
89513  ** This is the 2nd template.
89514  */
89515  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
89516    assert( !pTrigger );
89517    assert( pList==0 );
89518    goto insert_end;
89519  }
89520#endif /* SQLITE_OMIT_XFER_OPT */
89521
89522  /* If this is an AUTOINCREMENT table, look up the sequence number in the
89523  ** sqlite_sequence table and store it in memory cell regAutoinc.
89524  */
89525  regAutoinc = autoIncBegin(pParse, iDb, pTab);
89526
89527  /* Figure out how many columns of data are supplied.  If the data
89528  ** is coming from a SELECT statement, then generate a co-routine that
89529  ** produces a single row of the SELECT on each invocation.  The
89530  ** co-routine is the common header to the 3rd and 4th templates.
89531  */
89532  if( pSelect ){
89533    /* Data is coming from a SELECT.  Generate code to implement that SELECT
89534    ** as a co-routine.  The code is common to both the 3rd and 4th
89535    ** templates:
89536    **
89537    **         EOF <- 0
89538    **         X <- A
89539    **         goto B
89540    **      A: setup for the SELECT
89541    **         loop over the tables in the SELECT
89542    **           load value into register R..R+n
89543    **           yield X
89544    **         end loop
89545    **         cleanup after the SELECT
89546    **         EOF <- 1
89547    **         yield X
89548    **         halt-error
89549    **
89550    ** On each invocation of the co-routine, it puts a single row of the
89551    ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
89552    ** (These output registers are allocated by sqlite3Select().)  When
89553    ** the SELECT completes, it sets the EOF flag stored in regEof.
89554    */
89555    int rc, j1;
89556
89557    regEof = ++pParse->nMem;
89558    sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
89559    VdbeComment((v, "SELECT eof flag"));
89560    sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
89561    addrSelect = sqlite3VdbeCurrentAddr(v)+2;
89562    sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
89563    j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
89564    VdbeComment((v, "Jump over SELECT coroutine"));
89565
89566    /* Resolve the expressions in the SELECT statement and execute it. */
89567    rc = sqlite3Select(pParse, pSelect, &dest);
89568    assert( pParse->nErr==0 || rc );
89569    if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
89570      goto insert_cleanup;
89571    }
89572    sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
89573    sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
89574    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
89575    VdbeComment((v, "End of SELECT coroutine"));
89576    sqlite3VdbeJumpHere(v, j1);                          /* label B: */
89577
89578    regFromSelect = dest.iMem;
89579    assert( pSelect->pEList );
89580    nColumn = pSelect->pEList->nExpr;
89581    assert( dest.nMem==nColumn );
89582
89583    /* Set useTempTable to TRUE if the result of the SELECT statement
89584    ** should be written into a temporary table (template 4).  Set to
89585    ** FALSE if each* row of the SELECT can be written directly into
89586    ** the destination table (template 3).
89587    **
89588    ** A temp table must be used if the table being updated is also one
89589    ** of the tables being read by the SELECT statement.  Also use a
89590    ** temp table in the case of row triggers.
89591    */
89592    if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
89593      useTempTable = 1;
89594    }
89595
89596    if( useTempTable ){
89597      /* Invoke the coroutine to extract information from the SELECT
89598      ** and add it to a transient table srcTab.  The code generated
89599      ** here is from the 4th template:
89600      **
89601      **      B: open temp table
89602      **      L: yield X
89603      **         if EOF goto M
89604      **         insert row from R..R+n into temp table
89605      **         goto L
89606      **      M: ...
89607      */
89608      int regRec;          /* Register to hold packed record */
89609      int regTempRowid;    /* Register to hold temp table ROWID */
89610      int addrTop;         /* Label "L" */
89611      int addrIf;          /* Address of jump to M */
89612
89613      srcTab = pParse->nTab++;
89614      regRec = sqlite3GetTempReg(pParse);
89615      regTempRowid = sqlite3GetTempReg(pParse);
89616      sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
89617      addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
89618      addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
89619      sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
89620      sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
89621      sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
89622      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
89623      sqlite3VdbeJumpHere(v, addrIf);
89624      sqlite3ReleaseTempReg(pParse, regRec);
89625      sqlite3ReleaseTempReg(pParse, regTempRowid);
89626    }
89627  }else{
89628    /* This is the case if the data for the INSERT is coming from a VALUES
89629    ** clause
89630    */
89631    NameContext sNC;
89632    memset(&sNC, 0, sizeof(sNC));
89633    sNC.pParse = pParse;
89634    srcTab = -1;
89635    assert( useTempTable==0 );
89636    nColumn = pList ? pList->nExpr : 0;
89637    for(i=0; i<nColumn; i++){
89638      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
89639        goto insert_cleanup;
89640      }
89641    }
89642  }
89643
89644  /* Make sure the number of columns in the source data matches the number
89645  ** of columns to be inserted into the table.
89646  */
89647  if( IsVirtual(pTab) ){
89648    for(i=0; i<pTab->nCol; i++){
89649      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
89650    }
89651  }
89652  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
89653    sqlite3ErrorMsg(pParse,
89654       "table %S has %d columns but %d values were supplied",
89655       pTabList, 0, pTab->nCol-nHidden, nColumn);
89656    goto insert_cleanup;
89657  }
89658  if( pColumn!=0 && nColumn!=pColumn->nId ){
89659    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
89660    goto insert_cleanup;
89661  }
89662
89663  /* If the INSERT statement included an IDLIST term, then make sure
89664  ** all elements of the IDLIST really are columns of the table and
89665  ** remember the column indices.
89666  **
89667  ** If the table has an INTEGER PRIMARY KEY column and that column
89668  ** is named in the IDLIST, then record in the keyColumn variable
89669  ** the index into IDLIST of the primary key column.  keyColumn is
89670  ** the index of the primary key as it appears in IDLIST, not as
89671  ** is appears in the original table.  (The index of the primary
89672  ** key in the original table is pTab->iPKey.)
89673  */
89674  if( pColumn ){
89675    for(i=0; i<pColumn->nId; i++){
89676      pColumn->a[i].idx = -1;
89677    }
89678    for(i=0; i<pColumn->nId; i++){
89679      for(j=0; j<pTab->nCol; j++){
89680        if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
89681          pColumn->a[i].idx = j;
89682          if( j==pTab->iPKey ){
89683            keyColumn = i;
89684          }
89685          break;
89686        }
89687      }
89688      if( j>=pTab->nCol ){
89689        if( sqlite3IsRowid(pColumn->a[i].zName) ){
89690          keyColumn = i;
89691        }else{
89692          sqlite3ErrorMsg(pParse, "table %S has no column named %s",
89693              pTabList, 0, pColumn->a[i].zName);
89694          pParse->checkSchema = 1;
89695          goto insert_cleanup;
89696        }
89697      }
89698    }
89699  }
89700
89701  /* If there is no IDLIST term but the table has an integer primary
89702  ** key, the set the keyColumn variable to the primary key column index
89703  ** in the original table definition.
89704  */
89705  if( pColumn==0 && nColumn>0 ){
89706    keyColumn = pTab->iPKey;
89707  }
89708
89709  /* Initialize the count of rows to be inserted
89710  */
89711  if( db->flags & SQLITE_CountRows ){
89712    regRowCount = ++pParse->nMem;
89713    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
89714  }
89715
89716  /* If this is not a view, open the table and and all indices */
89717  if( !isView ){
89718    int nIdx;
89719
89720    baseCur = pParse->nTab;
89721    nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
89722    aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
89723    if( aRegIdx==0 ){
89724      goto insert_cleanup;
89725    }
89726    for(i=0; i<nIdx; i++){
89727      aRegIdx[i] = ++pParse->nMem;
89728    }
89729  }
89730
89731  /* This is the top of the main insertion loop */
89732  if( useTempTable ){
89733    /* This block codes the top of loop only.  The complete loop is the
89734    ** following pseudocode (template 4):
89735    **
89736    **         rewind temp table
89737    **      C: loop over rows of intermediate table
89738    **           transfer values form intermediate table into <table>
89739    **         end loop
89740    **      D: ...
89741    */
89742    addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
89743    addrCont = sqlite3VdbeCurrentAddr(v);
89744  }else if( pSelect ){
89745    /* This block codes the top of loop only.  The complete loop is the
89746    ** following pseudocode (template 3):
89747    **
89748    **      C: yield X
89749    **         if EOF goto D
89750    **         insert the select result into <table> from R..R+n
89751    **         goto C
89752    **      D: ...
89753    */
89754    addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
89755    addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
89756  }
89757
89758  /* Allocate registers for holding the rowid of the new row,
89759  ** the content of the new row, and the assemblied row record.
89760  */
89761  regRowid = regIns = pParse->nMem+1;
89762  pParse->nMem += pTab->nCol + 1;
89763  if( IsVirtual(pTab) ){
89764    regRowid++;
89765    pParse->nMem++;
89766  }
89767  regData = regRowid+1;
89768
89769  /* Run the BEFORE and INSTEAD OF triggers, if there are any
89770  */
89771  endOfLoop = sqlite3VdbeMakeLabel(v);
89772  if( tmask & TRIGGER_BEFORE ){
89773    int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
89774
89775    /* build the NEW.* reference row.  Note that if there is an INTEGER
89776    ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
89777    ** translated into a unique ID for the row.  But on a BEFORE trigger,
89778    ** we do not know what the unique ID will be (because the insert has
89779    ** not happened yet) so we substitute a rowid of -1
89780    */
89781    if( keyColumn<0 ){
89782      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89783    }else{
89784      int j1;
89785      if( useTempTable ){
89786        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
89787      }else{
89788        assert( pSelect==0 );  /* Otherwise useTempTable is true */
89789        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
89790      }
89791      j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
89792      sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
89793      sqlite3VdbeJumpHere(v, j1);
89794      sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
89795    }
89796
89797    /* Cannot have triggers on a virtual table. If it were possible,
89798    ** this block would have to account for hidden column.
89799    */
89800    assert( !IsVirtual(pTab) );
89801
89802    /* Create the new column data
89803    */
89804    for(i=0; i<pTab->nCol; i++){
89805      if( pColumn==0 ){
89806        j = i;
89807      }else{
89808        for(j=0; j<pColumn->nId; j++){
89809          if( pColumn->a[j].idx==i ) break;
89810        }
89811      }
89812      if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
89813        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
89814      }else if( useTempTable ){
89815        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
89816      }else{
89817        assert( pSelect==0 ); /* Otherwise useTempTable is true */
89818        sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
89819      }
89820    }
89821
89822    /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
89823    ** do not attempt any conversions before assembling the record.
89824    ** If this is a real table, attempt conversions as required by the
89825    ** table column affinities.
89826    */
89827    if( !isView ){
89828      sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
89829      sqlite3TableAffinityStr(v, pTab);
89830    }
89831
89832    /* Fire BEFORE or INSTEAD OF triggers */
89833    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
89834        pTab, regCols-pTab->nCol-1, onError, endOfLoop);
89835
89836    sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
89837  }
89838
89839  /* Push the record number for the new entry onto the stack.  The
89840  ** record number is a randomly generate integer created by NewRowid
89841  ** except when the table has an INTEGER PRIMARY KEY column, in which
89842  ** case the record number is the same as that column.
89843  */
89844  if( !isView ){
89845    if( IsVirtual(pTab) ){
89846      /* The row that the VUpdate opcode will delete: none */
89847      sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
89848    }
89849    if( keyColumn>=0 ){
89850      if( useTempTable ){
89851        sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
89852      }else if( pSelect ){
89853        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
89854      }else{
89855        VdbeOp *pOp;
89856        sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
89857        pOp = sqlite3VdbeGetOp(v, -1);
89858        if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
89859          appendFlag = 1;
89860          pOp->opcode = OP_NewRowid;
89861          pOp->p1 = baseCur;
89862          pOp->p2 = regRowid;
89863          pOp->p3 = regAutoinc;
89864        }
89865      }
89866      /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
89867      ** to generate a unique primary key value.
89868      */
89869      if( !appendFlag ){
89870        int j1;
89871        if( !IsVirtual(pTab) ){
89872          j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
89873          sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89874          sqlite3VdbeJumpHere(v, j1);
89875        }else{
89876          j1 = sqlite3VdbeCurrentAddr(v);
89877          sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
89878        }
89879        sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
89880      }
89881    }else if( IsVirtual(pTab) ){
89882      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
89883    }else{
89884      sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
89885      appendFlag = 1;
89886    }
89887    autoIncStep(pParse, regAutoinc, regRowid);
89888
89889    /* Push onto the stack, data for all columns of the new entry, beginning
89890    ** with the first column.
89891    */
89892    nHidden = 0;
89893    for(i=0; i<pTab->nCol; i++){
89894      int iRegStore = regRowid+1+i;
89895      if( i==pTab->iPKey ){
89896        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
89897        ** Whenever this column is read, the record number will be substituted
89898        ** in its place.  So will fill this column with a NULL to avoid
89899        ** taking up data space with information that will never be used. */
89900        sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
89901        continue;
89902      }
89903      if( pColumn==0 ){
89904        if( IsHiddenColumn(&pTab->aCol[i]) ){
89905          assert( IsVirtual(pTab) );
89906          j = -1;
89907          nHidden++;
89908        }else{
89909          j = i - nHidden;
89910        }
89911      }else{
89912        for(j=0; j<pColumn->nId; j++){
89913          if( pColumn->a[j].idx==i ) break;
89914        }
89915      }
89916      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
89917        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
89918      }else if( useTempTable ){
89919        sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
89920      }else if( pSelect ){
89921        sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
89922      }else{
89923        sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
89924      }
89925    }
89926
89927    /* Generate code to check constraints and generate index keys and
89928    ** do the insertion.
89929    */
89930#ifndef SQLITE_OMIT_VIRTUALTABLE
89931    if( IsVirtual(pTab) ){
89932      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
89933      sqlite3VtabMakeWritable(pParse, pTab);
89934      sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
89935      sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
89936      sqlite3MayAbort(pParse);
89937    }else
89938#endif
89939    {
89940      int isReplace;    /* Set to true if constraints may cause a replace */
89941      sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
89942          keyColumn>=0, 0, onError, endOfLoop, &isReplace
89943      );
89944      sqlite3FkCheck(pParse, pTab, 0, regIns);
89945      sqlite3CompleteInsertion(
89946          pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
89947      );
89948    }
89949  }
89950
89951  /* Update the count of rows that are inserted
89952  */
89953  if( (db->flags & SQLITE_CountRows)!=0 ){
89954    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
89955  }
89956
89957  if( pTrigger ){
89958    /* Code AFTER triggers */
89959    sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
89960        pTab, regData-2-pTab->nCol, onError, endOfLoop);
89961  }
89962
89963  /* The bottom of the main insertion loop, if the data source
89964  ** is a SELECT statement.
89965  */
89966  sqlite3VdbeResolveLabel(v, endOfLoop);
89967  if( useTempTable ){
89968    sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
89969    sqlite3VdbeJumpHere(v, addrInsTop);
89970    sqlite3VdbeAddOp1(v, OP_Close, srcTab);
89971  }else if( pSelect ){
89972    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
89973    sqlite3VdbeJumpHere(v, addrInsTop);
89974  }
89975
89976  if( !IsVirtual(pTab) && !isView ){
89977    /* Close all tables opened */
89978    sqlite3VdbeAddOp1(v, OP_Close, baseCur);
89979    for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
89980      sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
89981    }
89982  }
89983
89984insert_end:
89985  /* Update the sqlite_sequence table by storing the content of the
89986  ** maximum rowid counter values recorded while inserting into
89987  ** autoincrement tables.
89988  */
89989  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
89990    sqlite3AutoincrementEnd(pParse);
89991  }
89992
89993  /*
89994  ** Return the number of rows inserted. If this routine is
89995  ** generating code because of a call to sqlite3NestedParse(), do not
89996  ** invoke the callback function.
89997  */
89998  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
89999    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
90000    sqlite3VdbeSetNumCols(v, 1);
90001    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
90002  }
90003
90004insert_cleanup:
90005  sqlite3SrcListDelete(db, pTabList);
90006  sqlite3ExprListDelete(db, pList);
90007  sqlite3SelectDelete(db, pSelect);
90008  sqlite3IdListDelete(db, pColumn);
90009  sqlite3DbFree(db, aRegIdx);
90010}
90011
90012/* Make sure "isView" and other macros defined above are undefined. Otherwise
90013** thely may interfere with compilation of other functions in this file
90014** (or in another file, if this file becomes part of the amalgamation).  */
90015#ifdef isView
90016 #undef isView
90017#endif
90018#ifdef pTrigger
90019 #undef pTrigger
90020#endif
90021#ifdef tmask
90022 #undef tmask
90023#endif
90024
90025
90026/*
90027** Generate code to do constraint checks prior to an INSERT or an UPDATE.
90028**
90029** The input is a range of consecutive registers as follows:
90030**
90031**    1.  The rowid of the row after the update.
90032**
90033**    2.  The data in the first column of the entry after the update.
90034**
90035**    i.  Data from middle columns...
90036**
90037**    N.  The data in the last column of the entry after the update.
90038**
90039** The regRowid parameter is the index of the register containing (1).
90040**
90041** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
90042** the address of a register containing the rowid before the update takes
90043** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
90044** is false, indicating an INSERT statement, then a non-zero rowidChng
90045** indicates that the rowid was explicitly specified as part of the
90046** INSERT statement. If rowidChng is false, it means that  the rowid is
90047** computed automatically in an insert or that the rowid value is not
90048** modified by an update.
90049**
90050** The code generated by this routine store new index entries into
90051** registers identified by aRegIdx[].  No index entry is created for
90052** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
90053** the same as the order of indices on the linked list of indices
90054** attached to the table.
90055**
90056** This routine also generates code to check constraints.  NOT NULL,
90057** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
90058** then the appropriate action is performed.  There are five possible
90059** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
90060**
90061**  Constraint type  Action       What Happens
90062**  ---------------  ----------   ----------------------------------------
90063**  any              ROLLBACK     The current transaction is rolled back and
90064**                                sqlite3_exec() returns immediately with a
90065**                                return code of SQLITE_CONSTRAINT.
90066**
90067**  any              ABORT        Back out changes from the current command
90068**                                only (do not do a complete rollback) then
90069**                                cause sqlite3_exec() to return immediately
90070**                                with SQLITE_CONSTRAINT.
90071**
90072**  any              FAIL         Sqlite3_exec() returns immediately with a
90073**                                return code of SQLITE_CONSTRAINT.  The
90074**                                transaction is not rolled back and any
90075**                                prior changes are retained.
90076**
90077**  any              IGNORE       The record number and data is popped from
90078**                                the stack and there is an immediate jump
90079**                                to label ignoreDest.
90080**
90081**  NOT NULL         REPLACE      The NULL value is replace by the default
90082**                                value for that column.  If the default value
90083**                                is NULL, the action is the same as ABORT.
90084**
90085**  UNIQUE           REPLACE      The other row that conflicts with the row
90086**                                being inserted is removed.
90087**
90088**  CHECK            REPLACE      Illegal.  The results in an exception.
90089**
90090** Which action to take is determined by the overrideError parameter.
90091** Or if overrideError==OE_Default, then the pParse->onError parameter
90092** is used.  Or if pParse->onError==OE_Default then the onError value
90093** for the constraint is used.
90094**
90095** The calling routine must open a read/write cursor for pTab with
90096** cursor number "baseCur".  All indices of pTab must also have open
90097** read/write cursors with cursor number baseCur+i for the i-th cursor.
90098** Except, if there is no possibility of a REPLACE action then
90099** cursors do not need to be open for indices where aRegIdx[i]==0.
90100*/
90101SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
90102  Parse *pParse,      /* The parser context */
90103  Table *pTab,        /* the table into which we are inserting */
90104  int baseCur,        /* Index of a read/write cursor pointing at pTab */
90105  int regRowid,       /* Index of the range of input registers */
90106  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90107  int rowidChng,      /* True if the rowid might collide with existing entry */
90108  int isUpdate,       /* True for UPDATE, False for INSERT */
90109  int overrideError,  /* Override onError to this if not OE_Default */
90110  int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
90111  int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
90112){
90113  int i;              /* loop counter */
90114  Vdbe *v;            /* VDBE under constrution */
90115  int nCol;           /* Number of columns */
90116  int onError;        /* Conflict resolution strategy */
90117  int j1;             /* Addresss of jump instruction */
90118  int j2 = 0, j3;     /* Addresses of jump instructions */
90119  int regData;        /* Register containing first data column */
90120  int iCur;           /* Table cursor number */
90121  Index *pIdx;         /* Pointer to one of the indices */
90122  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
90123  int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
90124
90125  v = sqlite3GetVdbe(pParse);
90126  assert( v!=0 );
90127  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90128  nCol = pTab->nCol;
90129  regData = regRowid + 1;
90130
90131  /* Test all NOT NULL constraints.
90132  */
90133  for(i=0; i<nCol; i++){
90134    if( i==pTab->iPKey ){
90135      continue;
90136    }
90137    onError = pTab->aCol[i].notNull;
90138    if( onError==OE_None ) continue;
90139    if( overrideError!=OE_Default ){
90140      onError = overrideError;
90141    }else if( onError==OE_Default ){
90142      onError = OE_Abort;
90143    }
90144    if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
90145      onError = OE_Abort;
90146    }
90147    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90148        || onError==OE_Ignore || onError==OE_Replace );
90149    switch( onError ){
90150      case OE_Abort:
90151        sqlite3MayAbort(pParse);
90152      case OE_Rollback:
90153      case OE_Fail: {
90154        char *zMsg;
90155        sqlite3VdbeAddOp3(v, OP_HaltIfNull,
90156                                  SQLITE_CONSTRAINT, onError, regData+i);
90157        zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
90158                              pTab->zName, pTab->aCol[i].zName);
90159        sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
90160        break;
90161      }
90162      case OE_Ignore: {
90163        sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
90164        break;
90165      }
90166      default: {
90167        assert( onError==OE_Replace );
90168        j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
90169        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
90170        sqlite3VdbeJumpHere(v, j1);
90171        break;
90172      }
90173    }
90174  }
90175
90176  /* Test all CHECK constraints
90177  */
90178#ifndef SQLITE_OMIT_CHECK
90179  if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
90180    int allOk = sqlite3VdbeMakeLabel(v);
90181    pParse->ckBase = regData;
90182    sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
90183    onError = overrideError!=OE_Default ? overrideError : OE_Abort;
90184    if( onError==OE_Ignore ){
90185      sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90186    }else{
90187      if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
90188      sqlite3HaltConstraint(pParse, onError, 0, 0);
90189    }
90190    sqlite3VdbeResolveLabel(v, allOk);
90191  }
90192#endif /* !defined(SQLITE_OMIT_CHECK) */
90193
90194  /* If we have an INTEGER PRIMARY KEY, make sure the primary key
90195  ** of the new record does not previously exist.  Except, if this
90196  ** is an UPDATE and the primary key is not changing, that is OK.
90197  */
90198  if( rowidChng ){
90199    onError = pTab->keyConf;
90200    if( overrideError!=OE_Default ){
90201      onError = overrideError;
90202    }else if( onError==OE_Default ){
90203      onError = OE_Abort;
90204    }
90205
90206    if( isUpdate ){
90207      j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
90208    }
90209    j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
90210    switch( onError ){
90211      default: {
90212        onError = OE_Abort;
90213        /* Fall thru into the next case */
90214      }
90215      case OE_Rollback:
90216      case OE_Abort:
90217      case OE_Fail: {
90218        sqlite3HaltConstraint(
90219          pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
90220        break;
90221      }
90222      case OE_Replace: {
90223        /* If there are DELETE triggers on this table and the
90224        ** recursive-triggers flag is set, call GenerateRowDelete() to
90225        ** remove the conflicting row from the the table. This will fire
90226        ** the triggers and remove both the table and index b-tree entries.
90227        **
90228        ** Otherwise, if there are no triggers or the recursive-triggers
90229        ** flag is not set, but the table has one or more indexes, call
90230        ** GenerateRowIndexDelete(). This removes the index b-tree entries
90231        ** only. The table b-tree entry will be replaced by the new entry
90232        ** when it is inserted.
90233        **
90234        ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
90235        ** also invoke MultiWrite() to indicate that this VDBE may require
90236        ** statement rollback (if the statement is aborted after the delete
90237        ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
90238        ** but being more selective here allows statements like:
90239        **
90240        **   REPLACE INTO t(rowid) VALUES($newrowid)
90241        **
90242        ** to run without a statement journal if there are no indexes on the
90243        ** table.
90244        */
90245        Trigger *pTrigger = 0;
90246        if( pParse->db->flags&SQLITE_RecTriggers ){
90247          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90248        }
90249        if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
90250          sqlite3MultiWrite(pParse);
90251          sqlite3GenerateRowDelete(
90252              pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
90253          );
90254        }else if( pTab->pIndex ){
90255          sqlite3MultiWrite(pParse);
90256          sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
90257        }
90258        seenReplace = 1;
90259        break;
90260      }
90261      case OE_Ignore: {
90262        assert( seenReplace==0 );
90263        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90264        break;
90265      }
90266    }
90267    sqlite3VdbeJumpHere(v, j3);
90268    if( isUpdate ){
90269      sqlite3VdbeJumpHere(v, j2);
90270    }
90271  }
90272
90273  /* Test all UNIQUE constraints by creating entries for each UNIQUE
90274  ** index and making sure that duplicate entries do not already exist.
90275  ** Add the new records to the indices as we go.
90276  */
90277  for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
90278    int regIdx;
90279    int regR;
90280
90281    if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
90282
90283    /* Create a key for accessing the index entry */
90284    regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
90285    for(i=0; i<pIdx->nColumn; i++){
90286      int idx = pIdx->aiColumn[i];
90287      if( idx==pTab->iPKey ){
90288        sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90289      }else{
90290        sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
90291      }
90292    }
90293    sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
90294    sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
90295    sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
90296    sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
90297
90298    /* Find out what action to take in case there is an indexing conflict */
90299    onError = pIdx->onError;
90300    if( onError==OE_None ){
90301      sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90302      continue;  /* pIdx is not a UNIQUE index */
90303    }
90304    if( overrideError!=OE_Default ){
90305      onError = overrideError;
90306    }else if( onError==OE_Default ){
90307      onError = OE_Abort;
90308    }
90309    if( seenReplace ){
90310      if( onError==OE_Ignore ) onError = OE_Replace;
90311      else if( onError==OE_Fail ) onError = OE_Abort;
90312    }
90313
90314    /* Check to see if the new index entry will be unique */
90315    regR = sqlite3GetTempReg(pParse);
90316    sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
90317    j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
90318                           regR, SQLITE_INT_TO_PTR(regIdx),
90319                           P4_INT32);
90320    sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
90321
90322    /* Generate code that executes if the new index entry is not unique */
90323    assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
90324        || onError==OE_Ignore || onError==OE_Replace );
90325    switch( onError ){
90326      case OE_Rollback:
90327      case OE_Abort:
90328      case OE_Fail: {
90329        int j;
90330        StrAccum errMsg;
90331        const char *zSep;
90332        char *zErr;
90333
90334        sqlite3StrAccumInit(&errMsg, 0, 0, 200);
90335        errMsg.db = pParse->db;
90336        zSep = pIdx->nColumn>1 ? "columns " : "column ";
90337        for(j=0; j<pIdx->nColumn; j++){
90338          char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
90339          sqlite3StrAccumAppend(&errMsg, zSep, -1);
90340          zSep = ", ";
90341          sqlite3StrAccumAppend(&errMsg, zCol, -1);
90342        }
90343        sqlite3StrAccumAppend(&errMsg,
90344            pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
90345        zErr = sqlite3StrAccumFinish(&errMsg);
90346        sqlite3HaltConstraint(pParse, onError, zErr, 0);
90347        sqlite3DbFree(errMsg.db, zErr);
90348        break;
90349      }
90350      case OE_Ignore: {
90351        assert( seenReplace==0 );
90352        sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
90353        break;
90354      }
90355      default: {
90356        Trigger *pTrigger = 0;
90357        assert( onError==OE_Replace );
90358        sqlite3MultiWrite(pParse);
90359        if( pParse->db->flags&SQLITE_RecTriggers ){
90360          pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
90361        }
90362        sqlite3GenerateRowDelete(
90363            pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
90364        );
90365        seenReplace = 1;
90366        break;
90367      }
90368    }
90369    sqlite3VdbeJumpHere(v, j3);
90370    sqlite3ReleaseTempReg(pParse, regR);
90371  }
90372
90373  if( pbMayReplace ){
90374    *pbMayReplace = seenReplace;
90375  }
90376}
90377
90378/*
90379** This routine generates code to finish the INSERT or UPDATE operation
90380** that was started by a prior call to sqlite3GenerateConstraintChecks.
90381** A consecutive range of registers starting at regRowid contains the
90382** rowid and the content to be inserted.
90383**
90384** The arguments to this routine should be the same as the first six
90385** arguments to sqlite3GenerateConstraintChecks.
90386*/
90387SQLITE_PRIVATE void sqlite3CompleteInsertion(
90388  Parse *pParse,      /* The parser context */
90389  Table *pTab,        /* the table into which we are inserting */
90390  int baseCur,        /* Index of a read/write cursor pointing at pTab */
90391  int regRowid,       /* Range of content */
90392  int *aRegIdx,       /* Register used by each index.  0 for unused indices */
90393  int isUpdate,       /* True for UPDATE, False for INSERT */
90394  int appendBias,     /* True if this is likely to be an append */
90395  int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
90396){
90397  int i;
90398  Vdbe *v;
90399  int nIdx;
90400  Index *pIdx;
90401  u8 pik_flags;
90402  int regData;
90403  int regRec;
90404
90405  v = sqlite3GetVdbe(pParse);
90406  assert( v!=0 );
90407  assert( pTab->pSelect==0 );  /* This table is not a VIEW */
90408  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
90409  for(i=nIdx-1; i>=0; i--){
90410    if( aRegIdx[i]==0 ) continue;
90411    sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
90412    if( useSeekResult ){
90413      sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
90414    }
90415  }
90416  regData = regRowid + 1;
90417  regRec = sqlite3GetTempReg(pParse);
90418  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
90419  sqlite3TableAffinityStr(v, pTab);
90420  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
90421  if( pParse->nested ){
90422    pik_flags = 0;
90423  }else{
90424    pik_flags = OPFLAG_NCHANGE;
90425    pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
90426  }
90427  if( appendBias ){
90428    pik_flags |= OPFLAG_APPEND;
90429  }
90430  if( useSeekResult ){
90431    pik_flags |= OPFLAG_USESEEKRESULT;
90432  }
90433  sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
90434  if( !pParse->nested ){
90435    sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
90436  }
90437  sqlite3VdbeChangeP5(v, pik_flags);
90438}
90439
90440/*
90441** Generate code that will open cursors for a table and for all
90442** indices of that table.  The "baseCur" parameter is the cursor number used
90443** for the table.  Indices are opened on subsequent cursors.
90444**
90445** Return the number of indices on the table.
90446*/
90447SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
90448  Parse *pParse,   /* Parsing context */
90449  Table *pTab,     /* Table to be opened */
90450  int baseCur,     /* Cursor number assigned to the table */
90451  int op           /* OP_OpenRead or OP_OpenWrite */
90452){
90453  int i;
90454  int iDb;
90455  Index *pIdx;
90456  Vdbe *v;
90457
90458  if( IsVirtual(pTab) ) return 0;
90459  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
90460  v = sqlite3GetVdbe(pParse);
90461  assert( v!=0 );
90462  sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
90463  for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
90464    KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
90465    assert( pIdx->pSchema==pTab->pSchema );
90466    sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
90467                      (char*)pKey, P4_KEYINFO_HANDOFF);
90468    VdbeComment((v, "%s", pIdx->zName));
90469  }
90470  if( pParse->nTab<baseCur+i ){
90471    pParse->nTab = baseCur+i;
90472  }
90473  return i-1;
90474}
90475
90476
90477#ifdef SQLITE_TEST
90478/*
90479** The following global variable is incremented whenever the
90480** transfer optimization is used.  This is used for testing
90481** purposes only - to make sure the transfer optimization really
90482** is happening when it is suppose to.
90483*/
90484SQLITE_API int sqlite3_xferopt_count;
90485#endif /* SQLITE_TEST */
90486
90487
90488#ifndef SQLITE_OMIT_XFER_OPT
90489/*
90490** Check to collation names to see if they are compatible.
90491*/
90492static int xferCompatibleCollation(const char *z1, const char *z2){
90493  if( z1==0 ){
90494    return z2==0;
90495  }
90496  if( z2==0 ){
90497    return 0;
90498  }
90499  return sqlite3StrICmp(z1, z2)==0;
90500}
90501
90502
90503/*
90504** Check to see if index pSrc is compatible as a source of data
90505** for index pDest in an insert transfer optimization.  The rules
90506** for a compatible index:
90507**
90508**    *   The index is over the same set of columns
90509**    *   The same DESC and ASC markings occurs on all columns
90510**    *   The same onError processing (OE_Abort, OE_Ignore, etc)
90511**    *   The same collating sequence on each column
90512*/
90513static int xferCompatibleIndex(Index *pDest, Index *pSrc){
90514  int i;
90515  assert( pDest && pSrc );
90516  assert( pDest->pTable!=pSrc->pTable );
90517  if( pDest->nColumn!=pSrc->nColumn ){
90518    return 0;   /* Different number of columns */
90519  }
90520  if( pDest->onError!=pSrc->onError ){
90521    return 0;   /* Different conflict resolution strategies */
90522  }
90523  for(i=0; i<pSrc->nColumn; i++){
90524    if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
90525      return 0;   /* Different columns indexed */
90526    }
90527    if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
90528      return 0;   /* Different sort orders */
90529    }
90530    if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
90531      return 0;   /* Different collating sequences */
90532    }
90533  }
90534
90535  /* If no test above fails then the indices must be compatible */
90536  return 1;
90537}
90538
90539/*
90540** Attempt the transfer optimization on INSERTs of the form
90541**
90542**     INSERT INTO tab1 SELECT * FROM tab2;
90543**
90544** The xfer optimization transfers raw records from tab2 over to tab1.
90545** Columns are not decoded and reassemblied, which greatly improves
90546** performance.  Raw index records are transferred in the same way.
90547**
90548** The xfer optimization is only attempted if tab1 and tab2 are compatible.
90549** There are lots of rules for determining compatibility - see comments
90550** embedded in the code for details.
90551**
90552** This routine returns TRUE if the optimization is guaranteed to be used.
90553** Sometimes the xfer optimization will only work if the destination table
90554** is empty - a factor that can only be determined at run-time.  In that
90555** case, this routine generates code for the xfer optimization but also
90556** does a test to see if the destination table is empty and jumps over the
90557** xfer optimization code if the test fails.  In that case, this routine
90558** returns FALSE so that the caller will know to go ahead and generate
90559** an unoptimized transfer.  This routine also returns FALSE if there
90560** is no chance that the xfer optimization can be applied.
90561**
90562** This optimization is particularly useful at making VACUUM run faster.
90563*/
90564static int xferOptimization(
90565  Parse *pParse,        /* Parser context */
90566  Table *pDest,         /* The table we are inserting into */
90567  Select *pSelect,      /* A SELECT statement to use as the data source */
90568  int onError,          /* How to handle constraint errors */
90569  int iDbDest           /* The database of pDest */
90570){
90571  ExprList *pEList;                /* The result set of the SELECT */
90572  Table *pSrc;                     /* The table in the FROM clause of SELECT */
90573  Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
90574  struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
90575  int i;                           /* Loop counter */
90576  int iDbSrc;                      /* The database of pSrc */
90577  int iSrc, iDest;                 /* Cursors from source and destination */
90578  int addr1, addr2;                /* Loop addresses */
90579  int emptyDestTest;               /* Address of test for empty pDest */
90580  int emptySrcTest;                /* Address of test for empty pSrc */
90581  Vdbe *v;                         /* The VDBE we are building */
90582  KeyInfo *pKey;                   /* Key information for an index */
90583  int regAutoinc;                  /* Memory register used by AUTOINC */
90584  int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
90585  int regData, regRowid;           /* Registers holding data and rowid */
90586
90587  if( pSelect==0 ){
90588    return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
90589  }
90590  if( sqlite3TriggerList(pParse, pDest) ){
90591    return 0;   /* tab1 must not have triggers */
90592  }
90593#ifndef SQLITE_OMIT_VIRTUALTABLE
90594  if( pDest->tabFlags & TF_Virtual ){
90595    return 0;   /* tab1 must not be a virtual table */
90596  }
90597#endif
90598  if( onError==OE_Default ){
90599    if( pDest->iPKey>=0 ) onError = pDest->keyConf;
90600    if( onError==OE_Default ) onError = OE_Abort;
90601  }
90602  assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
90603  if( pSelect->pSrc->nSrc!=1 ){
90604    return 0;   /* FROM clause must have exactly one term */
90605  }
90606  if( pSelect->pSrc->a[0].pSelect ){
90607    return 0;   /* FROM clause cannot contain a subquery */
90608  }
90609  if( pSelect->pWhere ){
90610    return 0;   /* SELECT may not have a WHERE clause */
90611  }
90612  if( pSelect->pOrderBy ){
90613    return 0;   /* SELECT may not have an ORDER BY clause */
90614  }
90615  /* Do not need to test for a HAVING clause.  If HAVING is present but
90616  ** there is no ORDER BY, we will get an error. */
90617  if( pSelect->pGroupBy ){
90618    return 0;   /* SELECT may not have a GROUP BY clause */
90619  }
90620  if( pSelect->pLimit ){
90621    return 0;   /* SELECT may not have a LIMIT clause */
90622  }
90623  assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
90624  if( pSelect->pPrior ){
90625    return 0;   /* SELECT may not be a compound query */
90626  }
90627  if( pSelect->selFlags & SF_Distinct ){
90628    return 0;   /* SELECT may not be DISTINCT */
90629  }
90630  pEList = pSelect->pEList;
90631  assert( pEList!=0 );
90632  if( pEList->nExpr!=1 ){
90633    return 0;   /* The result set must have exactly one column */
90634  }
90635  assert( pEList->a[0].pExpr );
90636  if( pEList->a[0].pExpr->op!=TK_ALL ){
90637    return 0;   /* The result set must be the special operator "*" */
90638  }
90639
90640  /* At this point we have established that the statement is of the
90641  ** correct syntactic form to participate in this optimization.  Now
90642  ** we have to check the semantics.
90643  */
90644  pItem = pSelect->pSrc->a;
90645  pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
90646  if( pSrc==0 ){
90647    return 0;   /* FROM clause does not contain a real table */
90648  }
90649  if( pSrc==pDest ){
90650    return 0;   /* tab1 and tab2 may not be the same table */
90651  }
90652#ifndef SQLITE_OMIT_VIRTUALTABLE
90653  if( pSrc->tabFlags & TF_Virtual ){
90654    return 0;   /* tab2 must not be a virtual table */
90655  }
90656#endif
90657  if( pSrc->pSelect ){
90658    return 0;   /* tab2 may not be a view */
90659  }
90660  if( pDest->nCol!=pSrc->nCol ){
90661    return 0;   /* Number of columns must be the same in tab1 and tab2 */
90662  }
90663  if( pDest->iPKey!=pSrc->iPKey ){
90664    return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
90665  }
90666  for(i=0; i<pDest->nCol; i++){
90667    if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
90668      return 0;    /* Affinity must be the same on all columns */
90669    }
90670    if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
90671      return 0;    /* Collating sequence must be the same on all columns */
90672    }
90673    if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
90674      return 0;    /* tab2 must be NOT NULL if tab1 is */
90675    }
90676  }
90677  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90678    if( pDestIdx->onError!=OE_None ){
90679      destHasUniqueIdx = 1;
90680    }
90681    for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
90682      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90683    }
90684    if( pSrcIdx==0 ){
90685      return 0;    /* pDestIdx has no corresponding index in pSrc */
90686    }
90687  }
90688#ifndef SQLITE_OMIT_CHECK
90689  if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
90690    return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
90691  }
90692#endif
90693#ifndef SQLITE_OMIT_FOREIGN_KEY
90694  /* Disallow the transfer optimization if the destination table constains
90695  ** any foreign key constraints.  This is more restrictive than necessary.
90696  ** But the main beneficiary of the transfer optimization is the VACUUM
90697  ** command, and the VACUUM command disables foreign key constraints.  So
90698  ** the extra complication to make this rule less restrictive is probably
90699  ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
90700  */
90701  if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
90702    return 0;
90703  }
90704#endif
90705  if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
90706    return 0;  /* xfer opt does not play well with PRAGMA count_changes */
90707  }
90708
90709  /* If we get this far, it means that the xfer optimization is at
90710  ** least a possibility, though it might only work if the destination
90711  ** table (tab1) is initially empty.
90712  */
90713#ifdef SQLITE_TEST
90714  sqlite3_xferopt_count++;
90715#endif
90716  iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
90717  v = sqlite3GetVdbe(pParse);
90718  sqlite3CodeVerifySchema(pParse, iDbSrc);
90719  iSrc = pParse->nTab++;
90720  iDest = pParse->nTab++;
90721  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
90722  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
90723  if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
90724   || destHasUniqueIdx                              /* (2) */
90725   || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
90726  ){
90727    /* In some circumstances, we are able to run the xfer optimization
90728    ** only if the destination table is initially empty.  This code makes
90729    ** that determination.  Conditions under which the destination must
90730    ** be empty:
90731    **
90732    ** (1) There is no INTEGER PRIMARY KEY but there are indices.
90733    **     (If the destination is not initially empty, the rowid fields
90734    **     of index entries might need to change.)
90735    **
90736    ** (2) The destination has a unique index.  (The xfer optimization
90737    **     is unable to test uniqueness.)
90738    **
90739    ** (3) onError is something other than OE_Abort and OE_Rollback.
90740    */
90741    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
90742    emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90743    sqlite3VdbeJumpHere(v, addr1);
90744  }else{
90745    emptyDestTest = 0;
90746  }
90747  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
90748  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90749  regData = sqlite3GetTempReg(pParse);
90750  regRowid = sqlite3GetTempReg(pParse);
90751  if( pDest->iPKey>=0 ){
90752    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90753    addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
90754    sqlite3HaltConstraint(
90755        pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
90756    sqlite3VdbeJumpHere(v, addr2);
90757    autoIncStep(pParse, regAutoinc, regRowid);
90758  }else if( pDest->pIndex==0 ){
90759    addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
90760  }else{
90761    addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
90762    assert( (pDest->tabFlags & TF_Autoincrement)==0 );
90763  }
90764  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
90765  sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
90766  sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
90767  sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
90768  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
90769  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
90770    for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
90771      if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
90772    }
90773    assert( pSrcIdx );
90774    sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90775    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90776    pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
90777    sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
90778                      (char*)pKey, P4_KEYINFO_HANDOFF);
90779    VdbeComment((v, "%s", pSrcIdx->zName));
90780    pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
90781    sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
90782                      (char*)pKey, P4_KEYINFO_HANDOFF);
90783    VdbeComment((v, "%s", pDestIdx->zName));
90784    addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
90785    sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
90786    sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
90787    sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
90788    sqlite3VdbeJumpHere(v, addr1);
90789  }
90790  sqlite3VdbeJumpHere(v, emptySrcTest);
90791  sqlite3ReleaseTempReg(pParse, regRowid);
90792  sqlite3ReleaseTempReg(pParse, regData);
90793  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
90794  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90795  if( emptyDestTest ){
90796    sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
90797    sqlite3VdbeJumpHere(v, emptyDestTest);
90798    sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
90799    return 0;
90800  }else{
90801    return 1;
90802  }
90803}
90804#endif /* SQLITE_OMIT_XFER_OPT */
90805
90806/************** End of insert.c **********************************************/
90807/************** Begin file legacy.c ******************************************/
90808/*
90809** 2001 September 15
90810**
90811** The author disclaims copyright to this source code.  In place of
90812** a legal notice, here is a blessing:
90813**
90814**    May you do good and not evil.
90815**    May you find forgiveness for yourself and forgive others.
90816**    May you share freely, never taking more than you give.
90817**
90818*************************************************************************
90819** Main file for the SQLite library.  The routines in this file
90820** implement the programmer interface to the library.  Routines in
90821** other files are for internal use by SQLite and should not be
90822** accessed by users of the library.
90823*/
90824
90825
90826/*
90827** Execute SQL code.  Return one of the SQLITE_ success/failure
90828** codes.  Also write an error message into memory obtained from
90829** malloc() and make *pzErrMsg point to that message.
90830**
90831** If the SQL is a query, then for each row in the query result
90832** the xCallback() function is called.  pArg becomes the first
90833** argument to xCallback().  If xCallback=NULL then no callback
90834** is invoked, even for queries.
90835*/
90836SQLITE_API int sqlite3_exec(
90837  sqlite3 *db,                /* The database on which the SQL executes */
90838  const char *zSql,           /* The SQL to be executed */
90839  sqlite3_callback xCallback, /* Invoke this callback routine */
90840  void *pArg,                 /* First argument to xCallback() */
90841  char **pzErrMsg             /* Write error messages here */
90842){
90843  int rc = SQLITE_OK;         /* Return code */
90844  const char *zLeftover;      /* Tail of unprocessed SQL */
90845  sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
90846  char **azCols = 0;          /* Names of result columns */
90847  int nRetry = 0;             /* Number of retry attempts */
90848  int callbackIsInit;         /* True if callback data is initialized */
90849
90850  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
90851  if( zSql==0 ) zSql = "";
90852
90853  sqlite3_mutex_enter(db->mutex);
90854  sqlite3Error(db, SQLITE_OK, 0);
90855  while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
90856    int nCol;
90857    char **azVals = 0;
90858
90859    pStmt = 0;
90860    rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
90861    assert( rc==SQLITE_OK || pStmt==0 );
90862    if( rc!=SQLITE_OK ){
90863      continue;
90864    }
90865    if( !pStmt ){
90866      /* this happens for a comment or white-space */
90867      zSql = zLeftover;
90868      continue;
90869    }
90870
90871    callbackIsInit = 0;
90872    nCol = sqlite3_column_count(pStmt);
90873
90874    while( 1 ){
90875      int i;
90876      rc = sqlite3_step(pStmt);
90877
90878      /* Invoke the callback function if required */
90879      if( xCallback && (SQLITE_ROW==rc ||
90880          (SQLITE_DONE==rc && !callbackIsInit
90881                           && db->flags&SQLITE_NullCallback)) ){
90882        if( !callbackIsInit ){
90883          azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
90884          if( azCols==0 ){
90885            goto exec_out;
90886          }
90887          for(i=0; i<nCol; i++){
90888            azCols[i] = (char *)sqlite3_column_name(pStmt, i);
90889            /* sqlite3VdbeSetColName() installs column names as UTF8
90890            ** strings so there is no way for sqlite3_column_name() to fail. */
90891            assert( azCols[i]!=0 );
90892          }
90893          callbackIsInit = 1;
90894        }
90895        if( rc==SQLITE_ROW ){
90896          azVals = &azCols[nCol];
90897          for(i=0; i<nCol; i++){
90898            azVals[i] = (char *)sqlite3_column_text(pStmt, i);
90899            if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
90900              db->mallocFailed = 1;
90901              goto exec_out;
90902            }
90903          }
90904        }
90905        if( xCallback(pArg, nCol, azVals, azCols) ){
90906          rc = SQLITE_ABORT;
90907          sqlite3VdbeFinalize((Vdbe *)pStmt);
90908          pStmt = 0;
90909          sqlite3Error(db, SQLITE_ABORT, 0);
90910          goto exec_out;
90911        }
90912      }
90913
90914      if( rc!=SQLITE_ROW ){
90915        rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
90916        pStmt = 0;
90917        if( rc!=SQLITE_SCHEMA ){
90918          nRetry = 0;
90919          zSql = zLeftover;
90920          while( sqlite3Isspace(zSql[0]) ) zSql++;
90921        }
90922        break;
90923      }
90924    }
90925
90926    sqlite3DbFree(db, azCols);
90927    azCols = 0;
90928  }
90929
90930exec_out:
90931  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
90932  sqlite3DbFree(db, azCols);
90933
90934  rc = sqlite3ApiExit(db, rc);
90935  if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
90936    int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
90937    *pzErrMsg = sqlite3Malloc(nErrMsg);
90938    if( *pzErrMsg ){
90939      memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
90940    }else{
90941      rc = SQLITE_NOMEM;
90942      sqlite3Error(db, SQLITE_NOMEM, 0);
90943    }
90944  }else if( pzErrMsg ){
90945    *pzErrMsg = 0;
90946  }
90947
90948  assert( (rc&db->errMask)==rc );
90949  sqlite3_mutex_leave(db->mutex);
90950  return rc;
90951}
90952
90953/************** End of legacy.c **********************************************/
90954/************** Begin file loadext.c *****************************************/
90955/*
90956** 2006 June 7
90957**
90958** The author disclaims copyright to this source code.  In place of
90959** a legal notice, here is a blessing:
90960**
90961**    May you do good and not evil.
90962**    May you find forgiveness for yourself and forgive others.
90963**    May you share freely, never taking more than you give.
90964**
90965*************************************************************************
90966** This file contains code used to dynamically load extensions into
90967** the SQLite library.
90968*/
90969
90970#ifndef SQLITE_CORE
90971  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
90972#endif
90973/************** Include sqlite3ext.h in the middle of loadext.c **************/
90974/************** Begin file sqlite3ext.h **************************************/
90975/*
90976** 2006 June 7
90977**
90978** The author disclaims copyright to this source code.  In place of
90979** a legal notice, here is a blessing:
90980**
90981**    May you do good and not evil.
90982**    May you find forgiveness for yourself and forgive others.
90983**    May you share freely, never taking more than you give.
90984**
90985*************************************************************************
90986** This header file defines the SQLite interface for use by
90987** shared libraries that want to be imported as extensions into
90988** an SQLite instance.  Shared libraries that intend to be loaded
90989** as extensions by SQLite should #include this file instead of
90990** sqlite3.h.
90991*/
90992#ifndef _SQLITE3EXT_H_
90993#define _SQLITE3EXT_H_
90994
90995typedef struct sqlite3_api_routines sqlite3_api_routines;
90996
90997/*
90998** The following structure holds pointers to all of the SQLite API
90999** routines.
91000**
91001** WARNING:  In order to maintain backwards compatibility, add new
91002** interfaces to the end of this structure only.  If you insert new
91003** interfaces in the middle of this structure, then older different
91004** versions of SQLite will not be able to load each others' shared
91005** libraries!
91006*/
91007struct sqlite3_api_routines {
91008  void * (*aggregate_context)(sqlite3_context*,int nBytes);
91009  int  (*aggregate_count)(sqlite3_context*);
91010  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
91011  int  (*bind_double)(sqlite3_stmt*,int,double);
91012  int  (*bind_int)(sqlite3_stmt*,int,int);
91013  int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
91014  int  (*bind_null)(sqlite3_stmt*,int);
91015  int  (*bind_parameter_count)(sqlite3_stmt*);
91016  int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
91017  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
91018  int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
91019  int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
91020  int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
91021  int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
91022  int  (*busy_timeout)(sqlite3*,int ms);
91023  int  (*changes)(sqlite3*);
91024  int  (*close)(sqlite3*);
91025  int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
91026                           int eTextRep,const char*));
91027  int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
91028                             int eTextRep,const void*));
91029  const void * (*column_blob)(sqlite3_stmt*,int iCol);
91030  int  (*column_bytes)(sqlite3_stmt*,int iCol);
91031  int  (*column_bytes16)(sqlite3_stmt*,int iCol);
91032  int  (*column_count)(sqlite3_stmt*pStmt);
91033  const char * (*column_database_name)(sqlite3_stmt*,int);
91034  const void * (*column_database_name16)(sqlite3_stmt*,int);
91035  const char * (*column_decltype)(sqlite3_stmt*,int i);
91036  const void * (*column_decltype16)(sqlite3_stmt*,int);
91037  double  (*column_double)(sqlite3_stmt*,int iCol);
91038  int  (*column_int)(sqlite3_stmt*,int iCol);
91039  sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
91040  const char * (*column_name)(sqlite3_stmt*,int);
91041  const void * (*column_name16)(sqlite3_stmt*,int);
91042  const char * (*column_origin_name)(sqlite3_stmt*,int);
91043  const void * (*column_origin_name16)(sqlite3_stmt*,int);
91044  const char * (*column_table_name)(sqlite3_stmt*,int);
91045  const void * (*column_table_name16)(sqlite3_stmt*,int);
91046  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
91047  const void * (*column_text16)(sqlite3_stmt*,int iCol);
91048  int  (*column_type)(sqlite3_stmt*,int iCol);
91049  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
91050  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
91051  int  (*complete)(const char*sql);
91052  int  (*complete16)(const void*sql);
91053  int  (*create_collation)(sqlite3*,const char*,int,void*,
91054                           int(*)(void*,int,const void*,int,const void*));
91055  int  (*create_collation16)(sqlite3*,const void*,int,void*,
91056                             int(*)(void*,int,const void*,int,const void*));
91057  int  (*create_function)(sqlite3*,const char*,int,int,void*,
91058                          void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91059                          void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91060                          void (*xFinal)(sqlite3_context*));
91061  int  (*create_function16)(sqlite3*,const void*,int,int,void*,
91062                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91063                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91064                            void (*xFinal)(sqlite3_context*));
91065  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
91066  int  (*data_count)(sqlite3_stmt*pStmt);
91067  sqlite3 * (*db_handle)(sqlite3_stmt*);
91068  int (*declare_vtab)(sqlite3*,const char*);
91069  int  (*enable_shared_cache)(int);
91070  int  (*errcode)(sqlite3*db);
91071  const char * (*errmsg)(sqlite3*);
91072  const void * (*errmsg16)(sqlite3*);
91073  int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
91074  int  (*expired)(sqlite3_stmt*);
91075  int  (*finalize)(sqlite3_stmt*pStmt);
91076  void  (*free)(void*);
91077  void  (*free_table)(char**result);
91078  int  (*get_autocommit)(sqlite3*);
91079  void * (*get_auxdata)(sqlite3_context*,int);
91080  int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
91081  int  (*global_recover)(void);
91082  void  (*interruptx)(sqlite3*);
91083  sqlite_int64  (*last_insert_rowid)(sqlite3*);
91084  const char * (*libversion)(void);
91085  int  (*libversion_number)(void);
91086  void *(*malloc)(int);
91087  char * (*mprintf)(const char*,...);
91088  int  (*open)(const char*,sqlite3**);
91089  int  (*open16)(const void*,sqlite3**);
91090  int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
91091  int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
91092  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
91093  void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
91094  void *(*realloc)(void*,int);
91095  int  (*reset)(sqlite3_stmt*pStmt);
91096  void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
91097  void  (*result_double)(sqlite3_context*,double);
91098  void  (*result_error)(sqlite3_context*,const char*,int);
91099  void  (*result_error16)(sqlite3_context*,const void*,int);
91100  void  (*result_int)(sqlite3_context*,int);
91101  void  (*result_int64)(sqlite3_context*,sqlite_int64);
91102  void  (*result_null)(sqlite3_context*);
91103  void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
91104  void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
91105  void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
91106  void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
91107  void  (*result_value)(sqlite3_context*,sqlite3_value*);
91108  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
91109  int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
91110                         const char*,const char*),void*);
91111  void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
91112  char * (*snprintf)(int,char*,const char*,...);
91113  int  (*step)(sqlite3_stmt*);
91114  int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
91115                                char const**,char const**,int*,int*,int*);
91116  void  (*thread_cleanup)(void);
91117  int  (*total_changes)(sqlite3*);
91118  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
91119  int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
91120  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
91121                                         sqlite_int64),void*);
91122  void * (*user_data)(sqlite3_context*);
91123  const void * (*value_blob)(sqlite3_value*);
91124  int  (*value_bytes)(sqlite3_value*);
91125  int  (*value_bytes16)(sqlite3_value*);
91126  double  (*value_double)(sqlite3_value*);
91127  int  (*value_int)(sqlite3_value*);
91128  sqlite_int64  (*value_int64)(sqlite3_value*);
91129  int  (*value_numeric_type)(sqlite3_value*);
91130  const unsigned char * (*value_text)(sqlite3_value*);
91131  const void * (*value_text16)(sqlite3_value*);
91132  const void * (*value_text16be)(sqlite3_value*);
91133  const void * (*value_text16le)(sqlite3_value*);
91134  int  (*value_type)(sqlite3_value*);
91135  char *(*vmprintf)(const char*,va_list);
91136  /* Added ??? */
91137  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
91138  /* Added by 3.3.13 */
91139  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
91140  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
91141  int (*clear_bindings)(sqlite3_stmt*);
91142  /* Added by 3.4.1 */
91143  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
91144                          void (*xDestroy)(void *));
91145  /* Added by 3.5.0 */
91146  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
91147  int (*blob_bytes)(sqlite3_blob*);
91148  int (*blob_close)(sqlite3_blob*);
91149  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
91150                   int,sqlite3_blob**);
91151  int (*blob_read)(sqlite3_blob*,void*,int,int);
91152  int (*blob_write)(sqlite3_blob*,const void*,int,int);
91153  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
91154                             int(*)(void*,int,const void*,int,const void*),
91155                             void(*)(void*));
91156  int (*file_control)(sqlite3*,const char*,int,void*);
91157  sqlite3_int64 (*memory_highwater)(int);
91158  sqlite3_int64 (*memory_used)(void);
91159  sqlite3_mutex *(*mutex_alloc)(int);
91160  void (*mutex_enter)(sqlite3_mutex*);
91161  void (*mutex_free)(sqlite3_mutex*);
91162  void (*mutex_leave)(sqlite3_mutex*);
91163  int (*mutex_try)(sqlite3_mutex*);
91164  int (*open_v2)(const char*,sqlite3**,int,const char*);
91165  int (*release_memory)(int);
91166  void (*result_error_nomem)(sqlite3_context*);
91167  void (*result_error_toobig)(sqlite3_context*);
91168  int (*sleep)(int);
91169  void (*soft_heap_limit)(int);
91170  sqlite3_vfs *(*vfs_find)(const char*);
91171  int (*vfs_register)(sqlite3_vfs*,int);
91172  int (*vfs_unregister)(sqlite3_vfs*);
91173  int (*xthreadsafe)(void);
91174  void (*result_zeroblob)(sqlite3_context*,int);
91175  void (*result_error_code)(sqlite3_context*,int);
91176  int (*test_control)(int, ...);
91177  void (*randomness)(int,void*);
91178  sqlite3 *(*context_db_handle)(sqlite3_context*);
91179  int (*extended_result_codes)(sqlite3*,int);
91180  int (*limit)(sqlite3*,int,int);
91181  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
91182  const char *(*sql)(sqlite3_stmt*);
91183  int (*status)(int,int*,int*,int);
91184  int (*backup_finish)(sqlite3_backup*);
91185  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
91186  int (*backup_pagecount)(sqlite3_backup*);
91187  int (*backup_remaining)(sqlite3_backup*);
91188  int (*backup_step)(sqlite3_backup*,int);
91189  const char *(*compileoption_get)(int);
91190  int (*compileoption_used)(const char*);
91191  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
91192                            void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
91193                            void (*xStep)(sqlite3_context*,int,sqlite3_value**),
91194                            void (*xFinal)(sqlite3_context*),
91195                            void(*xDestroy)(void*));
91196  int (*db_config)(sqlite3*,int,...);
91197  sqlite3_mutex *(*db_mutex)(sqlite3*);
91198  int (*db_status)(sqlite3*,int,int*,int*,int);
91199  int (*extended_errcode)(sqlite3*);
91200  void (*log)(int,const char*,...);
91201  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
91202  const char *(*sourceid)(void);
91203  int (*stmt_status)(sqlite3_stmt*,int,int);
91204  int (*strnicmp)(const char*,const char*,int);
91205  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
91206  int (*wal_autocheckpoint)(sqlite3*,int);
91207  int (*wal_checkpoint)(sqlite3*,const char*);
91208  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
91209  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
91210  int (*vtab_config)(sqlite3*,int op,...);
91211  int (*vtab_on_conflict)(sqlite3*);
91212};
91213
91214/*
91215** The following macros redefine the API routines so that they are
91216** redirected throught the global sqlite3_api structure.
91217**
91218** This header file is also used by the loadext.c source file
91219** (part of the main SQLite library - not an extension) so that
91220** it can get access to the sqlite3_api_routines structure
91221** definition.  But the main library does not want to redefine
91222** the API.  So the redefinition macros are only valid if the
91223** SQLITE_CORE macros is undefined.
91224*/
91225#ifndef SQLITE_CORE
91226#define sqlite3_aggregate_context      sqlite3_api->aggregate_context
91227#ifndef SQLITE_OMIT_DEPRECATED
91228#define sqlite3_aggregate_count        sqlite3_api->aggregate_count
91229#endif
91230#define sqlite3_bind_blob              sqlite3_api->bind_blob
91231#define sqlite3_bind_double            sqlite3_api->bind_double
91232#define sqlite3_bind_int               sqlite3_api->bind_int
91233#define sqlite3_bind_int64             sqlite3_api->bind_int64
91234#define sqlite3_bind_null              sqlite3_api->bind_null
91235#define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
91236#define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
91237#define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
91238#define sqlite3_bind_text              sqlite3_api->bind_text
91239#define sqlite3_bind_text16            sqlite3_api->bind_text16
91240#define sqlite3_bind_value             sqlite3_api->bind_value
91241#define sqlite3_busy_handler           sqlite3_api->busy_handler
91242#define sqlite3_busy_timeout           sqlite3_api->busy_timeout
91243#define sqlite3_changes                sqlite3_api->changes
91244#define sqlite3_close                  sqlite3_api->close
91245#define sqlite3_collation_needed       sqlite3_api->collation_needed
91246#define sqlite3_collation_needed16     sqlite3_api->collation_needed16
91247#define sqlite3_column_blob            sqlite3_api->column_blob
91248#define sqlite3_column_bytes           sqlite3_api->column_bytes
91249#define sqlite3_column_bytes16         sqlite3_api->column_bytes16
91250#define sqlite3_column_count           sqlite3_api->column_count
91251#define sqlite3_column_database_name   sqlite3_api->column_database_name
91252#define sqlite3_column_database_name16 sqlite3_api->column_database_name16
91253#define sqlite3_column_decltype        sqlite3_api->column_decltype
91254#define sqlite3_column_decltype16      sqlite3_api->column_decltype16
91255#define sqlite3_column_double          sqlite3_api->column_double
91256#define sqlite3_column_int             sqlite3_api->column_int
91257#define sqlite3_column_int64           sqlite3_api->column_int64
91258#define sqlite3_column_name            sqlite3_api->column_name
91259#define sqlite3_column_name16          sqlite3_api->column_name16
91260#define sqlite3_column_origin_name     sqlite3_api->column_origin_name
91261#define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
91262#define sqlite3_column_table_name      sqlite3_api->column_table_name
91263#define sqlite3_column_table_name16    sqlite3_api->column_table_name16
91264#define sqlite3_column_text            sqlite3_api->column_text
91265#define sqlite3_column_text16          sqlite3_api->column_text16
91266#define sqlite3_column_type            sqlite3_api->column_type
91267#define sqlite3_column_value           sqlite3_api->column_value
91268#define sqlite3_commit_hook            sqlite3_api->commit_hook
91269#define sqlite3_complete               sqlite3_api->complete
91270#define sqlite3_complete16             sqlite3_api->complete16
91271#define sqlite3_create_collation       sqlite3_api->create_collation
91272#define sqlite3_create_collation16     sqlite3_api->create_collation16
91273#define sqlite3_create_function        sqlite3_api->create_function
91274#define sqlite3_create_function16      sqlite3_api->create_function16
91275#define sqlite3_create_module          sqlite3_api->create_module
91276#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
91277#define sqlite3_data_count             sqlite3_api->data_count
91278#define sqlite3_db_handle              sqlite3_api->db_handle
91279#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
91280#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
91281#define sqlite3_errcode                sqlite3_api->errcode
91282#define sqlite3_errmsg                 sqlite3_api->errmsg
91283#define sqlite3_errmsg16               sqlite3_api->errmsg16
91284#define sqlite3_exec                   sqlite3_api->exec
91285#ifndef SQLITE_OMIT_DEPRECATED
91286#define sqlite3_expired                sqlite3_api->expired
91287#endif
91288#define sqlite3_finalize               sqlite3_api->finalize
91289#define sqlite3_free                   sqlite3_api->free
91290#define sqlite3_free_table             sqlite3_api->free_table
91291#define sqlite3_get_autocommit         sqlite3_api->get_autocommit
91292#define sqlite3_get_auxdata            sqlite3_api->get_auxdata
91293#define sqlite3_get_table              sqlite3_api->get_table
91294#ifndef SQLITE_OMIT_DEPRECATED
91295#define sqlite3_global_recover         sqlite3_api->global_recover
91296#endif
91297#define sqlite3_interrupt              sqlite3_api->interruptx
91298#define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
91299#define sqlite3_libversion             sqlite3_api->libversion
91300#define sqlite3_libversion_number      sqlite3_api->libversion_number
91301#define sqlite3_malloc                 sqlite3_api->malloc
91302#define sqlite3_mprintf                sqlite3_api->mprintf
91303#define sqlite3_open                   sqlite3_api->open
91304#define sqlite3_open16                 sqlite3_api->open16
91305#define sqlite3_prepare                sqlite3_api->prepare
91306#define sqlite3_prepare16              sqlite3_api->prepare16
91307#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91308#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91309#define sqlite3_profile                sqlite3_api->profile
91310#define sqlite3_progress_handler       sqlite3_api->progress_handler
91311#define sqlite3_realloc                sqlite3_api->realloc
91312#define sqlite3_reset                  sqlite3_api->reset
91313#define sqlite3_result_blob            sqlite3_api->result_blob
91314#define sqlite3_result_double          sqlite3_api->result_double
91315#define sqlite3_result_error           sqlite3_api->result_error
91316#define sqlite3_result_error16         sqlite3_api->result_error16
91317#define sqlite3_result_int             sqlite3_api->result_int
91318#define sqlite3_result_int64           sqlite3_api->result_int64
91319#define sqlite3_result_null            sqlite3_api->result_null
91320#define sqlite3_result_text            sqlite3_api->result_text
91321#define sqlite3_result_text16          sqlite3_api->result_text16
91322#define sqlite3_result_text16be        sqlite3_api->result_text16be
91323#define sqlite3_result_text16le        sqlite3_api->result_text16le
91324#define sqlite3_result_value           sqlite3_api->result_value
91325#define sqlite3_rollback_hook          sqlite3_api->rollback_hook
91326#define sqlite3_set_authorizer         sqlite3_api->set_authorizer
91327#define sqlite3_set_auxdata            sqlite3_api->set_auxdata
91328#define sqlite3_snprintf               sqlite3_api->snprintf
91329#define sqlite3_step                   sqlite3_api->step
91330#define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
91331#define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
91332#define sqlite3_total_changes          sqlite3_api->total_changes
91333#define sqlite3_trace                  sqlite3_api->trace
91334#ifndef SQLITE_OMIT_DEPRECATED
91335#define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
91336#endif
91337#define sqlite3_update_hook            sqlite3_api->update_hook
91338#define sqlite3_user_data              sqlite3_api->user_data
91339#define sqlite3_value_blob             sqlite3_api->value_blob
91340#define sqlite3_value_bytes            sqlite3_api->value_bytes
91341#define sqlite3_value_bytes16          sqlite3_api->value_bytes16
91342#define sqlite3_value_double           sqlite3_api->value_double
91343#define sqlite3_value_int              sqlite3_api->value_int
91344#define sqlite3_value_int64            sqlite3_api->value_int64
91345#define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
91346#define sqlite3_value_text             sqlite3_api->value_text
91347#define sqlite3_value_text16           sqlite3_api->value_text16
91348#define sqlite3_value_text16be         sqlite3_api->value_text16be
91349#define sqlite3_value_text16le         sqlite3_api->value_text16le
91350#define sqlite3_value_type             sqlite3_api->value_type
91351#define sqlite3_vmprintf               sqlite3_api->vmprintf
91352#define sqlite3_overload_function      sqlite3_api->overload_function
91353#define sqlite3_prepare_v2             sqlite3_api->prepare_v2
91354#define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
91355#define sqlite3_clear_bindings         sqlite3_api->clear_bindings
91356#define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
91357#define sqlite3_blob_bytes             sqlite3_api->blob_bytes
91358#define sqlite3_blob_close             sqlite3_api->blob_close
91359#define sqlite3_blob_open              sqlite3_api->blob_open
91360#define sqlite3_blob_read              sqlite3_api->blob_read
91361#define sqlite3_blob_write             sqlite3_api->blob_write
91362#define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
91363#define sqlite3_file_control           sqlite3_api->file_control
91364#define sqlite3_memory_highwater       sqlite3_api->memory_highwater
91365#define sqlite3_memory_used            sqlite3_api->memory_used
91366#define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
91367#define sqlite3_mutex_enter            sqlite3_api->mutex_enter
91368#define sqlite3_mutex_free             sqlite3_api->mutex_free
91369#define sqlite3_mutex_leave            sqlite3_api->mutex_leave
91370#define sqlite3_mutex_try              sqlite3_api->mutex_try
91371#define sqlite3_open_v2                sqlite3_api->open_v2
91372#define sqlite3_release_memory         sqlite3_api->release_memory
91373#define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
91374#define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
91375#define sqlite3_sleep                  sqlite3_api->sleep
91376#define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
91377#define sqlite3_vfs_find               sqlite3_api->vfs_find
91378#define sqlite3_vfs_register           sqlite3_api->vfs_register
91379#define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
91380#define sqlite3_threadsafe             sqlite3_api->xthreadsafe
91381#define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
91382#define sqlite3_result_error_code      sqlite3_api->result_error_code
91383#define sqlite3_test_control           sqlite3_api->test_control
91384#define sqlite3_randomness             sqlite3_api->randomness
91385#define sqlite3_context_db_handle      sqlite3_api->context_db_handle
91386#define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
91387#define sqlite3_limit                  sqlite3_api->limit
91388#define sqlite3_next_stmt              sqlite3_api->next_stmt
91389#define sqlite3_sql                    sqlite3_api->sql
91390#define sqlite3_status                 sqlite3_api->status
91391#define sqlite3_backup_finish          sqlite3_api->backup_finish
91392#define sqlite3_backup_init            sqlite3_api->backup_init
91393#define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
91394#define sqlite3_backup_remaining       sqlite3_api->backup_remaining
91395#define sqlite3_backup_step            sqlite3_api->backup_step
91396#define sqlite3_compileoption_get      sqlite3_api->compileoption_get
91397#define sqlite3_compileoption_used     sqlite3_api->compileoption_used
91398#define sqlite3_create_function_v2     sqlite3_api->create_function_v2
91399#define sqlite3_db_config              sqlite3_api->db_config
91400#define sqlite3_db_mutex               sqlite3_api->db_mutex
91401#define sqlite3_db_status              sqlite3_api->db_status
91402#define sqlite3_extended_errcode       sqlite3_api->extended_errcode
91403#define sqlite3_log                    sqlite3_api->log
91404#define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
91405#define sqlite3_sourceid               sqlite3_api->sourceid
91406#define sqlite3_stmt_status            sqlite3_api->stmt_status
91407#define sqlite3_strnicmp               sqlite3_api->strnicmp
91408#define sqlite3_unlock_notify          sqlite3_api->unlock_notify
91409#define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
91410#define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
91411#define sqlite3_wal_hook               sqlite3_api->wal_hook
91412#define sqlite3_blob_reopen            sqlite3_api->blob_reopen
91413#define sqlite3_vtab_config            sqlite3_api->vtab_config
91414#define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
91415#endif /* SQLITE_CORE */
91416
91417#define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
91418#define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
91419
91420#endif /* _SQLITE3EXT_H_ */
91421
91422/************** End of sqlite3ext.h ******************************************/
91423/************** Continuing where we left off in loadext.c ********************/
91424/* #include <string.h> */
91425
91426#ifndef SQLITE_OMIT_LOAD_EXTENSION
91427
91428/*
91429** Some API routines are omitted when various features are
91430** excluded from a build of SQLite.  Substitute a NULL pointer
91431** for any missing APIs.
91432*/
91433#ifndef SQLITE_ENABLE_COLUMN_METADATA
91434# define sqlite3_column_database_name   0
91435# define sqlite3_column_database_name16 0
91436# define sqlite3_column_table_name      0
91437# define sqlite3_column_table_name16    0
91438# define sqlite3_column_origin_name     0
91439# define sqlite3_column_origin_name16   0
91440# define sqlite3_table_column_metadata  0
91441#endif
91442
91443#ifdef SQLITE_OMIT_AUTHORIZATION
91444# define sqlite3_set_authorizer         0
91445#endif
91446
91447#ifdef SQLITE_OMIT_UTF16
91448# define sqlite3_bind_text16            0
91449# define sqlite3_collation_needed16     0
91450# define sqlite3_column_decltype16      0
91451# define sqlite3_column_name16          0
91452# define sqlite3_column_text16          0
91453# define sqlite3_complete16             0
91454# define sqlite3_create_collation16     0
91455# define sqlite3_create_function16      0
91456# define sqlite3_errmsg16               0
91457# define sqlite3_open16                 0
91458# define sqlite3_prepare16              0
91459# define sqlite3_prepare16_v2           0
91460# define sqlite3_result_error16         0
91461# define sqlite3_result_text16          0
91462# define sqlite3_result_text16be        0
91463# define sqlite3_result_text16le        0
91464# define sqlite3_value_text16           0
91465# define sqlite3_value_text16be         0
91466# define sqlite3_value_text16le         0
91467# define sqlite3_column_database_name16 0
91468# define sqlite3_column_table_name16    0
91469# define sqlite3_column_origin_name16   0
91470#endif
91471
91472#ifdef SQLITE_OMIT_COMPLETE
91473# define sqlite3_complete 0
91474# define sqlite3_complete16 0
91475#endif
91476
91477#ifdef SQLITE_OMIT_DECLTYPE
91478# define sqlite3_column_decltype16      0
91479# define sqlite3_column_decltype        0
91480#endif
91481
91482#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
91483# define sqlite3_progress_handler 0
91484#endif
91485
91486#ifdef SQLITE_OMIT_VIRTUALTABLE
91487# define sqlite3_create_module 0
91488# define sqlite3_create_module_v2 0
91489# define sqlite3_declare_vtab 0
91490# define sqlite3_vtab_config 0
91491# define sqlite3_vtab_on_conflict 0
91492#endif
91493
91494#ifdef SQLITE_OMIT_SHARED_CACHE
91495# define sqlite3_enable_shared_cache 0
91496#endif
91497
91498#ifdef SQLITE_OMIT_TRACE
91499# define sqlite3_profile       0
91500# define sqlite3_trace         0
91501#endif
91502
91503#ifdef SQLITE_OMIT_GET_TABLE
91504# define sqlite3_free_table    0
91505# define sqlite3_get_table     0
91506#endif
91507
91508#ifdef SQLITE_OMIT_INCRBLOB
91509#define sqlite3_bind_zeroblob  0
91510#define sqlite3_blob_bytes     0
91511#define sqlite3_blob_close     0
91512#define sqlite3_blob_open      0
91513#define sqlite3_blob_read      0
91514#define sqlite3_blob_write     0
91515#define sqlite3_blob_reopen    0
91516#endif
91517
91518/*
91519** The following structure contains pointers to all SQLite API routines.
91520** A pointer to this structure is passed into extensions when they are
91521** loaded so that the extension can make calls back into the SQLite
91522** library.
91523**
91524** When adding new APIs, add them to the bottom of this structure
91525** in order to preserve backwards compatibility.
91526**
91527** Extensions that use newer APIs should first call the
91528** sqlite3_libversion_number() to make sure that the API they
91529** intend to use is supported by the library.  Extensions should
91530** also check to make sure that the pointer to the function is
91531** not NULL before calling it.
91532*/
91533static const sqlite3_api_routines sqlite3Apis = {
91534  sqlite3_aggregate_context,
91535#ifndef SQLITE_OMIT_DEPRECATED
91536  sqlite3_aggregate_count,
91537#else
91538  0,
91539#endif
91540  sqlite3_bind_blob,
91541  sqlite3_bind_double,
91542  sqlite3_bind_int,
91543  sqlite3_bind_int64,
91544  sqlite3_bind_null,
91545  sqlite3_bind_parameter_count,
91546  sqlite3_bind_parameter_index,
91547  sqlite3_bind_parameter_name,
91548  sqlite3_bind_text,
91549  sqlite3_bind_text16,
91550  sqlite3_bind_value,
91551  sqlite3_busy_handler,
91552  sqlite3_busy_timeout,
91553  sqlite3_changes,
91554  sqlite3_close,
91555  sqlite3_collation_needed,
91556  sqlite3_collation_needed16,
91557  sqlite3_column_blob,
91558  sqlite3_column_bytes,
91559  sqlite3_column_bytes16,
91560  sqlite3_column_count,
91561  sqlite3_column_database_name,
91562  sqlite3_column_database_name16,
91563  sqlite3_column_decltype,
91564  sqlite3_column_decltype16,
91565  sqlite3_column_double,
91566  sqlite3_column_int,
91567  sqlite3_column_int64,
91568  sqlite3_column_name,
91569  sqlite3_column_name16,
91570  sqlite3_column_origin_name,
91571  sqlite3_column_origin_name16,
91572  sqlite3_column_table_name,
91573  sqlite3_column_table_name16,
91574  sqlite3_column_text,
91575  sqlite3_column_text16,
91576  sqlite3_column_type,
91577  sqlite3_column_value,
91578  sqlite3_commit_hook,
91579  sqlite3_complete,
91580  sqlite3_complete16,
91581  sqlite3_create_collation,
91582  sqlite3_create_collation16,
91583  sqlite3_create_function,
91584  sqlite3_create_function16,
91585  sqlite3_create_module,
91586  sqlite3_data_count,
91587  sqlite3_db_handle,
91588  sqlite3_declare_vtab,
91589  sqlite3_enable_shared_cache,
91590  sqlite3_errcode,
91591  sqlite3_errmsg,
91592  sqlite3_errmsg16,
91593  sqlite3_exec,
91594#ifndef SQLITE_OMIT_DEPRECATED
91595  sqlite3_expired,
91596#else
91597  0,
91598#endif
91599  sqlite3_finalize,
91600  sqlite3_free,
91601  sqlite3_free_table,
91602  sqlite3_get_autocommit,
91603  sqlite3_get_auxdata,
91604  sqlite3_get_table,
91605  0,     /* Was sqlite3_global_recover(), but that function is deprecated */
91606  sqlite3_interrupt,
91607  sqlite3_last_insert_rowid,
91608  sqlite3_libversion,
91609  sqlite3_libversion_number,
91610  sqlite3_malloc,
91611  sqlite3_mprintf,
91612  sqlite3_open,
91613  sqlite3_open16,
91614  sqlite3_prepare,
91615  sqlite3_prepare16,
91616  sqlite3_profile,
91617  sqlite3_progress_handler,
91618  sqlite3_realloc,
91619  sqlite3_reset,
91620  sqlite3_result_blob,
91621  sqlite3_result_double,
91622  sqlite3_result_error,
91623  sqlite3_result_error16,
91624  sqlite3_result_int,
91625  sqlite3_result_int64,
91626  sqlite3_result_null,
91627  sqlite3_result_text,
91628  sqlite3_result_text16,
91629  sqlite3_result_text16be,
91630  sqlite3_result_text16le,
91631  sqlite3_result_value,
91632  sqlite3_rollback_hook,
91633  sqlite3_set_authorizer,
91634  sqlite3_set_auxdata,
91635  sqlite3_snprintf,
91636  sqlite3_step,
91637  sqlite3_table_column_metadata,
91638#ifndef SQLITE_OMIT_DEPRECATED
91639  sqlite3_thread_cleanup,
91640#else
91641  0,
91642#endif
91643  sqlite3_total_changes,
91644  sqlite3_trace,
91645#ifndef SQLITE_OMIT_DEPRECATED
91646  sqlite3_transfer_bindings,
91647#else
91648  0,
91649#endif
91650  sqlite3_update_hook,
91651  sqlite3_user_data,
91652  sqlite3_value_blob,
91653  sqlite3_value_bytes,
91654  sqlite3_value_bytes16,
91655  sqlite3_value_double,
91656  sqlite3_value_int,
91657  sqlite3_value_int64,
91658  sqlite3_value_numeric_type,
91659  sqlite3_value_text,
91660  sqlite3_value_text16,
91661  sqlite3_value_text16be,
91662  sqlite3_value_text16le,
91663  sqlite3_value_type,
91664  sqlite3_vmprintf,
91665  /*
91666  ** The original API set ends here.  All extensions can call any
91667  ** of the APIs above provided that the pointer is not NULL.  But
91668  ** before calling APIs that follow, extension should check the
91669  ** sqlite3_libversion_number() to make sure they are dealing with
91670  ** a library that is new enough to support that API.
91671  *************************************************************************
91672  */
91673  sqlite3_overload_function,
91674
91675  /*
91676  ** Added after 3.3.13
91677  */
91678  sqlite3_prepare_v2,
91679  sqlite3_prepare16_v2,
91680  sqlite3_clear_bindings,
91681
91682  /*
91683  ** Added for 3.4.1
91684  */
91685  sqlite3_create_module_v2,
91686
91687  /*
91688  ** Added for 3.5.0
91689  */
91690  sqlite3_bind_zeroblob,
91691  sqlite3_blob_bytes,
91692  sqlite3_blob_close,
91693  sqlite3_blob_open,
91694  sqlite3_blob_read,
91695  sqlite3_blob_write,
91696  sqlite3_create_collation_v2,
91697  sqlite3_file_control,
91698  sqlite3_memory_highwater,
91699  sqlite3_memory_used,
91700#ifdef SQLITE_MUTEX_OMIT
91701  0,
91702  0,
91703  0,
91704  0,
91705  0,
91706#else
91707  sqlite3_mutex_alloc,
91708  sqlite3_mutex_enter,
91709  sqlite3_mutex_free,
91710  sqlite3_mutex_leave,
91711  sqlite3_mutex_try,
91712#endif
91713  sqlite3_open_v2,
91714  sqlite3_release_memory,
91715  sqlite3_result_error_nomem,
91716  sqlite3_result_error_toobig,
91717  sqlite3_sleep,
91718  sqlite3_soft_heap_limit,
91719  sqlite3_vfs_find,
91720  sqlite3_vfs_register,
91721  sqlite3_vfs_unregister,
91722
91723  /*
91724  ** Added for 3.5.8
91725  */
91726  sqlite3_threadsafe,
91727  sqlite3_result_zeroblob,
91728  sqlite3_result_error_code,
91729  sqlite3_test_control,
91730  sqlite3_randomness,
91731  sqlite3_context_db_handle,
91732
91733  /*
91734  ** Added for 3.6.0
91735  */
91736  sqlite3_extended_result_codes,
91737  sqlite3_limit,
91738  sqlite3_next_stmt,
91739  sqlite3_sql,
91740  sqlite3_status,
91741
91742  /*
91743  ** Added for 3.7.4
91744  */
91745  sqlite3_backup_finish,
91746  sqlite3_backup_init,
91747  sqlite3_backup_pagecount,
91748  sqlite3_backup_remaining,
91749  sqlite3_backup_step,
91750#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
91751  sqlite3_compileoption_get,
91752  sqlite3_compileoption_used,
91753#else
91754  0,
91755  0,
91756#endif
91757  sqlite3_create_function_v2,
91758  sqlite3_db_config,
91759  sqlite3_db_mutex,
91760  sqlite3_db_status,
91761  sqlite3_extended_errcode,
91762  sqlite3_log,
91763  sqlite3_soft_heap_limit64,
91764  sqlite3_sourceid,
91765  sqlite3_stmt_status,
91766  sqlite3_strnicmp,
91767#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
91768  sqlite3_unlock_notify,
91769#else
91770  0,
91771#endif
91772#ifndef SQLITE_OMIT_WAL
91773  sqlite3_wal_autocheckpoint,
91774  sqlite3_wal_checkpoint,
91775  sqlite3_wal_hook,
91776#else
91777  0,
91778  0,
91779  0,
91780#endif
91781  sqlite3_blob_reopen,
91782  sqlite3_vtab_config,
91783  sqlite3_vtab_on_conflict,
91784};
91785
91786/*
91787** Attempt to load an SQLite extension library contained in the file
91788** zFile.  The entry point is zProc.  zProc may be 0 in which case a
91789** default entry point name (sqlite3_extension_init) is used.  Use
91790** of the default name is recommended.
91791**
91792** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
91793**
91794** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
91795** error message text.  The calling function should free this memory
91796** by calling sqlite3DbFree(db, ).
91797*/
91798static int sqlite3LoadExtension(
91799  sqlite3 *db,          /* Load the extension into this database connection */
91800  const char *zFile,    /* Name of the shared library containing extension */
91801  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91802  char **pzErrMsg       /* Put error message here if not 0 */
91803){
91804  sqlite3_vfs *pVfs = db->pVfs;
91805  void *handle;
91806  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
91807  char *zErrmsg = 0;
91808  void **aHandle;
91809  int nMsg = 300 + sqlite3Strlen30(zFile);
91810
91811  if( pzErrMsg ) *pzErrMsg = 0;
91812
91813  /* Ticket #1863.  To avoid a creating security problems for older
91814  ** applications that relink against newer versions of SQLite, the
91815  ** ability to run load_extension is turned off by default.  One
91816  ** must call sqlite3_enable_load_extension() to turn on extension
91817  ** loading.  Otherwise you get the following error.
91818  */
91819  if( (db->flags & SQLITE_LoadExtension)==0 ){
91820    if( pzErrMsg ){
91821      *pzErrMsg = sqlite3_mprintf("not authorized");
91822    }
91823    return SQLITE_ERROR;
91824  }
91825
91826  if( zProc==0 ){
91827    zProc = "sqlite3_extension_init";
91828  }
91829
91830  handle = sqlite3OsDlOpen(pVfs, zFile);
91831  if( handle==0 ){
91832    if( pzErrMsg ){
91833      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91834      if( zErrmsg ){
91835        sqlite3_snprintf(nMsg, zErrmsg,
91836            "unable to open shared library [%s]", zFile);
91837        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91838      }
91839    }
91840    return SQLITE_ERROR;
91841  }
91842  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
91843                   sqlite3OsDlSym(pVfs, handle, zProc);
91844  if( xInit==0 ){
91845    if( pzErrMsg ){
91846      nMsg += sqlite3Strlen30(zProc);
91847      *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
91848      if( zErrmsg ){
91849        sqlite3_snprintf(nMsg, zErrmsg,
91850            "no entry point [%s] in shared library [%s]", zProc,zFile);
91851        sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
91852      }
91853      sqlite3OsDlClose(pVfs, handle);
91854    }
91855    return SQLITE_ERROR;
91856  }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
91857    if( pzErrMsg ){
91858      *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
91859    }
91860    sqlite3_free(zErrmsg);
91861    sqlite3OsDlClose(pVfs, handle);
91862    return SQLITE_ERROR;
91863  }
91864
91865  /* Append the new shared library handle to the db->aExtension array. */
91866  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
91867  if( aHandle==0 ){
91868    return SQLITE_NOMEM;
91869  }
91870  if( db->nExtension>0 ){
91871    memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
91872  }
91873  sqlite3DbFree(db, db->aExtension);
91874  db->aExtension = aHandle;
91875
91876  db->aExtension[db->nExtension++] = handle;
91877  return SQLITE_OK;
91878}
91879SQLITE_API int sqlite3_load_extension(
91880  sqlite3 *db,          /* Load the extension into this database connection */
91881  const char *zFile,    /* Name of the shared library containing extension */
91882  const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
91883  char **pzErrMsg       /* Put error message here if not 0 */
91884){
91885  int rc;
91886  sqlite3_mutex_enter(db->mutex);
91887  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
91888  rc = sqlite3ApiExit(db, rc);
91889  sqlite3_mutex_leave(db->mutex);
91890  return rc;
91891}
91892
91893/*
91894** Call this routine when the database connection is closing in order
91895** to clean up loaded extensions
91896*/
91897SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
91898  int i;
91899  assert( sqlite3_mutex_held(db->mutex) );
91900  for(i=0; i<db->nExtension; i++){
91901    sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
91902  }
91903  sqlite3DbFree(db, db->aExtension);
91904}
91905
91906/*
91907** Enable or disable extension loading.  Extension loading is disabled by
91908** default so as not to open security holes in older applications.
91909*/
91910SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
91911  sqlite3_mutex_enter(db->mutex);
91912  if( onoff ){
91913    db->flags |= SQLITE_LoadExtension;
91914  }else{
91915    db->flags &= ~SQLITE_LoadExtension;
91916  }
91917  sqlite3_mutex_leave(db->mutex);
91918  return SQLITE_OK;
91919}
91920
91921#endif /* SQLITE_OMIT_LOAD_EXTENSION */
91922
91923/*
91924** The auto-extension code added regardless of whether or not extension
91925** loading is supported.  We need a dummy sqlite3Apis pointer for that
91926** code if regular extension loading is not available.  This is that
91927** dummy pointer.
91928*/
91929#ifdef SQLITE_OMIT_LOAD_EXTENSION
91930static const sqlite3_api_routines sqlite3Apis = { 0 };
91931#endif
91932
91933
91934/*
91935** The following object holds the list of automatically loaded
91936** extensions.
91937**
91938** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
91939** mutex must be held while accessing this list.
91940*/
91941typedef struct sqlite3AutoExtList sqlite3AutoExtList;
91942static SQLITE_WSD struct sqlite3AutoExtList {
91943  int nExt;              /* Number of entries in aExt[] */
91944  void (**aExt)(void);   /* Pointers to the extension init functions */
91945} sqlite3Autoext = { 0, 0 };
91946
91947/* The "wsdAutoext" macro will resolve to the autoextension
91948** state vector.  If writable static data is unsupported on the target,
91949** we have to locate the state vector at run-time.  In the more common
91950** case where writable static data is supported, wsdStat can refer directly
91951** to the "sqlite3Autoext" state vector declared above.
91952*/
91953#ifdef SQLITE_OMIT_WSD
91954# define wsdAutoextInit \
91955  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
91956# define wsdAutoext x[0]
91957#else
91958# define wsdAutoextInit
91959# define wsdAutoext sqlite3Autoext
91960#endif
91961
91962
91963/*
91964** Register a statically linked extension that is automatically
91965** loaded by every new database connection.
91966*/
91967SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
91968  int rc = SQLITE_OK;
91969#ifndef SQLITE_OMIT_AUTOINIT
91970  rc = sqlite3_initialize();
91971  if( rc ){
91972    return rc;
91973  }else
91974#endif
91975  {
91976    int i;
91977#if SQLITE_THREADSAFE
91978    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
91979#endif
91980    wsdAutoextInit;
91981    sqlite3_mutex_enter(mutex);
91982    for(i=0; i<wsdAutoext.nExt; i++){
91983      if( wsdAutoext.aExt[i]==xInit ) break;
91984    }
91985    if( i==wsdAutoext.nExt ){
91986      int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
91987      void (**aNew)(void);
91988      aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
91989      if( aNew==0 ){
91990        rc = SQLITE_NOMEM;
91991      }else{
91992        wsdAutoext.aExt = aNew;
91993        wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
91994        wsdAutoext.nExt++;
91995      }
91996    }
91997    sqlite3_mutex_leave(mutex);
91998    assert( (rc&0xff)==rc );
91999    return rc;
92000  }
92001}
92002
92003/*
92004** Reset the automatic extension loading mechanism.
92005*/
92006SQLITE_API void sqlite3_reset_auto_extension(void){
92007#ifndef SQLITE_OMIT_AUTOINIT
92008  if( sqlite3_initialize()==SQLITE_OK )
92009#endif
92010  {
92011#if SQLITE_THREADSAFE
92012    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
92013#endif
92014    wsdAutoextInit;
92015    sqlite3_mutex_enter(mutex);
92016    sqlite3_free(wsdAutoext.aExt);
92017    wsdAutoext.aExt = 0;
92018    wsdAutoext.nExt = 0;
92019    sqlite3_mutex_leave(mutex);
92020  }
92021}
92022
92023/*
92024** Load all automatic extensions.
92025**
92026** If anything goes wrong, set an error in the database connection.
92027*/
92028SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
92029  int i;
92030  int go = 1;
92031  int rc;
92032  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
92033
92034  wsdAutoextInit;
92035  if( wsdAutoext.nExt==0 ){
92036    /* Common case: early out without every having to acquire a mutex */
92037    return;
92038  }
92039  for(i=0; go; i++){
92040    char *zErrmsg;
92041#if SQLITE_THREADSAFE
92042    sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
92043#endif
92044    sqlite3_mutex_enter(mutex);
92045    if( i>=wsdAutoext.nExt ){
92046      xInit = 0;
92047      go = 0;
92048    }else{
92049      xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
92050              wsdAutoext.aExt[i];
92051    }
92052    sqlite3_mutex_leave(mutex);
92053    zErrmsg = 0;
92054    if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
92055      sqlite3Error(db, rc,
92056            "automatic extension loading failed: %s", zErrmsg);
92057      go = 0;
92058    }
92059    sqlite3_free(zErrmsg);
92060  }
92061}
92062
92063/************** End of loadext.c *********************************************/
92064/************** Begin file pragma.c ******************************************/
92065/*
92066** 2003 April 6
92067**
92068** The author disclaims copyright to this source code.  In place of
92069** a legal notice, here is a blessing:
92070**
92071**    May you do good and not evil.
92072**    May you find forgiveness for yourself and forgive others.
92073**    May you share freely, never taking more than you give.
92074**
92075*************************************************************************
92076** This file contains code used to implement the PRAGMA command.
92077*/
92078
92079/*
92080** Interpret the given string as a safety level.  Return 0 for OFF,
92081** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or
92082** unrecognized string argument.  The FULL option is disallowed
92083** if the omitFull parameter it 1.
92084**
92085** Note that the values returned are one less that the values that
92086** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
92087** to support legacy SQL code.  The safety level used to be boolean
92088** and older scripts may have used numbers 0 for OFF and 1 for ON.
92089*/
92090static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
92091                             /* 123456789 123456789 */
92092  static const char zText[] = "onoffalseyestruefull";
92093  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
92094  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
92095  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
92096  int i, n;
92097  if( sqlite3Isdigit(*z) ){
92098    return (u8)sqlite3Atoi(z);
92099  }
92100  n = sqlite3Strlen30(z);
92101  for(i=0; i<ArraySize(iLength)-omitFull; i++){
92102    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
92103      return iValue[i];
92104    }
92105  }
92106  return dflt;
92107}
92108
92109/*
92110** Interpret the given string as a boolean value.
92111*/
92112SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
92113  return getSafetyLevel(z,1,dflt)!=0;
92114}
92115
92116/* The sqlite3GetBoolean() function is used by other modules but the
92117** remainder of this file is specific to PRAGMA processing.  So omit
92118** the rest of the file if PRAGMAs are omitted from the build.
92119*/
92120#if !defined(SQLITE_OMIT_PRAGMA)
92121
92122/*
92123** Interpret the given string as a locking mode value.
92124*/
92125static int getLockingMode(const char *z){
92126  if( z ){
92127    if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
92128    if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
92129  }
92130  return PAGER_LOCKINGMODE_QUERY;
92131}
92132
92133#ifndef SQLITE_OMIT_AUTOVACUUM
92134/*
92135** Interpret the given string as an auto-vacuum mode value.
92136**
92137** The following strings, "none", "full" and "incremental" are
92138** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
92139*/
92140static int getAutoVacuum(const char *z){
92141  int i;
92142  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
92143  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
92144  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
92145  i = sqlite3Atoi(z);
92146  return (u8)((i>=0&&i<=2)?i:0);
92147}
92148#endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
92149
92150#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92151/*
92152** Interpret the given string as a temp db location. Return 1 for file
92153** backed temporary databases, 2 for the Red-Black tree in memory database
92154** and 0 to use the compile-time default.
92155*/
92156static int getTempStore(const char *z){
92157  if( z[0]>='0' && z[0]<='2' ){
92158    return z[0] - '0';
92159  }else if( sqlite3StrICmp(z, "file")==0 ){
92160    return 1;
92161  }else if( sqlite3StrICmp(z, "memory")==0 ){
92162    return 2;
92163  }else{
92164    return 0;
92165  }
92166}
92167#endif /* SQLITE_PAGER_PRAGMAS */
92168
92169#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92170/*
92171** Invalidate temp storage, either when the temp storage is changed
92172** from default, or when 'file' and the temp_store_directory has changed
92173*/
92174static int invalidateTempStorage(Parse *pParse){
92175  sqlite3 *db = pParse->db;
92176  if( db->aDb[1].pBt!=0 ){
92177    if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
92178      sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
92179        "from within a transaction");
92180      return SQLITE_ERROR;
92181    }
92182    sqlite3BtreeClose(db->aDb[1].pBt);
92183    db->aDb[1].pBt = 0;
92184    sqlite3ResetInternalSchema(db, -1);
92185  }
92186  return SQLITE_OK;
92187}
92188#endif /* SQLITE_PAGER_PRAGMAS */
92189
92190#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92191/*
92192** If the TEMP database is open, close it and mark the database schema
92193** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
92194** or DEFAULT_TEMP_STORE pragmas.
92195*/
92196static int changeTempStorage(Parse *pParse, const char *zStorageType){
92197  int ts = getTempStore(zStorageType);
92198  sqlite3 *db = pParse->db;
92199  if( db->temp_store==ts ) return SQLITE_OK;
92200  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
92201    return SQLITE_ERROR;
92202  }
92203  db->temp_store = (u8)ts;
92204  return SQLITE_OK;
92205}
92206#endif /* SQLITE_PAGER_PRAGMAS */
92207
92208/*
92209** Generate code to return a single integer value.
92210*/
92211static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
92212  Vdbe *v = sqlite3GetVdbe(pParse);
92213  int mem = ++pParse->nMem;
92214  i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
92215  if( pI64 ){
92216    memcpy(pI64, &value, sizeof(value));
92217  }
92218  sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
92219  sqlite3VdbeSetNumCols(v, 1);
92220  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
92221  sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
92222}
92223
92224#ifndef SQLITE_OMIT_FLAG_PRAGMAS
92225/*
92226** Check to see if zRight and zLeft refer to a pragma that queries
92227** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
92228** Also, implement the pragma.
92229*/
92230static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
92231  static const struct sPragmaType {
92232    const char *zName;  /* Name of the pragma */
92233    int mask;           /* Mask for the db->flags value */
92234  } aPragma[] = {
92235    { "full_column_names",        SQLITE_FullColNames  },
92236    { "short_column_names",       SQLITE_ShortColNames },
92237    { "count_changes",            SQLITE_CountRows     },
92238    { "empty_result_callbacks",   SQLITE_NullCallback  },
92239    { "legacy_file_format",       SQLITE_LegacyFileFmt },
92240    { "fullfsync",                SQLITE_FullFSync     },
92241    { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
92242    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
92243#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
92244    { "automatic_index",          SQLITE_AutoIndex     },
92245#endif
92246#ifdef SQLITE_DEBUG
92247    { "sql_trace",                SQLITE_SqlTrace      },
92248    { "vdbe_listing",             SQLITE_VdbeListing   },
92249    { "vdbe_trace",               SQLITE_VdbeTrace     },
92250#endif
92251#ifndef SQLITE_OMIT_CHECK
92252    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
92253#endif
92254    /* The following is VERY experimental */
92255    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
92256
92257    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
92258    ** flag if there are any active statements. */
92259    { "read_uncommitted",         SQLITE_ReadUncommitted },
92260    { "recursive_triggers",       SQLITE_RecTriggers },
92261
92262    /* This flag may only be set if both foreign-key and trigger support
92263    ** are present in the build.  */
92264#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
92265    { "foreign_keys",             SQLITE_ForeignKeys },
92266#endif
92267  };
92268  int i;
92269  const struct sPragmaType *p;
92270  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
92271    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
92272      sqlite3 *db = pParse->db;
92273      Vdbe *v;
92274      v = sqlite3GetVdbe(pParse);
92275      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
92276      if( ALWAYS(v) ){
92277        if( zRight==0 ){
92278          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
92279        }else{
92280          int mask = p->mask;          /* Mask of bits to set or clear. */
92281          if( db->autoCommit==0 ){
92282            /* Foreign key support may not be enabled or disabled while not
92283            ** in auto-commit mode.  */
92284            mask &= ~(SQLITE_ForeignKeys);
92285          }
92286
92287          if( sqlite3GetBoolean(zRight, 0) ){
92288            db->flags |= mask;
92289          }else{
92290            db->flags &= ~mask;
92291          }
92292
92293          /* Many of the flag-pragmas modify the code generated by the SQL
92294          ** compiler (eg. count_changes). So add an opcode to expire all
92295          ** compiled SQL statements after modifying a pragma value.
92296          */
92297          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
92298        }
92299      }
92300
92301      return 1;
92302    }
92303  }
92304  return 0;
92305}
92306#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
92307
92308/*
92309** Return a human-readable name for a constraint resolution action.
92310*/
92311#ifndef SQLITE_OMIT_FOREIGN_KEY
92312static const char *actionName(u8 action){
92313  const char *zName;
92314  switch( action ){
92315    case OE_SetNull:  zName = "SET NULL";        break;
92316    case OE_SetDflt:  zName = "SET DEFAULT";     break;
92317    case OE_Cascade:  zName = "CASCADE";         break;
92318    case OE_Restrict: zName = "RESTRICT";        break;
92319    default:          zName = "NO ACTION";
92320                      assert( action==OE_None ); break;
92321  }
92322  return zName;
92323}
92324#endif
92325
92326
92327/*
92328** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
92329** defined in pager.h. This function returns the associated lowercase
92330** journal-mode name.
92331*/
92332SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
92333  static char * const azModeName[] = {
92334    "delete", "persist", "off", "truncate", "memory"
92335#ifndef SQLITE_OMIT_WAL
92336     , "wal"
92337#endif
92338  };
92339  assert( PAGER_JOURNALMODE_DELETE==0 );
92340  assert( PAGER_JOURNALMODE_PERSIST==1 );
92341  assert( PAGER_JOURNALMODE_OFF==2 );
92342  assert( PAGER_JOURNALMODE_TRUNCATE==3 );
92343  assert( PAGER_JOURNALMODE_MEMORY==4 );
92344  assert( PAGER_JOURNALMODE_WAL==5 );
92345  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
92346
92347  if( eMode==ArraySize(azModeName) ) return 0;
92348  return azModeName[eMode];
92349}
92350
92351/*
92352** Process a pragma statement.
92353**
92354** Pragmas are of this form:
92355**
92356**      PRAGMA [database.]id [= value]
92357**
92358** The identifier might also be a string.  The value is a string, and
92359** identifier, or a number.  If minusFlag is true, then the value is
92360** a number that was preceded by a minus sign.
92361**
92362** If the left side is "database.id" then pId1 is the database name
92363** and pId2 is the id.  If the left side is just "id" then pId1 is the
92364** id and pId2 is any empty string.
92365*/
92366SQLITE_PRIVATE void sqlite3Pragma(
92367  Parse *pParse,
92368  Token *pId1,        /* First part of [database.]id field */
92369  Token *pId2,        /* Second part of [database.]id field, or NULL */
92370  Token *pValue,      /* Token for <value>, or NULL */
92371  int minusFlag       /* True if a '-' sign preceded <value> */
92372){
92373  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
92374  char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
92375  const char *zDb = 0;   /* The database name */
92376  Token *pId;            /* Pointer to <id> token */
92377  int iDb;               /* Database index for <database> */
92378  char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
92379  int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
92380  sqlite3 *db = pParse->db;    /* The database connection */
92381  Db *pDb;                     /* The specific database being pragmaed */
92382  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);  /* Prepared statement */
92383
92384  if( v==0 ) return;
92385  sqlite3VdbeRunOnlyOnce(v);
92386  pParse->nMem = 2;
92387
92388  /* Interpret the [database.] part of the pragma statement. iDb is the
92389  ** index of the database this pragma is being applied to in db.aDb[]. */
92390  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
92391  if( iDb<0 ) return;
92392  pDb = &db->aDb[iDb];
92393
92394  /* If the temp database has been explicitly named as part of the
92395  ** pragma, make sure it is open.
92396  */
92397  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
92398    return;
92399  }
92400
92401  zLeft = sqlite3NameFromToken(db, pId);
92402  if( !zLeft ) return;
92403  if( minusFlag ){
92404    zRight = sqlite3MPrintf(db, "-%T", pValue);
92405  }else{
92406    zRight = sqlite3NameFromToken(db, pValue);
92407  }
92408
92409  assert( pId2 );
92410  zDb = pId2->n>0 ? pDb->zName : 0;
92411  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
92412    goto pragma_out;
92413  }
92414
92415  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
92416  ** connection.  If it returns SQLITE_OK, then assume that the VFS
92417  ** handled the pragma and generate a no-op prepared statement.
92418  */
92419  aFcntl[0] = 0;
92420  aFcntl[1] = zLeft;
92421  aFcntl[2] = zRight;
92422  aFcntl[3] = 0;
92423  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
92424  if( rc==SQLITE_OK ){
92425    if( aFcntl[0] ){
92426      int mem = ++pParse->nMem;
92427      sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
92428      sqlite3VdbeSetNumCols(v, 1);
92429      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
92430      sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
92431      sqlite3_free(aFcntl[0]);
92432    }
92433  }else if( rc!=SQLITE_NOTFOUND ){
92434    if( aFcntl[0] ){
92435      sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
92436      sqlite3_free(aFcntl[0]);
92437    }
92438    pParse->nErr++;
92439    pParse->rc = rc;
92440  }else
92441
92442
92443#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
92444  /*
92445  **  PRAGMA [database.]default_cache_size
92446  **  PRAGMA [database.]default_cache_size=N
92447  **
92448  ** The first form reports the current persistent setting for the
92449  ** page cache size.  The value returned is the maximum number of
92450  ** pages in the page cache.  The second form sets both the current
92451  ** page cache size value and the persistent page cache size value
92452  ** stored in the database file.
92453  **
92454  ** Older versions of SQLite would set the default cache size to a
92455  ** negative number to indicate synchronous=OFF.  These days, synchronous
92456  ** is always on by default regardless of the sign of the default cache
92457  ** size.  But continue to take the absolute value of the default cache
92458  ** size of historical compatibility.
92459  */
92460  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
92461    static const VdbeOpList getCacheSize[] = {
92462      { OP_Transaction, 0, 0,        0},                         /* 0 */
92463      { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
92464      { OP_IfPos,       1, 7,        0},
92465      { OP_Integer,     0, 2,        0},
92466      { OP_Subtract,    1, 2,        1},
92467      { OP_IfPos,       1, 7,        0},
92468      { OP_Integer,     0, 1,        0},                         /* 6 */
92469      { OP_ResultRow,   1, 1,        0},
92470    };
92471    int addr;
92472    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92473    sqlite3VdbeUsesBtree(v, iDb);
92474    if( !zRight ){
92475      sqlite3VdbeSetNumCols(v, 1);
92476      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
92477      pParse->nMem += 2;
92478      addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
92479      sqlite3VdbeChangeP1(v, addr, iDb);
92480      sqlite3VdbeChangeP1(v, addr+1, iDb);
92481      sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
92482    }else{
92483      int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
92484      sqlite3BeginWriteOperation(pParse, 0, iDb);
92485      sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
92486      sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
92487      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92488      pDb->pSchema->cache_size = size;
92489      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92490    }
92491  }else
92492#endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
92493
92494#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
92495  /*
92496  **  PRAGMA [database.]page_size
92497  **  PRAGMA [database.]page_size=N
92498  **
92499  ** The first form reports the current setting for the
92500  ** database page size in bytes.  The second form sets the
92501  ** database page size value.  The value can only be set if
92502  ** the database has not yet been created.
92503  */
92504  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
92505    Btree *pBt = pDb->pBt;
92506    assert( pBt!=0 );
92507    if( !zRight ){
92508      int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
92509      returnSingleInt(pParse, "page_size", size);
92510    }else{
92511      /* Malloc may fail when setting the page-size, as there is an internal
92512      ** buffer that the pager module resizes using sqlite3_realloc().
92513      */
92514      db->nextPagesize = sqlite3Atoi(zRight);
92515      if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
92516        db->mallocFailed = 1;
92517      }
92518    }
92519  }else
92520
92521  /*
92522  **  PRAGMA [database.]secure_delete
92523  **  PRAGMA [database.]secure_delete=ON/OFF
92524  **
92525  ** The first form reports the current setting for the
92526  ** secure_delete flag.  The second form changes the secure_delete
92527  ** flag setting and reports thenew value.
92528  */
92529  if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
92530    Btree *pBt = pDb->pBt;
92531    int b = -1;
92532    assert( pBt!=0 );
92533    if( zRight ){
92534      b = sqlite3GetBoolean(zRight, 0);
92535    }
92536    if( pId2->n==0 && b>=0 ){
92537      int ii;
92538      for(ii=0; ii<db->nDb; ii++){
92539        sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
92540      }
92541    }
92542    b = sqlite3BtreeSecureDelete(pBt, b);
92543    returnSingleInt(pParse, "secure_delete", b);
92544  }else
92545
92546  /*
92547  **  PRAGMA [database.]max_page_count
92548  **  PRAGMA [database.]max_page_count=N
92549  **
92550  ** The first form reports the current setting for the
92551  ** maximum number of pages in the database file.  The
92552  ** second form attempts to change this setting.  Both
92553  ** forms return the current setting.
92554  **
92555  ** The absolute value of N is used.  This is undocumented and might
92556  ** change.  The only purpose is to provide an easy way to test
92557  ** the sqlite3AbsInt32() function.
92558  **
92559  **  PRAGMA [database.]page_count
92560  **
92561  ** Return the number of pages in the specified database.
92562  */
92563  if( sqlite3StrICmp(zLeft,"page_count")==0
92564   || sqlite3StrICmp(zLeft,"max_page_count")==0
92565  ){
92566    int iReg;
92567    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92568    sqlite3CodeVerifySchema(pParse, iDb);
92569    iReg = ++pParse->nMem;
92570    if( sqlite3Tolower(zLeft[0])=='p' ){
92571      sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
92572    }else{
92573      sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
92574                        sqlite3AbsInt32(sqlite3Atoi(zRight)));
92575    }
92576    sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
92577    sqlite3VdbeSetNumCols(v, 1);
92578    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
92579  }else
92580
92581  /*
92582  **  PRAGMA [database.]locking_mode
92583  **  PRAGMA [database.]locking_mode = (normal|exclusive)
92584  */
92585  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
92586    const char *zRet = "normal";
92587    int eMode = getLockingMode(zRight);
92588
92589    if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
92590      /* Simple "PRAGMA locking_mode;" statement. This is a query for
92591      ** the current default locking mode (which may be different to
92592      ** the locking-mode of the main database).
92593      */
92594      eMode = db->dfltLockMode;
92595    }else{
92596      Pager *pPager;
92597      if( pId2->n==0 ){
92598        /* This indicates that no database name was specified as part
92599        ** of the PRAGMA command. In this case the locking-mode must be
92600        ** set on all attached databases, as well as the main db file.
92601        **
92602        ** Also, the sqlite3.dfltLockMode variable is set so that
92603        ** any subsequently attached databases also use the specified
92604        ** locking mode.
92605        */
92606        int ii;
92607        assert(pDb==&db->aDb[0]);
92608        for(ii=2; ii<db->nDb; ii++){
92609          pPager = sqlite3BtreePager(db->aDb[ii].pBt);
92610          sqlite3PagerLockingMode(pPager, eMode);
92611        }
92612        db->dfltLockMode = (u8)eMode;
92613      }
92614      pPager = sqlite3BtreePager(pDb->pBt);
92615      eMode = sqlite3PagerLockingMode(pPager, eMode);
92616    }
92617
92618    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
92619    if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
92620      zRet = "exclusive";
92621    }
92622    sqlite3VdbeSetNumCols(v, 1);
92623    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
92624    sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
92625    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92626  }else
92627
92628  /*
92629  **  PRAGMA [database.]journal_mode
92630  **  PRAGMA [database.]journal_mode =
92631  **                      (delete|persist|off|truncate|memory|wal|off)
92632  */
92633  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
92634    int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
92635    int ii;           /* Loop counter */
92636
92637    /* Force the schema to be loaded on all databases.  This causes all
92638    ** database files to be opened and the journal_modes set.  This is
92639    ** necessary because subsequent processing must know if the databases
92640    ** are in WAL mode. */
92641    if( sqlite3ReadSchema(pParse) ){
92642      goto pragma_out;
92643    }
92644
92645    sqlite3VdbeSetNumCols(v, 1);
92646    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
92647
92648    if( zRight==0 ){
92649      /* If there is no "=MODE" part of the pragma, do a query for the
92650      ** current mode */
92651      eMode = PAGER_JOURNALMODE_QUERY;
92652    }else{
92653      const char *zMode;
92654      int n = sqlite3Strlen30(zRight);
92655      for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
92656        if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
92657      }
92658      if( !zMode ){
92659        /* If the "=MODE" part does not match any known journal mode,
92660        ** then do a query */
92661        eMode = PAGER_JOURNALMODE_QUERY;
92662      }
92663    }
92664    if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
92665      /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
92666      iDb = 0;
92667      pId2->n = 1;
92668    }
92669    for(ii=db->nDb-1; ii>=0; ii--){
92670      if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
92671        sqlite3VdbeUsesBtree(v, ii);
92672        sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
92673      }
92674    }
92675    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92676  }else
92677
92678  /*
92679  **  PRAGMA [database.]journal_size_limit
92680  **  PRAGMA [database.]journal_size_limit=N
92681  **
92682  ** Get or set the size limit on rollback journal files.
92683  */
92684  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
92685    Pager *pPager = sqlite3BtreePager(pDb->pBt);
92686    i64 iLimit = -2;
92687    if( zRight ){
92688      sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
92689      if( iLimit<-1 ) iLimit = -1;
92690    }
92691    iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
92692    returnSingleInt(pParse, "journal_size_limit", iLimit);
92693  }else
92694
92695#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92696
92697  /*
92698  **  PRAGMA [database.]auto_vacuum
92699  **  PRAGMA [database.]auto_vacuum=N
92700  **
92701  ** Get or set the value of the database 'auto-vacuum' parameter.
92702  ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
92703  */
92704#ifndef SQLITE_OMIT_AUTOVACUUM
92705  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
92706    Btree *pBt = pDb->pBt;
92707    assert( pBt!=0 );
92708    if( sqlite3ReadSchema(pParse) ){
92709      goto pragma_out;
92710    }
92711    if( !zRight ){
92712      int auto_vacuum;
92713      if( ALWAYS(pBt) ){
92714         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
92715      }else{
92716         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
92717      }
92718      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
92719    }else{
92720      int eAuto = getAutoVacuum(zRight);
92721      assert( eAuto>=0 && eAuto<=2 );
92722      db->nextAutovac = (u8)eAuto;
92723      if( ALWAYS(eAuto>=0) ){
92724        /* Call SetAutoVacuum() to set initialize the internal auto and
92725        ** incr-vacuum flags. This is required in case this connection
92726        ** creates the database file. It is important that it is created
92727        ** as an auto-vacuum capable db.
92728        */
92729        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
92730        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
92731          /* When setting the auto_vacuum mode to either "full" or
92732          ** "incremental", write the value of meta[6] in the database
92733          ** file. Before writing to meta[6], check that meta[3] indicates
92734          ** that this really is an auto-vacuum capable database.
92735          */
92736          static const VdbeOpList setMeta6[] = {
92737            { OP_Transaction,    0,         1,                 0},    /* 0 */
92738            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
92739            { OP_If,             1,         0,                 0},    /* 2 */
92740            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
92741            { OP_Integer,        0,         1,                 0},    /* 4 */
92742            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
92743          };
92744          int iAddr;
92745          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
92746          sqlite3VdbeChangeP1(v, iAddr, iDb);
92747          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
92748          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
92749          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
92750          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
92751          sqlite3VdbeUsesBtree(v, iDb);
92752        }
92753      }
92754    }
92755  }else
92756#endif
92757
92758  /*
92759  **  PRAGMA [database.]incremental_vacuum(N)
92760  **
92761  ** Do N steps of incremental vacuuming on a database.
92762  */
92763#ifndef SQLITE_OMIT_AUTOVACUUM
92764  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
92765    int iLimit, addr;
92766    if( sqlite3ReadSchema(pParse) ){
92767      goto pragma_out;
92768    }
92769    if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
92770      iLimit = 0x7fffffff;
92771    }
92772    sqlite3BeginWriteOperation(pParse, 0, iDb);
92773    sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
92774    addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
92775    sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
92776    sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
92777    sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
92778    sqlite3VdbeJumpHere(v, addr);
92779  }else
92780#endif
92781
92782#ifndef SQLITE_OMIT_PAGER_PRAGMAS
92783  /*
92784  **  PRAGMA [database.]cache_size
92785  **  PRAGMA [database.]cache_size=N
92786  **
92787  ** The first form reports the current local setting for the
92788  ** page cache size. The second form sets the local
92789  ** page cache size value.  If N is positive then that is the
92790  ** number of pages in the cache.  If N is negative, then the
92791  ** number of pages is adjusted so that the cache uses -N kibibytes
92792  ** of memory.
92793  */
92794  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
92795    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92796    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92797    if( !zRight ){
92798      returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
92799    }else{
92800      int size = sqlite3Atoi(zRight);
92801      pDb->pSchema->cache_size = size;
92802      sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
92803    }
92804  }else
92805
92806  /*
92807  **   PRAGMA temp_store
92808  **   PRAGMA temp_store = "default"|"memory"|"file"
92809  **
92810  ** Return or set the local value of the temp_store flag.  Changing
92811  ** the local value does not make changes to the disk file and the default
92812  ** value will be restored the next time the database is opened.
92813  **
92814  ** Note that it is possible for the library compile-time options to
92815  ** override this setting
92816  */
92817  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
92818    if( !zRight ){
92819      returnSingleInt(pParse, "temp_store", db->temp_store);
92820    }else{
92821      changeTempStorage(pParse, zRight);
92822    }
92823  }else
92824
92825  /*
92826  **   PRAGMA temp_store_directory
92827  **   PRAGMA temp_store_directory = ""|"directory_name"
92828  **
92829  ** Return or set the local value of the temp_store_directory flag.  Changing
92830  ** the value sets a specific directory to be used for temporary files.
92831  ** Setting to a null string reverts to the default temporary directory search.
92832  ** If temporary directory is changed, then invalidateTempStorage.
92833  **
92834  */
92835  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
92836    if( !zRight ){
92837      if( sqlite3_temp_directory ){
92838        sqlite3VdbeSetNumCols(v, 1);
92839        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
92840            "temp_store_directory", SQLITE_STATIC);
92841        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
92842        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92843      }
92844    }else{
92845#ifndef SQLITE_OMIT_WSD
92846      if( zRight[0] ){
92847        int res;
92848        rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
92849        if( rc!=SQLITE_OK || res==0 ){
92850          sqlite3ErrorMsg(pParse, "not a writable directory");
92851          goto pragma_out;
92852        }
92853      }
92854      if( SQLITE_TEMP_STORE==0
92855       || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
92856       || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
92857      ){
92858        invalidateTempStorage(pParse);
92859      }
92860      sqlite3_free(sqlite3_temp_directory);
92861      if( zRight[0] ){
92862        sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
92863      }else{
92864        sqlite3_temp_directory = 0;
92865      }
92866#endif /* SQLITE_OMIT_WSD */
92867    }
92868  }else
92869
92870#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
92871#  if defined(__APPLE__)
92872#    define SQLITE_ENABLE_LOCKING_STYLE 1
92873#  else
92874#    define SQLITE_ENABLE_LOCKING_STYLE 0
92875#  endif
92876#endif
92877#if SQLITE_ENABLE_LOCKING_STYLE
92878  /*
92879   **   PRAGMA [database.]lock_proxy_file
92880   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
92881   **
92882   ** Return or set the value of the lock_proxy_file flag.  Changing
92883   ** the value sets a specific file to be used for database access locks.
92884   **
92885   */
92886  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
92887    if( !zRight ){
92888      Pager *pPager = sqlite3BtreePager(pDb->pBt);
92889      char *proxy_file_path = NULL;
92890      sqlite3_file *pFile = sqlite3PagerFile(pPager);
92891      sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
92892                           &proxy_file_path);
92893
92894      if( proxy_file_path ){
92895        sqlite3VdbeSetNumCols(v, 1);
92896        sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
92897                              "lock_proxy_file", SQLITE_STATIC);
92898        sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
92899        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
92900      }
92901    }else{
92902      Pager *pPager = sqlite3BtreePager(pDb->pBt);
92903      sqlite3_file *pFile = sqlite3PagerFile(pPager);
92904      int res;
92905      if( zRight[0] ){
92906        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
92907                                     zRight);
92908      } else {
92909        res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
92910                                     NULL);
92911      }
92912      if( res!=SQLITE_OK ){
92913        sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
92914        goto pragma_out;
92915      }
92916    }
92917  }else
92918#endif /* SQLITE_ENABLE_LOCKING_STYLE */
92919
92920  /*
92921  **   PRAGMA [database.]synchronous
92922  **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
92923  **
92924  ** Return or set the local value of the synchronous flag.  Changing
92925  ** the local value does not make changes to the disk file and the
92926  ** default value will be restored the next time the database is
92927  ** opened.
92928  */
92929  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
92930    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92931    if( !zRight ){
92932      returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
92933    }else{
92934      if( !db->autoCommit ){
92935        sqlite3ErrorMsg(pParse,
92936            "Safety level may not be changed inside a transaction");
92937      }else{
92938        pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
92939      }
92940    }
92941  }else
92942#endif /* SQLITE_OMIT_PAGER_PRAGMAS */
92943
92944#ifndef SQLITE_OMIT_FLAG_PRAGMAS
92945  if( flagPragma(pParse, zLeft, zRight) ){
92946    /* The flagPragma() subroutine also generates any necessary code
92947    ** there is nothing more to do here */
92948  }else
92949#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
92950
92951#ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
92952  /*
92953  **   PRAGMA table_info(<table>)
92954  **
92955  ** Return a single row for each column of the named table. The columns of
92956  ** the returned data set are:
92957  **
92958  ** cid:        Column id (numbered from left to right, starting at 0)
92959  ** name:       Column name
92960  ** type:       Column declaration type.
92961  ** notnull:    True if 'NOT NULL' is part of column declaration
92962  ** dflt_value: The default value for the column, if any.
92963  */
92964  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
92965    Table *pTab;
92966    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
92967    pTab = sqlite3FindTable(db, zRight, zDb);
92968    if( pTab ){
92969      int i;
92970      int nHidden = 0;
92971      Column *pCol;
92972      sqlite3VdbeSetNumCols(v, 6);
92973      pParse->nMem = 6;
92974      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
92975      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
92976      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
92977      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
92978      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
92979      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
92980      sqlite3ViewGetColumnNames(pParse, pTab);
92981      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
92982        if( IsHiddenColumn(pCol) ){
92983          nHidden++;
92984          continue;
92985        }
92986        sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
92987        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
92988        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
92989           pCol->zType ? pCol->zType : "", 0);
92990        sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
92991        if( pCol->zDflt ){
92992          sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
92993        }else{
92994          sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
92995        }
92996        sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
92997        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
92998      }
92999    }
93000  }else
93001
93002  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
93003    Index *pIdx;
93004    Table *pTab;
93005    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93006    pIdx = sqlite3FindIndex(db, zRight, zDb);
93007    if( pIdx ){
93008      int i;
93009      pTab = pIdx->pTable;
93010      sqlite3VdbeSetNumCols(v, 3);
93011      pParse->nMem = 3;
93012      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
93013      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
93014      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
93015      for(i=0; i<pIdx->nColumn; i++){
93016        int cnum = pIdx->aiColumn[i];
93017        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93018        sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
93019        assert( pTab->nCol>cnum );
93020        sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
93021        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93022      }
93023    }
93024  }else
93025
93026  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
93027    Index *pIdx;
93028    Table *pTab;
93029    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93030    pTab = sqlite3FindTable(db, zRight, zDb);
93031    if( pTab ){
93032      v = sqlite3GetVdbe(pParse);
93033      pIdx = pTab->pIndex;
93034      if( pIdx ){
93035        int i = 0;
93036        sqlite3VdbeSetNumCols(v, 3);
93037        pParse->nMem = 3;
93038        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93039        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93040        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
93041        while(pIdx){
93042          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93043          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
93044          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
93045          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93046          ++i;
93047          pIdx = pIdx->pNext;
93048        }
93049      }
93050    }
93051  }else
93052
93053  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
93054    int i;
93055    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93056    sqlite3VdbeSetNumCols(v, 3);
93057    pParse->nMem = 3;
93058    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93059    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93060    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
93061    for(i=0; i<db->nDb; i++){
93062      if( db->aDb[i].pBt==0 ) continue;
93063      assert( db->aDb[i].zName!=0 );
93064      sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93065      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
93066      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93067           sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
93068      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93069    }
93070  }else
93071
93072  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
93073    int i = 0;
93074    HashElem *p;
93075    sqlite3VdbeSetNumCols(v, 2);
93076    pParse->nMem = 2;
93077    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
93078    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
93079    for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
93080      CollSeq *pColl = (CollSeq *)sqliteHashData(p);
93081      sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
93082      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
93083      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93084    }
93085  }else
93086#endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
93087
93088#ifndef SQLITE_OMIT_FOREIGN_KEY
93089  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
93090    FKey *pFK;
93091    Table *pTab;
93092    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93093    pTab = sqlite3FindTable(db, zRight, zDb);
93094    if( pTab ){
93095      v = sqlite3GetVdbe(pParse);
93096      pFK = pTab->pFKey;
93097      if( pFK ){
93098        int i = 0;
93099        sqlite3VdbeSetNumCols(v, 8);
93100        pParse->nMem = 8;
93101        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
93102        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
93103        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
93104        sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
93105        sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
93106        sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
93107        sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
93108        sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
93109        while(pFK){
93110          int j;
93111          for(j=0; j<pFK->nCol; j++){
93112            char *zCol = pFK->aCol[j].zCol;
93113            char *zOnDelete = (char *)actionName(pFK->aAction[0]);
93114            char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
93115            sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
93116            sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
93117            sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
93118            sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
93119                              pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
93120            sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
93121            sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
93122            sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
93123            sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
93124            sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
93125          }
93126          ++i;
93127          pFK = pFK->pNextFrom;
93128        }
93129      }
93130    }
93131  }else
93132#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
93133
93134#ifndef NDEBUG
93135  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
93136    if( zRight ){
93137      if( sqlite3GetBoolean(zRight, 0) ){
93138        sqlite3ParserTrace(stderr, "parser: ");
93139      }else{
93140        sqlite3ParserTrace(0, 0);
93141      }
93142    }
93143  }else
93144#endif
93145
93146  /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
93147  ** used will be case sensitive or not depending on the RHS.
93148  */
93149  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
93150    if( zRight ){
93151      sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
93152    }
93153  }else
93154
93155#ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
93156# define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
93157#endif
93158
93159#ifndef SQLITE_OMIT_INTEGRITY_CHECK
93160  /* Pragma "quick_check" is an experimental reduced version of
93161  ** integrity_check designed to detect most database corruption
93162  ** without most of the overhead of a full integrity-check.
93163  */
93164  if( sqlite3StrICmp(zLeft, "integrity_check")==0
93165   || sqlite3StrICmp(zLeft, "quick_check")==0
93166  ){
93167    int i, j, addr, mxErr;
93168
93169    /* Code that appears at the end of the integrity check.  If no error
93170    ** messages have been generated, output OK.  Otherwise output the
93171    ** error message
93172    */
93173    static const VdbeOpList endCode[] = {
93174      { OP_AddImm,      1, 0,        0},    /* 0 */
93175      { OP_IfNeg,       1, 0,        0},    /* 1 */
93176      { OP_String8,     0, 3,        0},    /* 2 */
93177      { OP_ResultRow,   3, 1,        0},
93178    };
93179
93180    int isQuick = (sqlite3Tolower(zLeft[0])=='q');
93181
93182    /* Initialize the VDBE program */
93183    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93184    pParse->nMem = 6;
93185    sqlite3VdbeSetNumCols(v, 1);
93186    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
93187
93188    /* Set the maximum error count */
93189    mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
93190    if( zRight ){
93191      sqlite3GetInt32(zRight, &mxErr);
93192      if( mxErr<=0 ){
93193        mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
93194      }
93195    }
93196    sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
93197
93198    /* Do an integrity check on each database file */
93199    for(i=0; i<db->nDb; i++){
93200      HashElem *x;
93201      Hash *pTbls;
93202      int cnt = 0;
93203
93204      if( OMIT_TEMPDB && i==1 ) continue;
93205
93206      sqlite3CodeVerifySchema(pParse, i);
93207      addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
93208      sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93209      sqlite3VdbeJumpHere(v, addr);
93210
93211      /* Do an integrity check of the B-Tree
93212      **
93213      ** Begin by filling registers 2, 3, ... with the root pages numbers
93214      ** for all tables and indices in the database.
93215      */
93216      assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93217      pTbls = &db->aDb[i].pSchema->tblHash;
93218      for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
93219        Table *pTab = sqliteHashData(x);
93220        Index *pIdx;
93221        sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
93222        cnt++;
93223        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93224          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
93225          cnt++;
93226        }
93227      }
93228
93229      /* Make sure sufficient number of registers have been allocated */
93230      if( pParse->nMem < cnt+4 ){
93231        pParse->nMem = cnt+4;
93232      }
93233
93234      /* Do the b-tree integrity checks */
93235      sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
93236      sqlite3VdbeChangeP5(v, (u8)i);
93237      addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
93238      sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
93239         sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
93240         P4_DYNAMIC);
93241      sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
93242      sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
93243      sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
93244      sqlite3VdbeJumpHere(v, addr);
93245
93246      /* Make sure all the indices are constructed correctly.
93247      */
93248      for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
93249        Table *pTab = sqliteHashData(x);
93250        Index *pIdx;
93251        int loopTop;
93252
93253        if( pTab->pIndex==0 ) continue;
93254        addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
93255        sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93256        sqlite3VdbeJumpHere(v, addr);
93257        sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
93258        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
93259        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
93260        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
93261        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93262          int jmp2;
93263          int r1;
93264          static const VdbeOpList idxErr[] = {
93265            { OP_AddImm,      1, -1,  0},
93266            { OP_String8,     0,  3,  0},    /* 1 */
93267            { OP_Rowid,       1,  4,  0},
93268            { OP_String8,     0,  5,  0},    /* 3 */
93269            { OP_String8,     0,  6,  0},    /* 4 */
93270            { OP_Concat,      4,  3,  3},
93271            { OP_Concat,      5,  3,  3},
93272            { OP_Concat,      6,  3,  3},
93273            { OP_ResultRow,   3,  1,  0},
93274            { OP_IfPos,       1,  0,  0},    /* 9 */
93275            { OP_Halt,        0,  0,  0},
93276          };
93277          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
93278          jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
93279          addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
93280          sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
93281          sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
93282          sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
93283          sqlite3VdbeJumpHere(v, addr+9);
93284          sqlite3VdbeJumpHere(v, jmp2);
93285        }
93286        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
93287        sqlite3VdbeJumpHere(v, loopTop);
93288        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
93289          static const VdbeOpList cntIdx[] = {
93290             { OP_Integer,      0,  3,  0},
93291             { OP_Rewind,       0,  0,  0},  /* 1 */
93292             { OP_AddImm,       3,  1,  0},
93293             { OP_Next,         0,  0,  0},  /* 3 */
93294             { OP_Eq,           2,  0,  3},  /* 4 */
93295             { OP_AddImm,       1, -1,  0},
93296             { OP_String8,      0,  2,  0},  /* 6 */
93297             { OP_String8,      0,  3,  0},  /* 7 */
93298             { OP_Concat,       3,  2,  2},
93299             { OP_ResultRow,    2,  1,  0},
93300          };
93301          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
93302          sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
93303          sqlite3VdbeJumpHere(v, addr);
93304          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
93305          sqlite3VdbeChangeP1(v, addr+1, j+2);
93306          sqlite3VdbeChangeP2(v, addr+1, addr+4);
93307          sqlite3VdbeChangeP1(v, addr+3, j+2);
93308          sqlite3VdbeChangeP2(v, addr+3, addr+2);
93309          sqlite3VdbeJumpHere(v, addr+4);
93310          sqlite3VdbeChangeP4(v, addr+6,
93311                     "wrong # of entries in index ", P4_STATIC);
93312          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
93313        }
93314      }
93315    }
93316    addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
93317    sqlite3VdbeChangeP2(v, addr, -mxErr);
93318    sqlite3VdbeJumpHere(v, addr+1);
93319    sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
93320  }else
93321#endif /* SQLITE_OMIT_INTEGRITY_CHECK */
93322
93323#ifndef SQLITE_OMIT_UTF16
93324  /*
93325  **   PRAGMA encoding
93326  **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
93327  **
93328  ** In its first form, this pragma returns the encoding of the main
93329  ** database. If the database is not initialized, it is initialized now.
93330  **
93331  ** The second form of this pragma is a no-op if the main database file
93332  ** has not already been initialized. In this case it sets the default
93333  ** encoding that will be used for the main database file if a new file
93334  ** is created. If an existing main database file is opened, then the
93335  ** default text encoding for the existing database is used.
93336  **
93337  ** In all cases new databases created using the ATTACH command are
93338  ** created to use the same default text encoding as the main database. If
93339  ** the main database has not been initialized and/or created when ATTACH
93340  ** is executed, this is done before the ATTACH operation.
93341  **
93342  ** In the second form this pragma sets the text encoding to be used in
93343  ** new database files created using this database handle. It is only
93344  ** useful if invoked immediately after the main database i
93345  */
93346  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
93347    static const struct EncName {
93348      char *zName;
93349      u8 enc;
93350    } encnames[] = {
93351      { "UTF8",     SQLITE_UTF8        },
93352      { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
93353      { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
93354      { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
93355      { "UTF16le",  SQLITE_UTF16LE     },
93356      { "UTF16be",  SQLITE_UTF16BE     },
93357      { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
93358      { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
93359      { 0, 0 }
93360    };
93361    const struct EncName *pEnc;
93362    if( !zRight ){    /* "PRAGMA encoding" */
93363      if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93364      sqlite3VdbeSetNumCols(v, 1);
93365      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
93366      sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
93367      assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
93368      assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
93369      assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
93370      sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
93371      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93372    }else{                        /* "PRAGMA encoding = XXX" */
93373      /* Only change the value of sqlite.enc if the database handle is not
93374      ** initialized. If the main database exists, the new sqlite.enc value
93375      ** will be overwritten when the schema is next loaded. If it does not
93376      ** already exists, it will be created to use the new encoding value.
93377      */
93378      if(
93379        !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
93380        DbHasProperty(db, 0, DB_Empty)
93381      ){
93382        for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
93383          if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
93384            ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
93385            break;
93386          }
93387        }
93388        if( !pEnc->zName ){
93389          sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
93390        }
93391      }
93392    }
93393  }else
93394#endif /* SQLITE_OMIT_UTF16 */
93395
93396#ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
93397  /*
93398  **   PRAGMA [database.]schema_version
93399  **   PRAGMA [database.]schema_version = <integer>
93400  **
93401  **   PRAGMA [database.]user_version
93402  **   PRAGMA [database.]user_version = <integer>
93403  **
93404  ** The pragma's schema_version and user_version are used to set or get
93405  ** the value of the schema-version and user-version, respectively. Both
93406  ** the schema-version and the user-version are 32-bit signed integers
93407  ** stored in the database header.
93408  **
93409  ** The schema-cookie is usually only manipulated internally by SQLite. It
93410  ** is incremented by SQLite whenever the database schema is modified (by
93411  ** creating or dropping a table or index). The schema version is used by
93412  ** SQLite each time a query is executed to ensure that the internal cache
93413  ** of the schema used when compiling the SQL query matches the schema of
93414  ** the database against which the compiled query is actually executed.
93415  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
93416  ** the schema-version is potentially dangerous and may lead to program
93417  ** crashes or database corruption. Use with caution!
93418  **
93419  ** The user-version is not used internally by SQLite. It may be used by
93420  ** applications for any purpose.
93421  */
93422  if( sqlite3StrICmp(zLeft, "schema_version")==0
93423   || sqlite3StrICmp(zLeft, "user_version")==0
93424   || sqlite3StrICmp(zLeft, "freelist_count")==0
93425  ){
93426    int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
93427    sqlite3VdbeUsesBtree(v, iDb);
93428    switch( zLeft[0] ){
93429      case 'f': case 'F':
93430        iCookie = BTREE_FREE_PAGE_COUNT;
93431        break;
93432      case 's': case 'S':
93433        iCookie = BTREE_SCHEMA_VERSION;
93434        break;
93435      default:
93436        iCookie = BTREE_USER_VERSION;
93437        break;
93438    }
93439
93440    if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
93441      /* Write the specified cookie value */
93442      static const VdbeOpList setCookie[] = {
93443        { OP_Transaction,    0,  1,  0},    /* 0 */
93444        { OP_Integer,        0,  1,  0},    /* 1 */
93445        { OP_SetCookie,      0,  0,  1},    /* 2 */
93446      };
93447      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
93448      sqlite3VdbeChangeP1(v, addr, iDb);
93449      sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
93450      sqlite3VdbeChangeP1(v, addr+2, iDb);
93451      sqlite3VdbeChangeP2(v, addr+2, iCookie);
93452    }else{
93453      /* Read the specified cookie value */
93454      static const VdbeOpList readCookie[] = {
93455        { OP_Transaction,     0,  0,  0},    /* 0 */
93456        { OP_ReadCookie,      0,  1,  0},    /* 1 */
93457        { OP_ResultRow,       1,  1,  0}
93458      };
93459      int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
93460      sqlite3VdbeChangeP1(v, addr, iDb);
93461      sqlite3VdbeChangeP1(v, addr+1, iDb);
93462      sqlite3VdbeChangeP3(v, addr+1, iCookie);
93463      sqlite3VdbeSetNumCols(v, 1);
93464      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
93465    }
93466  }else
93467#endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
93468
93469#ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
93470  /*
93471  **   PRAGMA compile_options
93472  **
93473  ** Return the names of all compile-time options used in this build,
93474  ** one option per row.
93475  */
93476  if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
93477    int i = 0;
93478    const char *zOpt;
93479    sqlite3VdbeSetNumCols(v, 1);
93480    pParse->nMem = 1;
93481    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
93482    while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
93483      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
93484      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93485    }
93486  }else
93487#endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
93488
93489#ifndef SQLITE_OMIT_WAL
93490  /*
93491  **   PRAGMA [database.]wal_checkpoint = passive|full|restart
93492  **
93493  ** Checkpoint the database.
93494  */
93495  if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
93496    int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
93497    int eMode = SQLITE_CHECKPOINT_PASSIVE;
93498    if( zRight ){
93499      if( sqlite3StrICmp(zRight, "full")==0 ){
93500        eMode = SQLITE_CHECKPOINT_FULL;
93501      }else if( sqlite3StrICmp(zRight, "restart")==0 ){
93502        eMode = SQLITE_CHECKPOINT_RESTART;
93503      }
93504    }
93505    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93506    sqlite3VdbeSetNumCols(v, 3);
93507    pParse->nMem = 3;
93508    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
93509    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
93510    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
93511
93512    sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
93513    sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
93514  }else
93515
93516  /*
93517  **   PRAGMA wal_autocheckpoint
93518  **   PRAGMA wal_autocheckpoint = N
93519  **
93520  ** Configure a database connection to automatically checkpoint a database
93521  ** after accumulating N frames in the log. Or query for the current value
93522  ** of N.
93523  */
93524  if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
93525    if( zRight ){
93526      sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
93527    }
93528    returnSingleInt(pParse, "wal_autocheckpoint",
93529       db->xWalCallback==sqlite3WalDefaultHook ?
93530           SQLITE_PTR_TO_INT(db->pWalArg) : 0);
93531  }else
93532#endif
93533
93534  /*
93535  **  PRAGMA shrink_memory
93536  **
93537  ** This pragma attempts to free as much memory as possible from the
93538  ** current database connection.
93539  */
93540  if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
93541    sqlite3_db_release_memory(db);
93542  }else
93543
93544#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
93545  /*
93546  ** Report the current state of file logs for all databases
93547  */
93548  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
93549    static const char *const azLockName[] = {
93550      "unlocked", "shared", "reserved", "pending", "exclusive"
93551    };
93552    int i;
93553    sqlite3VdbeSetNumCols(v, 2);
93554    pParse->nMem = 2;
93555    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
93556    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
93557    for(i=0; i<db->nDb; i++){
93558      Btree *pBt;
93559      Pager *pPager;
93560      const char *zState = "unknown";
93561      int j;
93562      if( db->aDb[i].zName==0 ) continue;
93563      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
93564      pBt = db->aDb[i].pBt;
93565      if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
93566        zState = "closed";
93567      }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
93568                                     SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
93569         zState = azLockName[j];
93570      }
93571      sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
93572      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
93573    }
93574
93575  }else
93576#endif
93577
93578#ifdef SQLITE_HAS_CODEC
93579  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
93580    sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
93581  }else
93582  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
93583    sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
93584  }else
93585  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
93586                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
93587    int i, h1, h2;
93588    char zKey[40];
93589    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
93590      h1 += 9*(1&(h1>>6));
93591      h2 += 9*(1&(h2>>6));
93592      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
93593    }
93594    if( (zLeft[3] & 0xf)==0xb ){
93595      sqlite3_key(db, zKey, i/2);
93596    }else{
93597      sqlite3_rekey(db, zKey, i/2);
93598    }
93599  }else
93600#endif
93601#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
93602  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
93603#ifdef SQLITE_HAS_CODEC
93604    if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
93605      sqlite3_activate_see(&zRight[4]);
93606    }
93607#endif
93608#ifdef SQLITE_ENABLE_CEROD
93609    if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
93610      sqlite3_activate_cerod(&zRight[6]);
93611    }
93612#endif
93613  }else
93614#endif
93615
93616
93617  {/* Empty ELSE clause */}
93618
93619  /*
93620  ** Reset the safety level, in case the fullfsync flag or synchronous
93621  ** setting changed.
93622  */
93623#ifndef SQLITE_OMIT_PAGER_PRAGMAS
93624  if( db->autoCommit ){
93625    sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
93626               (db->flags&SQLITE_FullFSync)!=0,
93627               (db->flags&SQLITE_CkptFullFSync)!=0);
93628  }
93629#endif
93630pragma_out:
93631  sqlite3DbFree(db, zLeft);
93632  sqlite3DbFree(db, zRight);
93633}
93634
93635#endif /* SQLITE_OMIT_PRAGMA */
93636
93637/************** End of pragma.c **********************************************/
93638/************** Begin file prepare.c *****************************************/
93639/*
93640** 2005 May 25
93641**
93642** The author disclaims copyright to this source code.  In place of
93643** a legal notice, here is a blessing:
93644**
93645**    May you do good and not evil.
93646**    May you find forgiveness for yourself and forgive others.
93647**    May you share freely, never taking more than you give.
93648**
93649*************************************************************************
93650** This file contains the implementation of the sqlite3_prepare()
93651** interface, and routines that contribute to loading the database schema
93652** from disk.
93653*/
93654
93655/*
93656** Fill the InitData structure with an error message that indicates
93657** that the database is corrupt.
93658*/
93659static void corruptSchema(
93660  InitData *pData,     /* Initialization context */
93661  const char *zObj,    /* Object being parsed at the point of error */
93662  const char *zExtra   /* Error information */
93663){
93664  sqlite3 *db = pData->db;
93665  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
93666    if( zObj==0 ) zObj = "?";
93667    sqlite3SetString(pData->pzErrMsg, db,
93668      "malformed database schema (%s)", zObj);
93669    if( zExtra ){
93670      *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
93671                                 "%s - %s", *pData->pzErrMsg, zExtra);
93672    }
93673  }
93674  pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
93675}
93676
93677/*
93678** This is the callback routine for the code that initializes the
93679** database.  See sqlite3Init() below for additional information.
93680** This routine is also called from the OP_ParseSchema opcode of the VDBE.
93681**
93682** Each callback contains the following information:
93683**
93684**     argv[0] = name of thing being created
93685**     argv[1] = root page number for table or index. 0 for trigger or view.
93686**     argv[2] = SQL text for the CREATE statement.
93687**
93688*/
93689SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
93690  InitData *pData = (InitData*)pInit;
93691  sqlite3 *db = pData->db;
93692  int iDb = pData->iDb;
93693
93694  assert( argc==3 );
93695  UNUSED_PARAMETER2(NotUsed, argc);
93696  assert( sqlite3_mutex_held(db->mutex) );
93697  DbClearProperty(db, iDb, DB_Empty);
93698  if( db->mallocFailed ){
93699    corruptSchema(pData, argv[0], 0);
93700    return 1;
93701  }
93702
93703  assert( iDb>=0 && iDb<db->nDb );
93704  if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
93705  if( argv[1]==0 ){
93706    corruptSchema(pData, argv[0], 0);
93707  }else if( argv[2] && argv[2][0] ){
93708    /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
93709    ** But because db->init.busy is set to 1, no VDBE code is generated
93710    ** or executed.  All the parser does is build the internal data
93711    ** structures that describe the table, index, or view.
93712    */
93713    int rc;
93714    sqlite3_stmt *pStmt;
93715    TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
93716
93717    assert( db->init.busy );
93718    db->init.iDb = iDb;
93719    db->init.newTnum = sqlite3Atoi(argv[1]);
93720    db->init.orphanTrigger = 0;
93721    TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
93722    rc = db->errCode;
93723    assert( (rc&0xFF)==(rcp&0xFF) );
93724    db->init.iDb = 0;
93725    if( SQLITE_OK!=rc ){
93726      if( db->init.orphanTrigger ){
93727        assert( iDb==1 );
93728      }else{
93729        pData->rc = rc;
93730        if( rc==SQLITE_NOMEM ){
93731          db->mallocFailed = 1;
93732        }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
93733          corruptSchema(pData, argv[0], sqlite3_errmsg(db));
93734        }
93735      }
93736    }
93737    sqlite3_finalize(pStmt);
93738  }else if( argv[0]==0 ){
93739    corruptSchema(pData, 0, 0);
93740  }else{
93741    /* If the SQL column is blank it means this is an index that
93742    ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
93743    ** constraint for a CREATE TABLE.  The index should have already
93744    ** been created when we processed the CREATE TABLE.  All we have
93745    ** to do here is record the root page number for that index.
93746    */
93747    Index *pIndex;
93748    pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
93749    if( pIndex==0 ){
93750      /* This can occur if there exists an index on a TEMP table which
93751      ** has the same name as another index on a permanent index.  Since
93752      ** the permanent table is hidden by the TEMP table, we can also
93753      ** safely ignore the index on the permanent table.
93754      */
93755      /* Do Nothing */;
93756    }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
93757      corruptSchema(pData, argv[0], "invalid rootpage");
93758    }
93759  }
93760  return 0;
93761}
93762
93763/*
93764** Attempt to read the database schema and initialize internal
93765** data structures for a single database file.  The index of the
93766** database file is given by iDb.  iDb==0 is used for the main
93767** database.  iDb==1 should never be used.  iDb>=2 is used for
93768** auxiliary databases.  Return one of the SQLITE_ error codes to
93769** indicate success or failure.
93770*/
93771static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
93772  int rc;
93773  int i;
93774  int size;
93775  Table *pTab;
93776  Db *pDb;
93777  char const *azArg[4];
93778  int meta[5];
93779  InitData initData;
93780  char const *zMasterSchema;
93781  char const *zMasterName;
93782  int openedTransaction = 0;
93783
93784  /*
93785  ** The master database table has a structure like this
93786  */
93787  static const char master_schema[] =
93788     "CREATE TABLE sqlite_master(\n"
93789     "  type text,\n"
93790     "  name text,\n"
93791     "  tbl_name text,\n"
93792     "  rootpage integer,\n"
93793     "  sql text\n"
93794     ")"
93795  ;
93796#ifndef SQLITE_OMIT_TEMPDB
93797  static const char temp_master_schema[] =
93798     "CREATE TEMP TABLE sqlite_temp_master(\n"
93799     "  type text,\n"
93800     "  name text,\n"
93801     "  tbl_name text,\n"
93802     "  rootpage integer,\n"
93803     "  sql text\n"
93804     ")"
93805  ;
93806#else
93807  #define temp_master_schema 0
93808#endif
93809
93810  assert( iDb>=0 && iDb<db->nDb );
93811  assert( db->aDb[iDb].pSchema );
93812  assert( sqlite3_mutex_held(db->mutex) );
93813  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
93814
93815  /* zMasterSchema and zInitScript are set to point at the master schema
93816  ** and initialisation script appropriate for the database being
93817  ** initialised. zMasterName is the name of the master table.
93818  */
93819  if( !OMIT_TEMPDB && iDb==1 ){
93820    zMasterSchema = temp_master_schema;
93821  }else{
93822    zMasterSchema = master_schema;
93823  }
93824  zMasterName = SCHEMA_TABLE(iDb);
93825
93826  /* Construct the schema tables.  */
93827  azArg[0] = zMasterName;
93828  azArg[1] = "1";
93829  azArg[2] = zMasterSchema;
93830  azArg[3] = 0;
93831  initData.db = db;
93832  initData.iDb = iDb;
93833  initData.rc = SQLITE_OK;
93834  initData.pzErrMsg = pzErrMsg;
93835  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
93836  if( initData.rc ){
93837    rc = initData.rc;
93838    goto error_out;
93839  }
93840  pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
93841  if( ALWAYS(pTab) ){
93842    pTab->tabFlags |= TF_Readonly;
93843  }
93844
93845  /* Create a cursor to hold the database open
93846  */
93847  pDb = &db->aDb[iDb];
93848  if( pDb->pBt==0 ){
93849    if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
93850      DbSetProperty(db, 1, DB_SchemaLoaded);
93851    }
93852    return SQLITE_OK;
93853  }
93854
93855  /* If there is not already a read-only (or read-write) transaction opened
93856  ** on the b-tree database, open one now. If a transaction is opened, it
93857  ** will be closed before this function returns.  */
93858  sqlite3BtreeEnter(pDb->pBt);
93859  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
93860    rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
93861    if( rc!=SQLITE_OK ){
93862      sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
93863      goto initone_error_out;
93864    }
93865    openedTransaction = 1;
93866  }
93867
93868  /* Get the database meta information.
93869  **
93870  ** Meta values are as follows:
93871  **    meta[0]   Schema cookie.  Changes with each schema change.
93872  **    meta[1]   File format of schema layer.
93873  **    meta[2]   Size of the page cache.
93874  **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
93875  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
93876  **    meta[5]   User version
93877  **    meta[6]   Incremental vacuum mode
93878  **    meta[7]   unused
93879  **    meta[8]   unused
93880  **    meta[9]   unused
93881  **
93882  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
93883  ** the possible values of meta[4].
93884  */
93885  for(i=0; i<ArraySize(meta); i++){
93886    sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
93887  }
93888  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
93889
93890  /* If opening a non-empty database, check the text encoding. For the
93891  ** main database, set sqlite3.enc to the encoding of the main database.
93892  ** For an attached db, it is an error if the encoding is not the same
93893  ** as sqlite3.enc.
93894  */
93895  if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
93896    if( iDb==0 ){
93897      u8 encoding;
93898      /* If opening the main database, set ENC(db). */
93899      encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
93900      if( encoding==0 ) encoding = SQLITE_UTF8;
93901      ENC(db) = encoding;
93902      db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
93903    }else{
93904      /* If opening an attached database, the encoding much match ENC(db) */
93905      if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
93906        sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
93907            " text encoding as main database");
93908        rc = SQLITE_ERROR;
93909        goto initone_error_out;
93910      }
93911    }
93912  }else{
93913    DbSetProperty(db, iDb, DB_Empty);
93914  }
93915  pDb->pSchema->enc = ENC(db);
93916
93917  if( pDb->pSchema->cache_size==0 ){
93918#ifndef SQLITE_OMIT_DEPRECATED
93919    size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
93920    if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
93921    pDb->pSchema->cache_size = size;
93922#else
93923    pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
93924#endif
93925    sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93926  }
93927
93928  /*
93929  ** file_format==1    Version 3.0.0.
93930  ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
93931  ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
93932  ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
93933  */
93934  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
93935  if( pDb->pSchema->file_format==0 ){
93936    pDb->pSchema->file_format = 1;
93937  }
93938  if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
93939    sqlite3SetString(pzErrMsg, db, "unsupported file format");
93940    rc = SQLITE_ERROR;
93941    goto initone_error_out;
93942  }
93943
93944  /* Ticket #2804:  When we open a database in the newer file format,
93945  ** clear the legacy_file_format pragma flag so that a VACUUM will
93946  ** not downgrade the database and thus invalidate any descending
93947  ** indices that the user might have created.
93948  */
93949  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
93950    db->flags &= ~SQLITE_LegacyFileFmt;
93951  }
93952
93953  /* Read the schema information out of the schema tables
93954  */
93955  assert( db->init.busy );
93956  {
93957    char *zSql;
93958    zSql = sqlite3MPrintf(db,
93959        "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
93960        db->aDb[iDb].zName, zMasterName);
93961#ifndef SQLITE_OMIT_AUTHORIZATION
93962    {
93963      int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
93964      xAuth = db->xAuth;
93965      db->xAuth = 0;
93966#endif
93967      rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
93968#ifndef SQLITE_OMIT_AUTHORIZATION
93969      db->xAuth = xAuth;
93970    }
93971#endif
93972    if( rc==SQLITE_OK ) rc = initData.rc;
93973    sqlite3DbFree(db, zSql);
93974#ifndef SQLITE_OMIT_ANALYZE
93975    if( rc==SQLITE_OK ){
93976      sqlite3AnalysisLoad(db, iDb);
93977    }
93978#endif
93979  }
93980  if( db->mallocFailed ){
93981    rc = SQLITE_NOMEM;
93982    sqlite3ResetInternalSchema(db, -1);
93983  }
93984  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
93985    /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
93986    ** the schema loaded, even if errors occurred. In this situation the
93987    ** current sqlite3_prepare() operation will fail, but the following one
93988    ** will attempt to compile the supplied statement against whatever subset
93989    ** of the schema was loaded before the error occurred. The primary
93990    ** purpose of this is to allow access to the sqlite_master table
93991    ** even when its contents have been corrupted.
93992    */
93993    DbSetProperty(db, iDb, DB_SchemaLoaded);
93994    rc = SQLITE_OK;
93995  }
93996
93997  /* Jump here for an error that occurs after successfully allocating
93998  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
93999  ** before that point, jump to error_out.
94000  */
94001initone_error_out:
94002  if( openedTransaction ){
94003    sqlite3BtreeCommit(pDb->pBt);
94004  }
94005  sqlite3BtreeLeave(pDb->pBt);
94006
94007error_out:
94008  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
94009    db->mallocFailed = 1;
94010  }
94011  return rc;
94012}
94013
94014/*
94015** Initialize all database files - the main database file, the file
94016** used to store temporary tables, and any additional database files
94017** created using ATTACH statements.  Return a success code.  If an
94018** error occurs, write an error message into *pzErrMsg.
94019**
94020** After a database is initialized, the DB_SchemaLoaded bit is set
94021** bit is set in the flags field of the Db structure. If the database
94022** file was of zero-length, then the DB_Empty flag is also set.
94023*/
94024SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
94025  int i, rc;
94026  int commit_internal = !(db->flags&SQLITE_InternChanges);
94027
94028  assert( sqlite3_mutex_held(db->mutex) );
94029  rc = SQLITE_OK;
94030  db->init.busy = 1;
94031  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
94032    if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
94033    rc = sqlite3InitOne(db, i, pzErrMsg);
94034    if( rc ){
94035      sqlite3ResetInternalSchema(db, i);
94036    }
94037  }
94038
94039  /* Once all the other databases have been initialised, load the schema
94040  ** for the TEMP database. This is loaded last, as the TEMP database
94041  ** schema may contain references to objects in other databases.
94042  */
94043#ifndef SQLITE_OMIT_TEMPDB
94044  if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
94045                    && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
94046    rc = sqlite3InitOne(db, 1, pzErrMsg);
94047    if( rc ){
94048      sqlite3ResetInternalSchema(db, 1);
94049    }
94050  }
94051#endif
94052
94053  db->init.busy = 0;
94054  if( rc==SQLITE_OK && commit_internal ){
94055    sqlite3CommitInternalChanges(db);
94056  }
94057
94058  return rc;
94059}
94060
94061/*
94062** This routine is a no-op if the database schema is already initialised.
94063** Otherwise, the schema is loaded. An error code is returned.
94064*/
94065SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
94066  int rc = SQLITE_OK;
94067  sqlite3 *db = pParse->db;
94068  assert( sqlite3_mutex_held(db->mutex) );
94069  if( !db->init.busy ){
94070    rc = sqlite3Init(db, &pParse->zErrMsg);
94071  }
94072  if( rc!=SQLITE_OK ){
94073    pParse->rc = rc;
94074    pParse->nErr++;
94075  }
94076  return rc;
94077}
94078
94079
94080/*
94081** Check schema cookies in all databases.  If any cookie is out
94082** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
94083** make no changes to pParse->rc.
94084*/
94085static void schemaIsValid(Parse *pParse){
94086  sqlite3 *db = pParse->db;
94087  int iDb;
94088  int rc;
94089  int cookie;
94090
94091  assert( pParse->checkSchema );
94092  assert( sqlite3_mutex_held(db->mutex) );
94093  for(iDb=0; iDb<db->nDb; iDb++){
94094    int openedTransaction = 0;         /* True if a transaction is opened */
94095    Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
94096    if( pBt==0 ) continue;
94097
94098    /* If there is not already a read-only (or read-write) transaction opened
94099    ** on the b-tree database, open one now. If a transaction is opened, it
94100    ** will be closed immediately after reading the meta-value. */
94101    if( !sqlite3BtreeIsInReadTrans(pBt) ){
94102      rc = sqlite3BtreeBeginTrans(pBt, 0);
94103      if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
94104        db->mallocFailed = 1;
94105      }
94106      if( rc!=SQLITE_OK ) return;
94107      openedTransaction = 1;
94108    }
94109
94110    /* Read the schema cookie from the database. If it does not match the
94111    ** value stored as part of the in-memory schema representation,
94112    ** set Parse.rc to SQLITE_SCHEMA. */
94113    sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
94114    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94115    if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
94116      sqlite3ResetInternalSchema(db, iDb);
94117      pParse->rc = SQLITE_SCHEMA;
94118    }
94119
94120    /* Close the transaction, if one was opened. */
94121    if( openedTransaction ){
94122      sqlite3BtreeCommit(pBt);
94123    }
94124  }
94125}
94126
94127/*
94128** Convert a schema pointer into the iDb index that indicates
94129** which database file in db->aDb[] the schema refers to.
94130**
94131** If the same database is attached more than once, the first
94132** attached database is returned.
94133*/
94134SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
94135  int i = -1000000;
94136
94137  /* If pSchema is NULL, then return -1000000. This happens when code in
94138  ** expr.c is trying to resolve a reference to a transient table (i.e. one
94139  ** created by a sub-select). In this case the return value of this
94140  ** function should never be used.
94141  **
94142  ** We return -1000000 instead of the more usual -1 simply because using
94143  ** -1000000 as the incorrect index into db->aDb[] is much
94144  ** more likely to cause a segfault than -1 (of course there are assert()
94145  ** statements too, but it never hurts to play the odds).
94146  */
94147  assert( sqlite3_mutex_held(db->mutex) );
94148  if( pSchema ){
94149    for(i=0; ALWAYS(i<db->nDb); i++){
94150      if( db->aDb[i].pSchema==pSchema ){
94151        break;
94152      }
94153    }
94154    assert( i>=0 && i<db->nDb );
94155  }
94156  return i;
94157}
94158
94159/*
94160** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
94161*/
94162static int sqlite3Prepare(
94163  sqlite3 *db,              /* Database handle. */
94164  const char *zSql,         /* UTF-8 encoded SQL statement. */
94165  int nBytes,               /* Length of zSql in bytes. */
94166  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
94167  Vdbe *pReprepare,         /* VM being reprepared */
94168  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94169  const char **pzTail       /* OUT: End of parsed string */
94170){
94171  Parse *pParse;            /* Parsing context */
94172  char *zErrMsg = 0;        /* Error message */
94173  int rc = SQLITE_OK;       /* Result code */
94174  int i;                    /* Loop counter */
94175
94176  /* Allocate the parsing context */
94177  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
94178  if( pParse==0 ){
94179    rc = SQLITE_NOMEM;
94180    goto end_prepare;
94181  }
94182  pParse->pReprepare = pReprepare;
94183  assert( ppStmt && *ppStmt==0 );
94184  assert( !db->mallocFailed );
94185  assert( sqlite3_mutex_held(db->mutex) );
94186
94187  /* Check to verify that it is possible to get a read lock on all
94188  ** database schemas.  The inability to get a read lock indicates that
94189  ** some other database connection is holding a write-lock, which in
94190  ** turn means that the other connection has made uncommitted changes
94191  ** to the schema.
94192  **
94193  ** Were we to proceed and prepare the statement against the uncommitted
94194  ** schema changes and if those schema changes are subsequently rolled
94195  ** back and different changes are made in their place, then when this
94196  ** prepared statement goes to run the schema cookie would fail to detect
94197  ** the schema change.  Disaster would follow.
94198  **
94199  ** This thread is currently holding mutexes on all Btrees (because
94200  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
94201  ** is not possible for another thread to start a new schema change
94202  ** while this routine is running.  Hence, we do not need to hold
94203  ** locks on the schema, we just need to make sure nobody else is
94204  ** holding them.
94205  **
94206  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
94207  ** but it does *not* override schema lock detection, so this all still
94208  ** works even if READ_UNCOMMITTED is set.
94209  */
94210  for(i=0; i<db->nDb; i++) {
94211    Btree *pBt = db->aDb[i].pBt;
94212    if( pBt ){
94213      assert( sqlite3BtreeHoldsMutex(pBt) );
94214      rc = sqlite3BtreeSchemaLocked(pBt);
94215      if( rc ){
94216        const char *zDb = db->aDb[i].zName;
94217        sqlite3Error(db, rc, "database schema is locked: %s", zDb);
94218        testcase( db->flags & SQLITE_ReadUncommitted );
94219        goto end_prepare;
94220      }
94221    }
94222  }
94223
94224  sqlite3VtabUnlockList(db);
94225
94226  pParse->db = db;
94227  pParse->nQueryLoop = (double)1;
94228  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
94229    char *zSqlCopy;
94230    int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
94231    testcase( nBytes==mxLen );
94232    testcase( nBytes==mxLen+1 );
94233    if( nBytes>mxLen ){
94234      sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
94235      rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
94236      goto end_prepare;
94237    }
94238    zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
94239    if( zSqlCopy ){
94240      sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
94241      sqlite3DbFree(db, zSqlCopy);
94242      pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
94243    }else{
94244      pParse->zTail = &zSql[nBytes];
94245    }
94246  }else{
94247    sqlite3RunParser(pParse, zSql, &zErrMsg);
94248  }
94249  assert( 1==(int)pParse->nQueryLoop );
94250
94251  if( db->mallocFailed ){
94252    pParse->rc = SQLITE_NOMEM;
94253  }
94254  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
94255  if( pParse->checkSchema ){
94256    schemaIsValid(pParse);
94257  }
94258  if( db->mallocFailed ){
94259    pParse->rc = SQLITE_NOMEM;
94260  }
94261  if( pzTail ){
94262    *pzTail = pParse->zTail;
94263  }
94264  rc = pParse->rc;
94265
94266#ifndef SQLITE_OMIT_EXPLAIN
94267  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
94268    static const char * const azColName[] = {
94269       "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
94270       "selectid", "order", "from", "detail"
94271    };
94272    int iFirst, mx;
94273    if( pParse->explain==2 ){
94274      sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
94275      iFirst = 8;
94276      mx = 12;
94277    }else{
94278      sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
94279      iFirst = 0;
94280      mx = 8;
94281    }
94282    for(i=iFirst; i<mx; i++){
94283      sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
94284                            azColName[i], SQLITE_STATIC);
94285    }
94286  }
94287#endif
94288
94289  assert( db->init.busy==0 || saveSqlFlag==0 );
94290  if( db->init.busy==0 ){
94291    Vdbe *pVdbe = pParse->pVdbe;
94292    sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
94293  }
94294  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
94295    sqlite3VdbeFinalize(pParse->pVdbe);
94296    assert(!(*ppStmt));
94297  }else{
94298    *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
94299  }
94300
94301  if( zErrMsg ){
94302    sqlite3Error(db, rc, "%s", zErrMsg);
94303    sqlite3DbFree(db, zErrMsg);
94304  }else{
94305    sqlite3Error(db, rc, 0);
94306  }
94307
94308  /* Delete any TriggerPrg structures allocated while parsing this statement. */
94309  while( pParse->pTriggerPrg ){
94310    TriggerPrg *pT = pParse->pTriggerPrg;
94311    pParse->pTriggerPrg = pT->pNext;
94312    sqlite3DbFree(db, pT);
94313  }
94314
94315end_prepare:
94316
94317  sqlite3StackFree(db, pParse);
94318  rc = sqlite3ApiExit(db, rc);
94319  assert( (rc&db->errMask)==rc );
94320  return rc;
94321}
94322static int sqlite3LockAndPrepare(
94323  sqlite3 *db,              /* Database handle. */
94324  const char *zSql,         /* UTF-8 encoded SQL statement. */
94325  int nBytes,               /* Length of zSql in bytes. */
94326  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
94327  Vdbe *pOld,               /* VM being reprepared */
94328  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94329  const char **pzTail       /* OUT: End of parsed string */
94330){
94331  int rc;
94332  assert( ppStmt!=0 );
94333  *ppStmt = 0;
94334  if( !sqlite3SafetyCheckOk(db) ){
94335    return SQLITE_MISUSE_BKPT;
94336  }
94337  sqlite3_mutex_enter(db->mutex);
94338  sqlite3BtreeEnterAll(db);
94339  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94340  if( rc==SQLITE_SCHEMA ){
94341    sqlite3_finalize(*ppStmt);
94342    rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
94343  }
94344  sqlite3BtreeLeaveAll(db);
94345  sqlite3_mutex_leave(db->mutex);
94346  return rc;
94347}
94348
94349/*
94350** Rerun the compilation of a statement after a schema change.
94351**
94352** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
94353** if the statement cannot be recompiled because another connection has
94354** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
94355** occurs, return SQLITE_SCHEMA.
94356*/
94357SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
94358  int rc;
94359  sqlite3_stmt *pNew;
94360  const char *zSql;
94361  sqlite3 *db;
94362
94363  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
94364  zSql = sqlite3_sql((sqlite3_stmt *)p);
94365  assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
94366  db = sqlite3VdbeDb(p);
94367  assert( sqlite3_mutex_held(db->mutex) );
94368  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
94369  if( rc ){
94370    if( rc==SQLITE_NOMEM ){
94371      db->mallocFailed = 1;
94372    }
94373    assert( pNew==0 );
94374    return rc;
94375  }else{
94376    assert( pNew!=0 );
94377  }
94378  sqlite3VdbeSwap((Vdbe*)pNew, p);
94379  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
94380  sqlite3VdbeResetStepResult((Vdbe*)pNew);
94381  sqlite3VdbeFinalize((Vdbe*)pNew);
94382  return SQLITE_OK;
94383}
94384
94385
94386/*
94387** Two versions of the official API.  Legacy and new use.  In the legacy
94388** version, the original SQL text is not saved in the prepared statement
94389** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94390** sqlite3_step().  In the new version, the original SQL text is retained
94391** and the statement is automatically recompiled if an schema change
94392** occurs.
94393*/
94394SQLITE_API int sqlite3_prepare(
94395  sqlite3 *db,              /* Database handle. */
94396  const char *zSql,         /* UTF-8 encoded SQL statement. */
94397  int nBytes,               /* Length of zSql in bytes. */
94398  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94399  const char **pzTail       /* OUT: End of parsed string */
94400){
94401  int rc;
94402  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
94403  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94404  return rc;
94405}
94406SQLITE_API int sqlite3_prepare_v2(
94407  sqlite3 *db,              /* Database handle. */
94408  const char *zSql,         /* UTF-8 encoded SQL statement. */
94409  int nBytes,               /* Length of zSql in bytes. */
94410  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94411  const char **pzTail       /* OUT: End of parsed string */
94412){
94413  int rc;
94414  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
94415  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94416  return rc;
94417}
94418
94419
94420#ifndef SQLITE_OMIT_UTF16
94421/*
94422** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
94423*/
94424static int sqlite3Prepare16(
94425  sqlite3 *db,              /* Database handle. */
94426  const void *zSql,         /* UTF-16 encoded SQL statement. */
94427  int nBytes,               /* Length of zSql in bytes. */
94428  int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
94429  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94430  const void **pzTail       /* OUT: End of parsed string */
94431){
94432  /* This function currently works by first transforming the UTF-16
94433  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
94434  ** tricky bit is figuring out the pointer to return in *pzTail.
94435  */
94436  char *zSql8;
94437  const char *zTail8 = 0;
94438  int rc = SQLITE_OK;
94439
94440  assert( ppStmt );
94441  *ppStmt = 0;
94442  if( !sqlite3SafetyCheckOk(db) ){
94443    return SQLITE_MISUSE_BKPT;
94444  }
94445  sqlite3_mutex_enter(db->mutex);
94446  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
94447  if( zSql8 ){
94448    rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
94449  }
94450
94451  if( zTail8 && pzTail ){
94452    /* If sqlite3_prepare returns a tail pointer, we calculate the
94453    ** equivalent pointer into the UTF-16 string by counting the unicode
94454    ** characters between zSql8 and zTail8, and then returning a pointer
94455    ** the same number of characters into the UTF-16 string.
94456    */
94457    int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
94458    *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
94459  }
94460  sqlite3DbFree(db, zSql8);
94461  rc = sqlite3ApiExit(db, rc);
94462  sqlite3_mutex_leave(db->mutex);
94463  return rc;
94464}
94465
94466/*
94467** Two versions of the official API.  Legacy and new use.  In the legacy
94468** version, the original SQL text is not saved in the prepared statement
94469** and so if a schema change occurs, SQLITE_SCHEMA is returned by
94470** sqlite3_step().  In the new version, the original SQL text is retained
94471** and the statement is automatically recompiled if an schema change
94472** occurs.
94473*/
94474SQLITE_API int sqlite3_prepare16(
94475  sqlite3 *db,              /* Database handle. */
94476  const void *zSql,         /* UTF-16 encoded SQL statement. */
94477  int nBytes,               /* Length of zSql in bytes. */
94478  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94479  const void **pzTail       /* OUT: End of parsed string */
94480){
94481  int rc;
94482  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
94483  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94484  return rc;
94485}
94486SQLITE_API int sqlite3_prepare16_v2(
94487  sqlite3 *db,              /* Database handle. */
94488  const void *zSql,         /* UTF-16 encoded SQL statement. */
94489  int nBytes,               /* Length of zSql in bytes. */
94490  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
94491  const void **pzTail       /* OUT: End of parsed string */
94492){
94493  int rc;
94494  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
94495  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
94496  return rc;
94497}
94498
94499#endif /* SQLITE_OMIT_UTF16 */
94500
94501/************** End of prepare.c *********************************************/
94502/************** Begin file select.c ******************************************/
94503/*
94504** 2001 September 15
94505**
94506** The author disclaims copyright to this source code.  In place of
94507** a legal notice, here is a blessing:
94508**
94509**    May you do good and not evil.
94510**    May you find forgiveness for yourself and forgive others.
94511**    May you share freely, never taking more than you give.
94512**
94513*************************************************************************
94514** This file contains C code routines that are called by the parser
94515** to handle SELECT statements in SQLite.
94516*/
94517
94518
94519/*
94520** Delete all the content of a Select structure but do not deallocate
94521** the select structure itself.
94522*/
94523static void clearSelect(sqlite3 *db, Select *p){
94524  sqlite3ExprListDelete(db, p->pEList);
94525  sqlite3SrcListDelete(db, p->pSrc);
94526  sqlite3ExprDelete(db, p->pWhere);
94527  sqlite3ExprListDelete(db, p->pGroupBy);
94528  sqlite3ExprDelete(db, p->pHaving);
94529  sqlite3ExprListDelete(db, p->pOrderBy);
94530  sqlite3SelectDelete(db, p->pPrior);
94531  sqlite3ExprDelete(db, p->pLimit);
94532  sqlite3ExprDelete(db, p->pOffset);
94533}
94534
94535/*
94536** Initialize a SelectDest structure.
94537*/
94538SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
94539  pDest->eDest = (u8)eDest;
94540  pDest->iParm = iParm;
94541  pDest->affinity = 0;
94542  pDest->iMem = 0;
94543  pDest->nMem = 0;
94544}
94545
94546
94547/*
94548** Allocate a new Select structure and return a pointer to that
94549** structure.
94550*/
94551SQLITE_PRIVATE Select *sqlite3SelectNew(
94552  Parse *pParse,        /* Parsing context */
94553  ExprList *pEList,     /* which columns to include in the result */
94554  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
94555  Expr *pWhere,         /* the WHERE clause */
94556  ExprList *pGroupBy,   /* the GROUP BY clause */
94557  Expr *pHaving,        /* the HAVING clause */
94558  ExprList *pOrderBy,   /* the ORDER BY clause */
94559  int isDistinct,       /* true if the DISTINCT keyword is present */
94560  Expr *pLimit,         /* LIMIT value.  NULL means not used */
94561  Expr *pOffset         /* OFFSET value.  NULL means no offset */
94562){
94563  Select *pNew;
94564  Select standin;
94565  sqlite3 *db = pParse->db;
94566  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
94567  assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
94568  if( pNew==0 ){
94569    assert( db->mallocFailed );
94570    pNew = &standin;
94571    memset(pNew, 0, sizeof(*pNew));
94572  }
94573  if( pEList==0 ){
94574    pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
94575  }
94576  pNew->pEList = pEList;
94577  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
94578  pNew->pSrc = pSrc;
94579  pNew->pWhere = pWhere;
94580  pNew->pGroupBy = pGroupBy;
94581  pNew->pHaving = pHaving;
94582  pNew->pOrderBy = pOrderBy;
94583  pNew->selFlags = isDistinct ? SF_Distinct : 0;
94584  pNew->op = TK_SELECT;
94585  pNew->pLimit = pLimit;
94586  pNew->pOffset = pOffset;
94587  assert( pOffset==0 || pLimit!=0 );
94588  pNew->addrOpenEphm[0] = -1;
94589  pNew->addrOpenEphm[1] = -1;
94590  pNew->addrOpenEphm[2] = -1;
94591  if( db->mallocFailed ) {
94592    clearSelect(db, pNew);
94593    if( pNew!=&standin ) sqlite3DbFree(db, pNew);
94594    pNew = 0;
94595  }else{
94596    assert( pNew->pSrc!=0 || pParse->nErr>0 );
94597  }
94598  assert( pNew!=&standin );
94599  return pNew;
94600}
94601
94602/*
94603** Delete the given Select structure and all of its substructures.
94604*/
94605SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
94606  if( p ){
94607    clearSelect(db, p);
94608    sqlite3DbFree(db, p);
94609  }
94610}
94611
94612/*
94613** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
94614** type of join.  Return an integer constant that expresses that type
94615** in terms of the following bit values:
94616**
94617**     JT_INNER
94618**     JT_CROSS
94619**     JT_OUTER
94620**     JT_NATURAL
94621**     JT_LEFT
94622**     JT_RIGHT
94623**
94624** A full outer join is the combination of JT_LEFT and JT_RIGHT.
94625**
94626** If an illegal or unsupported join type is seen, then still return
94627** a join type, but put an error in the pParse structure.
94628*/
94629SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
94630  int jointype = 0;
94631  Token *apAll[3];
94632  Token *p;
94633                             /*   0123456789 123456789 123456789 123 */
94634  static const char zKeyText[] = "naturaleftouterightfullinnercross";
94635  static const struct {
94636    u8 i;        /* Beginning of keyword text in zKeyText[] */
94637    u8 nChar;    /* Length of the keyword in characters */
94638    u8 code;     /* Join type mask */
94639  } aKeyword[] = {
94640    /* natural */ { 0,  7, JT_NATURAL                },
94641    /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
94642    /* outer   */ { 10, 5, JT_OUTER                  },
94643    /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
94644    /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
94645    /* inner   */ { 23, 5, JT_INNER                  },
94646    /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
94647  };
94648  int i, j;
94649  apAll[0] = pA;
94650  apAll[1] = pB;
94651  apAll[2] = pC;
94652  for(i=0; i<3 && apAll[i]; i++){
94653    p = apAll[i];
94654    for(j=0; j<ArraySize(aKeyword); j++){
94655      if( p->n==aKeyword[j].nChar
94656          && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
94657        jointype |= aKeyword[j].code;
94658        break;
94659      }
94660    }
94661    testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
94662    if( j>=ArraySize(aKeyword) ){
94663      jointype |= JT_ERROR;
94664      break;
94665    }
94666  }
94667  if(
94668     (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
94669     (jointype & JT_ERROR)!=0
94670  ){
94671    const char *zSp = " ";
94672    assert( pB!=0 );
94673    if( pC==0 ){ zSp++; }
94674    sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
94675       "%T %T%s%T", pA, pB, zSp, pC);
94676    jointype = JT_INNER;
94677  }else if( (jointype & JT_OUTER)!=0
94678         && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
94679    sqlite3ErrorMsg(pParse,
94680      "RIGHT and FULL OUTER JOINs are not currently supported");
94681    jointype = JT_INNER;
94682  }
94683  return jointype;
94684}
94685
94686/*
94687** Return the index of a column in a table.  Return -1 if the column
94688** is not contained in the table.
94689*/
94690static int columnIndex(Table *pTab, const char *zCol){
94691  int i;
94692  for(i=0; i<pTab->nCol; i++){
94693    if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
94694  }
94695  return -1;
94696}
94697
94698/*
94699** Search the first N tables in pSrc, from left to right, looking for a
94700** table that has a column named zCol.
94701**
94702** When found, set *piTab and *piCol to the table index and column index
94703** of the matching column and return TRUE.
94704**
94705** If not found, return FALSE.
94706*/
94707static int tableAndColumnIndex(
94708  SrcList *pSrc,       /* Array of tables to search */
94709  int N,               /* Number of tables in pSrc->a[] to search */
94710  const char *zCol,    /* Name of the column we are looking for */
94711  int *piTab,          /* Write index of pSrc->a[] here */
94712  int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
94713){
94714  int i;               /* For looping over tables in pSrc */
94715  int iCol;            /* Index of column matching zCol */
94716
94717  assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
94718  for(i=0; i<N; i++){
94719    iCol = columnIndex(pSrc->a[i].pTab, zCol);
94720    if( iCol>=0 ){
94721      if( piTab ){
94722        *piTab = i;
94723        *piCol = iCol;
94724      }
94725      return 1;
94726    }
94727  }
94728  return 0;
94729}
94730
94731/*
94732** This function is used to add terms implied by JOIN syntax to the
94733** WHERE clause expression of a SELECT statement. The new term, which
94734** is ANDed with the existing WHERE clause, is of the form:
94735**
94736**    (tab1.col1 = tab2.col2)
94737**
94738** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
94739** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
94740** column iColRight of tab2.
94741*/
94742static void addWhereTerm(
94743  Parse *pParse,                  /* Parsing context */
94744  SrcList *pSrc,                  /* List of tables in FROM clause */
94745  int iLeft,                      /* Index of first table to join in pSrc */
94746  int iColLeft,                   /* Index of column in first table */
94747  int iRight,                     /* Index of second table in pSrc */
94748  int iColRight,                  /* Index of column in second table */
94749  int isOuterJoin,                /* True if this is an OUTER join */
94750  Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
94751){
94752  sqlite3 *db = pParse->db;
94753  Expr *pE1;
94754  Expr *pE2;
94755  Expr *pEq;
94756
94757  assert( iLeft<iRight );
94758  assert( pSrc->nSrc>iRight );
94759  assert( pSrc->a[iLeft].pTab );
94760  assert( pSrc->a[iRight].pTab );
94761
94762  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
94763  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
94764
94765  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
94766  if( pEq && isOuterJoin ){
94767    ExprSetProperty(pEq, EP_FromJoin);
94768    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
94769    ExprSetIrreducible(pEq);
94770    pEq->iRightJoinTable = (i16)pE2->iTable;
94771  }
94772  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
94773}
94774
94775/*
94776** Set the EP_FromJoin property on all terms of the given expression.
94777** And set the Expr.iRightJoinTable to iTable for every term in the
94778** expression.
94779**
94780** The EP_FromJoin property is used on terms of an expression to tell
94781** the LEFT OUTER JOIN processing logic that this term is part of the
94782** join restriction specified in the ON or USING clause and not a part
94783** of the more general WHERE clause.  These terms are moved over to the
94784** WHERE clause during join processing but we need to remember that they
94785** originated in the ON or USING clause.
94786**
94787** The Expr.iRightJoinTable tells the WHERE clause processing that the
94788** expression depends on table iRightJoinTable even if that table is not
94789** explicitly mentioned in the expression.  That information is needed
94790** for cases like this:
94791**
94792**    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
94793**
94794** The where clause needs to defer the handling of the t1.x=5
94795** term until after the t2 loop of the join.  In that way, a
94796** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
94797** defer the handling of t1.x=5, it will be processed immediately
94798** after the t1 loop and rows with t1.x!=5 will never appear in
94799** the output, which is incorrect.
94800*/
94801static void setJoinExpr(Expr *p, int iTable){
94802  while( p ){
94803    ExprSetProperty(p, EP_FromJoin);
94804    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
94805    ExprSetIrreducible(p);
94806    p->iRightJoinTable = (i16)iTable;
94807    setJoinExpr(p->pLeft, iTable);
94808    p = p->pRight;
94809  }
94810}
94811
94812/*
94813** This routine processes the join information for a SELECT statement.
94814** ON and USING clauses are converted into extra terms of the WHERE clause.
94815** NATURAL joins also create extra WHERE clause terms.
94816**
94817** The terms of a FROM clause are contained in the Select.pSrc structure.
94818** The left most table is the first entry in Select.pSrc.  The right-most
94819** table is the last entry.  The join operator is held in the entry to
94820** the left.  Thus entry 0 contains the join operator for the join between
94821** entries 0 and 1.  Any ON or USING clauses associated with the join are
94822** also attached to the left entry.
94823**
94824** This routine returns the number of errors encountered.
94825*/
94826static int sqliteProcessJoin(Parse *pParse, Select *p){
94827  SrcList *pSrc;                  /* All tables in the FROM clause */
94828  int i, j;                       /* Loop counters */
94829  struct SrcList_item *pLeft;     /* Left table being joined */
94830  struct SrcList_item *pRight;    /* Right table being joined */
94831
94832  pSrc = p->pSrc;
94833  pLeft = &pSrc->a[0];
94834  pRight = &pLeft[1];
94835  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
94836    Table *pLeftTab = pLeft->pTab;
94837    Table *pRightTab = pRight->pTab;
94838    int isOuter;
94839
94840    if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
94841    isOuter = (pRight->jointype & JT_OUTER)!=0;
94842
94843    /* When the NATURAL keyword is present, add WHERE clause terms for
94844    ** every column that the two tables have in common.
94845    */
94846    if( pRight->jointype & JT_NATURAL ){
94847      if( pRight->pOn || pRight->pUsing ){
94848        sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
94849           "an ON or USING clause", 0);
94850        return 1;
94851      }
94852      for(j=0; j<pRightTab->nCol; j++){
94853        char *zName;   /* Name of column in the right table */
94854        int iLeft;     /* Matching left table */
94855        int iLeftCol;  /* Matching column in the left table */
94856
94857        zName = pRightTab->aCol[j].zName;
94858        if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
94859          addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
94860                       isOuter, &p->pWhere);
94861        }
94862      }
94863    }
94864
94865    /* Disallow both ON and USING clauses in the same join
94866    */
94867    if( pRight->pOn && pRight->pUsing ){
94868      sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
94869        "clauses in the same join");
94870      return 1;
94871    }
94872
94873    /* Add the ON clause to the end of the WHERE clause, connected by
94874    ** an AND operator.
94875    */
94876    if( pRight->pOn ){
94877      if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
94878      p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
94879      pRight->pOn = 0;
94880    }
94881
94882    /* Create extra terms on the WHERE clause for each column named
94883    ** in the USING clause.  Example: If the two tables to be joined are
94884    ** A and B and the USING clause names X, Y, and Z, then add this
94885    ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
94886    ** Report an error if any column mentioned in the USING clause is
94887    ** not contained in both tables to be joined.
94888    */
94889    if( pRight->pUsing ){
94890      IdList *pList = pRight->pUsing;
94891      for(j=0; j<pList->nId; j++){
94892        char *zName;     /* Name of the term in the USING clause */
94893        int iLeft;       /* Table on the left with matching column name */
94894        int iLeftCol;    /* Column number of matching column on the left */
94895        int iRightCol;   /* Column number of matching column on the right */
94896
94897        zName = pList->a[j].zName;
94898        iRightCol = columnIndex(pRightTab, zName);
94899        if( iRightCol<0
94900         || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
94901        ){
94902          sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
94903            "not present in both tables", zName);
94904          return 1;
94905        }
94906        addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
94907                     isOuter, &p->pWhere);
94908      }
94909    }
94910  }
94911  return 0;
94912}
94913
94914/*
94915** Insert code into "v" that will push the record on the top of the
94916** stack into the sorter.
94917*/
94918static void pushOntoSorter(
94919  Parse *pParse,         /* Parser context */
94920  ExprList *pOrderBy,    /* The ORDER BY clause */
94921  Select *pSelect,       /* The whole SELECT statement */
94922  int regData            /* Register holding data to be sorted */
94923){
94924  Vdbe *v = pParse->pVdbe;
94925  int nExpr = pOrderBy->nExpr;
94926  int regBase = sqlite3GetTempRange(pParse, nExpr+2);
94927  int regRecord = sqlite3GetTempReg(pParse);
94928  int op;
94929  sqlite3ExprCacheClear(pParse);
94930  sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
94931  sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
94932  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
94933  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
94934  if( pSelect->selFlags & SF_UseSorter ){
94935    op = OP_SorterInsert;
94936  }else{
94937    op = OP_IdxInsert;
94938  }
94939  sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
94940  sqlite3ReleaseTempReg(pParse, regRecord);
94941  sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
94942  if( pSelect->iLimit ){
94943    int addr1, addr2;
94944    int iLimit;
94945    if( pSelect->iOffset ){
94946      iLimit = pSelect->iOffset+1;
94947    }else{
94948      iLimit = pSelect->iLimit;
94949    }
94950    addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
94951    sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
94952    addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
94953    sqlite3VdbeJumpHere(v, addr1);
94954    sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
94955    sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
94956    sqlite3VdbeJumpHere(v, addr2);
94957  }
94958}
94959
94960/*
94961** Add code to implement the OFFSET
94962*/
94963static void codeOffset(
94964  Vdbe *v,          /* Generate code into this VM */
94965  Select *p,        /* The SELECT statement being coded */
94966  int iContinue     /* Jump here to skip the current record */
94967){
94968  if( p->iOffset && iContinue!=0 ){
94969    int addr;
94970    sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
94971    addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
94972    sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
94973    VdbeComment((v, "skip OFFSET records"));
94974    sqlite3VdbeJumpHere(v, addr);
94975  }
94976}
94977
94978/*
94979** Add code that will check to make sure the N registers starting at iMem
94980** form a distinct entry.  iTab is a sorting index that holds previously
94981** seen combinations of the N values.  A new entry is made in iTab
94982** if the current N values are new.
94983**
94984** A jump to addrRepeat is made and the N+1 values are popped from the
94985** stack if the top N elements are not distinct.
94986*/
94987static void codeDistinct(
94988  Parse *pParse,     /* Parsing and code generating context */
94989  int iTab,          /* A sorting index used to test for distinctness */
94990  int addrRepeat,    /* Jump to here if not distinct */
94991  int N,             /* Number of elements */
94992  int iMem           /* First element */
94993){
94994  Vdbe *v;
94995  int r1;
94996
94997  v = pParse->pVdbe;
94998  r1 = sqlite3GetTempReg(pParse);
94999  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
95000  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
95001  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
95002  sqlite3ReleaseTempReg(pParse, r1);
95003}
95004
95005#ifndef SQLITE_OMIT_SUBQUERY
95006/*
95007** Generate an error message when a SELECT is used within a subexpression
95008** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
95009** column.  We do this in a subroutine because the error used to occur
95010** in multiple places.  (The error only occurs in one place now, but we
95011** retain the subroutine to minimize code disruption.)
95012*/
95013static int checkForMultiColumnSelectError(
95014  Parse *pParse,       /* Parse context. */
95015  SelectDest *pDest,   /* Destination of SELECT results */
95016  int nExpr            /* Number of result columns returned by SELECT */
95017){
95018  int eDest = pDest->eDest;
95019  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
95020    sqlite3ErrorMsg(pParse, "only a single result allowed for "
95021       "a SELECT that is part of an expression");
95022    return 1;
95023  }else{
95024    return 0;
95025  }
95026}
95027#endif
95028
95029/*
95030** This routine generates the code for the inside of the inner loop
95031** of a SELECT.
95032**
95033** If srcTab and nColumn are both zero, then the pEList expressions
95034** are evaluated in order to get the data for this row.  If nColumn>0
95035** then data is pulled from srcTab and pEList is used only to get the
95036** datatypes for each column.
95037*/
95038static void selectInnerLoop(
95039  Parse *pParse,          /* The parser context */
95040  Select *p,              /* The complete select statement being coded */
95041  ExprList *pEList,       /* List of values being extracted */
95042  int srcTab,             /* Pull data from this table */
95043  int nColumn,            /* Number of columns in the source table */
95044  ExprList *pOrderBy,     /* If not NULL, sort results using this key */
95045  int distinct,           /* If >=0, make sure results are distinct */
95046  SelectDest *pDest,      /* How to dispose of the results */
95047  int iContinue,          /* Jump here to continue with next row */
95048  int iBreak              /* Jump here to break out of the inner loop */
95049){
95050  Vdbe *v = pParse->pVdbe;
95051  int i;
95052  int hasDistinct;        /* True if the DISTINCT keyword is present */
95053  int regResult;              /* Start of memory holding result set */
95054  int eDest = pDest->eDest;   /* How to dispose of results */
95055  int iParm = pDest->iParm;   /* First argument to disposal method */
95056  int nResultCol;             /* Number of result columns */
95057
95058  assert( v );
95059  if( NEVER(v==0) ) return;
95060  assert( pEList!=0 );
95061  hasDistinct = distinct>=0;
95062  if( pOrderBy==0 && !hasDistinct ){
95063    codeOffset(v, p, iContinue);
95064  }
95065
95066  /* Pull the requested columns.
95067  */
95068  if( nColumn>0 ){
95069    nResultCol = nColumn;
95070  }else{
95071    nResultCol = pEList->nExpr;
95072  }
95073  if( pDest->iMem==0 ){
95074    pDest->iMem = pParse->nMem+1;
95075    pDest->nMem = nResultCol;
95076    pParse->nMem += nResultCol;
95077  }else{
95078    assert( pDest->nMem==nResultCol );
95079  }
95080  regResult = pDest->iMem;
95081  if( nColumn>0 ){
95082    for(i=0; i<nColumn; i++){
95083      sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
95084    }
95085  }else if( eDest!=SRT_Exists ){
95086    /* If the destination is an EXISTS(...) expression, the actual
95087    ** values returned by the SELECT are not required.
95088    */
95089    sqlite3ExprCacheClear(pParse);
95090    sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
95091  }
95092  nColumn = nResultCol;
95093
95094  /* If the DISTINCT keyword was present on the SELECT statement
95095  ** and this row has been seen before, then do not make this row
95096  ** part of the result.
95097  */
95098  if( hasDistinct ){
95099    assert( pEList!=0 );
95100    assert( pEList->nExpr==nColumn );
95101    codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
95102    if( pOrderBy==0 ){
95103      codeOffset(v, p, iContinue);
95104    }
95105  }
95106
95107  switch( eDest ){
95108    /* In this mode, write each query result to the key of the temporary
95109    ** table iParm.
95110    */
95111#ifndef SQLITE_OMIT_COMPOUND_SELECT
95112    case SRT_Union: {
95113      int r1;
95114      r1 = sqlite3GetTempReg(pParse);
95115      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95116      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
95117      sqlite3ReleaseTempReg(pParse, r1);
95118      break;
95119    }
95120
95121    /* Construct a record from the query result, but instead of
95122    ** saving that record, use it as a key to delete elements from
95123    ** the temporary table iParm.
95124    */
95125    case SRT_Except: {
95126      sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
95127      break;
95128    }
95129#endif
95130
95131    /* Store the result as data using a unique key.
95132    */
95133    case SRT_Table:
95134    case SRT_EphemTab: {
95135      int r1 = sqlite3GetTempReg(pParse);
95136      testcase( eDest==SRT_Table );
95137      testcase( eDest==SRT_EphemTab );
95138      sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95139      if( pOrderBy ){
95140        pushOntoSorter(pParse, pOrderBy, p, r1);
95141      }else{
95142        int r2 = sqlite3GetTempReg(pParse);
95143        sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
95144        sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
95145        sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95146        sqlite3ReleaseTempReg(pParse, r2);
95147      }
95148      sqlite3ReleaseTempReg(pParse, r1);
95149      break;
95150    }
95151
95152#ifndef SQLITE_OMIT_SUBQUERY
95153    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
95154    ** then there should be a single item on the stack.  Write this
95155    ** item into the set table with bogus data.
95156    */
95157    case SRT_Set: {
95158      assert( nColumn==1 );
95159      p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
95160      if( pOrderBy ){
95161        /* At first glance you would think we could optimize out the
95162        ** ORDER BY in this case since the order of entries in the set
95163        ** does not matter.  But there might be a LIMIT clause, in which
95164        ** case the order does matter */
95165        pushOntoSorter(pParse, pOrderBy, p, regResult);
95166      }else{
95167        int r1 = sqlite3GetTempReg(pParse);
95168        sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
95169        sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
95170        sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
95171        sqlite3ReleaseTempReg(pParse, r1);
95172      }
95173      break;
95174    }
95175
95176    /* If any row exist in the result set, record that fact and abort.
95177    */
95178    case SRT_Exists: {
95179      sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
95180      /* The LIMIT clause will terminate the loop for us */
95181      break;
95182    }
95183
95184    /* If this is a scalar select that is part of an expression, then
95185    ** store the results in the appropriate memory cell and break out
95186    ** of the scan loop.
95187    */
95188    case SRT_Mem: {
95189      assert( nColumn==1 );
95190      if( pOrderBy ){
95191        pushOntoSorter(pParse, pOrderBy, p, regResult);
95192      }else{
95193        sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
95194        /* The LIMIT clause will jump out of the loop for us */
95195      }
95196      break;
95197    }
95198#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
95199
95200    /* Send the data to the callback function or to a subroutine.  In the
95201    ** case of a subroutine, the subroutine itself is responsible for
95202    ** popping the data from the stack.
95203    */
95204    case SRT_Coroutine:
95205    case SRT_Output: {
95206      testcase( eDest==SRT_Coroutine );
95207      testcase( eDest==SRT_Output );
95208      if( pOrderBy ){
95209        int r1 = sqlite3GetTempReg(pParse);
95210        sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
95211        pushOntoSorter(pParse, pOrderBy, p, r1);
95212        sqlite3ReleaseTempReg(pParse, r1);
95213      }else if( eDest==SRT_Coroutine ){
95214        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
95215      }else{
95216        sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
95217        sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
95218      }
95219      break;
95220    }
95221
95222#if !defined(SQLITE_OMIT_TRIGGER)
95223    /* Discard the results.  This is used for SELECT statements inside
95224    ** the body of a TRIGGER.  The purpose of such selects is to call
95225    ** user-defined functions that have side effects.  We do not care
95226    ** about the actual results of the select.
95227    */
95228    default: {
95229      assert( eDest==SRT_Discard );
95230      break;
95231    }
95232#endif
95233  }
95234
95235  /* Jump to the end of the loop if the LIMIT is reached.  Except, if
95236  ** there is a sorter, in which case the sorter has already limited
95237  ** the output for us.
95238  */
95239  if( pOrderBy==0 && p->iLimit ){
95240    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
95241  }
95242}
95243
95244/*
95245** Given an expression list, generate a KeyInfo structure that records
95246** the collating sequence for each expression in that expression list.
95247**
95248** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
95249** KeyInfo structure is appropriate for initializing a virtual index to
95250** implement that clause.  If the ExprList is the result set of a SELECT
95251** then the KeyInfo structure is appropriate for initializing a virtual
95252** index to implement a DISTINCT test.
95253**
95254** Space to hold the KeyInfo structure is obtain from malloc.  The calling
95255** function is responsible for seeing that this structure is eventually
95256** freed.  Add the KeyInfo structure to the P4 field of an opcode using
95257** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
95258*/
95259static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
95260  sqlite3 *db = pParse->db;
95261  int nExpr;
95262  KeyInfo *pInfo;
95263  struct ExprList_item *pItem;
95264  int i;
95265
95266  nExpr = pList->nExpr;
95267  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
95268  if( pInfo ){
95269    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
95270    pInfo->nField = (u16)nExpr;
95271    pInfo->enc = ENC(db);
95272    pInfo->db = db;
95273    for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
95274      CollSeq *pColl;
95275      pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
95276      if( !pColl ){
95277        pColl = db->pDfltColl;
95278      }
95279      pInfo->aColl[i] = pColl;
95280      pInfo->aSortOrder[i] = pItem->sortOrder;
95281    }
95282  }
95283  return pInfo;
95284}
95285
95286#ifndef SQLITE_OMIT_COMPOUND_SELECT
95287/*
95288** Name of the connection operator, used for error messages.
95289*/
95290static const char *selectOpName(int id){
95291  char *z;
95292  switch( id ){
95293    case TK_ALL:       z = "UNION ALL";   break;
95294    case TK_INTERSECT: z = "INTERSECT";   break;
95295    case TK_EXCEPT:    z = "EXCEPT";      break;
95296    default:           z = "UNION";       break;
95297  }
95298  return z;
95299}
95300#endif /* SQLITE_OMIT_COMPOUND_SELECT */
95301
95302#ifndef SQLITE_OMIT_EXPLAIN
95303/*
95304** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95305** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95306** where the caption is of the form:
95307**
95308**   "USE TEMP B-TREE FOR xxx"
95309**
95310** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
95311** is determined by the zUsage argument.
95312*/
95313static void explainTempTable(Parse *pParse, const char *zUsage){
95314  if( pParse->explain==2 ){
95315    Vdbe *v = pParse->pVdbe;
95316    char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
95317    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95318  }
95319}
95320
95321/*
95322** Assign expression b to lvalue a. A second, no-op, version of this macro
95323** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
95324** in sqlite3Select() to assign values to structure member variables that
95325** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
95326** code with #ifndef directives.
95327*/
95328# define explainSetInteger(a, b) a = b
95329
95330#else
95331/* No-op versions of the explainXXX() functions and macros. */
95332# define explainTempTable(y,z)
95333# define explainSetInteger(y,z)
95334#endif
95335
95336#if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
95337/*
95338** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
95339** is a no-op. Otherwise, it adds a single row of output to the EQP result,
95340** where the caption is of one of the two forms:
95341**
95342**   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
95343**   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
95344**
95345** where iSub1 and iSub2 are the integers passed as the corresponding
95346** function parameters, and op is the text representation of the parameter
95347** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
95348** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
95349** false, or the second form if it is true.
95350*/
95351static void explainComposite(
95352  Parse *pParse,                  /* Parse context */
95353  int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
95354  int iSub1,                      /* Subquery id 1 */
95355  int iSub2,                      /* Subquery id 2 */
95356  int bUseTmp                     /* True if a temp table was used */
95357){
95358  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
95359  if( pParse->explain==2 ){
95360    Vdbe *v = pParse->pVdbe;
95361    char *zMsg = sqlite3MPrintf(
95362        pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
95363        bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
95364    );
95365    sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
95366  }
95367}
95368#else
95369/* No-op versions of the explainXXX() functions and macros. */
95370# define explainComposite(v,w,x,y,z)
95371#endif
95372
95373/*
95374** If the inner loop was generated using a non-null pOrderBy argument,
95375** then the results were placed in a sorter.  After the loop is terminated
95376** we need to run the sorter and output the results.  The following
95377** routine generates the code needed to do that.
95378*/
95379static void generateSortTail(
95380  Parse *pParse,    /* Parsing context */
95381  Select *p,        /* The SELECT statement */
95382  Vdbe *v,          /* Generate code into this VDBE */
95383  int nColumn,      /* Number of columns of data */
95384  SelectDest *pDest /* Write the sorted results here */
95385){
95386  int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
95387  int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
95388  int addr;
95389  int iTab;
95390  int pseudoTab = 0;
95391  ExprList *pOrderBy = p->pOrderBy;
95392
95393  int eDest = pDest->eDest;
95394  int iParm = pDest->iParm;
95395
95396  int regRow;
95397  int regRowid;
95398
95399  iTab = pOrderBy->iECursor;
95400  regRow = sqlite3GetTempReg(pParse);
95401  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95402    pseudoTab = pParse->nTab++;
95403    sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
95404    regRowid = 0;
95405  }else{
95406    regRowid = sqlite3GetTempReg(pParse);
95407  }
95408  if( p->selFlags & SF_UseSorter ){
95409    int regSortOut = ++pParse->nMem;
95410    int ptab2 = pParse->nTab++;
95411    sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
95412    addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
95413    codeOffset(v, p, addrContinue);
95414    sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
95415    sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
95416    sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95417  }else{
95418    addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
95419    codeOffset(v, p, addrContinue);
95420    sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
95421  }
95422  switch( eDest ){
95423    case SRT_Table:
95424    case SRT_EphemTab: {
95425      testcase( eDest==SRT_Table );
95426      testcase( eDest==SRT_EphemTab );
95427      sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
95428      sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
95429      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
95430      break;
95431    }
95432#ifndef SQLITE_OMIT_SUBQUERY
95433    case SRT_Set: {
95434      assert( nColumn==1 );
95435      sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
95436      sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
95437      sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
95438      break;
95439    }
95440    case SRT_Mem: {
95441      assert( nColumn==1 );
95442      sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
95443      /* The LIMIT clause will terminate the loop for us */
95444      break;
95445    }
95446#endif
95447    default: {
95448      int i;
95449      assert( eDest==SRT_Output || eDest==SRT_Coroutine );
95450      testcase( eDest==SRT_Output );
95451      testcase( eDest==SRT_Coroutine );
95452      for(i=0; i<nColumn; i++){
95453        assert( regRow!=pDest->iMem+i );
95454        sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
95455        if( i==0 ){
95456          sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
95457        }
95458      }
95459      if( eDest==SRT_Output ){
95460        sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
95461        sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
95462      }else{
95463        sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
95464      }
95465      break;
95466    }
95467  }
95468  sqlite3ReleaseTempReg(pParse, regRow);
95469  sqlite3ReleaseTempReg(pParse, regRowid);
95470
95471  /* The bottom of the loop
95472  */
95473  sqlite3VdbeResolveLabel(v, addrContinue);
95474  if( p->selFlags & SF_UseSorter ){
95475    sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
95476  }else{
95477    sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
95478  }
95479  sqlite3VdbeResolveLabel(v, addrBreak);
95480  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
95481    sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
95482  }
95483}
95484
95485/*
95486** Return a pointer to a string containing the 'declaration type' of the
95487** expression pExpr. The string may be treated as static by the caller.
95488**
95489** The declaration type is the exact datatype definition extracted from the
95490** original CREATE TABLE statement if the expression is a column. The
95491** declaration type for a ROWID field is INTEGER. Exactly when an expression
95492** is considered a column can be complex in the presence of subqueries. The
95493** result-set expression in all of the following SELECT statements is
95494** considered a column by this function.
95495**
95496**   SELECT col FROM tbl;
95497**   SELECT (SELECT col FROM tbl;
95498**   SELECT (SELECT col FROM tbl);
95499**   SELECT abc FROM (SELECT col AS abc FROM tbl);
95500**
95501** The declaration type for any expression other than a column is NULL.
95502*/
95503static const char *columnType(
95504  NameContext *pNC,
95505  Expr *pExpr,
95506  const char **pzOriginDb,
95507  const char **pzOriginTab,
95508  const char **pzOriginCol
95509){
95510  char const *zType = 0;
95511  char const *zOriginDb = 0;
95512  char const *zOriginTab = 0;
95513  char const *zOriginCol = 0;
95514  int j;
95515  if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
95516
95517  switch( pExpr->op ){
95518    case TK_AGG_COLUMN:
95519    case TK_COLUMN: {
95520      /* The expression is a column. Locate the table the column is being
95521      ** extracted from in NameContext.pSrcList. This table may be real
95522      ** database table or a subquery.
95523      */
95524      Table *pTab = 0;            /* Table structure column is extracted from */
95525      Select *pS = 0;             /* Select the column is extracted from */
95526      int iCol = pExpr->iColumn;  /* Index of column in pTab */
95527      testcase( pExpr->op==TK_AGG_COLUMN );
95528      testcase( pExpr->op==TK_COLUMN );
95529      while( pNC && !pTab ){
95530        SrcList *pTabList = pNC->pSrcList;
95531        for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
95532        if( j<pTabList->nSrc ){
95533          pTab = pTabList->a[j].pTab;
95534          pS = pTabList->a[j].pSelect;
95535        }else{
95536          pNC = pNC->pNext;
95537        }
95538      }
95539
95540      if( pTab==0 ){
95541        /* At one time, code such as "SELECT new.x" within a trigger would
95542        ** cause this condition to run.  Since then, we have restructured how
95543        ** trigger code is generated and so this condition is no longer
95544        ** possible. However, it can still be true for statements like
95545        ** the following:
95546        **
95547        **   CREATE TABLE t1(col INTEGER);
95548        **   SELECT (SELECT t1.col) FROM FROM t1;
95549        **
95550        ** when columnType() is called on the expression "t1.col" in the
95551        ** sub-select. In this case, set the column type to NULL, even
95552        ** though it should really be "INTEGER".
95553        **
95554        ** This is not a problem, as the column type of "t1.col" is never
95555        ** used. When columnType() is called on the expression
95556        ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
95557        ** branch below.  */
95558        break;
95559      }
95560
95561      assert( pTab && pExpr->pTab==pTab );
95562      if( pS ){
95563        /* The "table" is actually a sub-select or a view in the FROM clause
95564        ** of the SELECT statement. Return the declaration type and origin
95565        ** data for the result-set column of the sub-select.
95566        */
95567        if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
95568          /* If iCol is less than zero, then the expression requests the
95569          ** rowid of the sub-select or view. This expression is legal (see
95570          ** test case misc2.2.2) - it always evaluates to NULL.
95571          */
95572          NameContext sNC;
95573          Expr *p = pS->pEList->a[iCol].pExpr;
95574          sNC.pSrcList = pS->pSrc;
95575          sNC.pNext = pNC;
95576          sNC.pParse = pNC->pParse;
95577          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
95578        }
95579      }else if( ALWAYS(pTab->pSchema) ){
95580        /* A real table */
95581        assert( !pS );
95582        if( iCol<0 ) iCol = pTab->iPKey;
95583        assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95584        if( iCol<0 ){
95585          zType = "INTEGER";
95586          zOriginCol = "rowid";
95587        }else{
95588          zType = pTab->aCol[iCol].zType;
95589          zOriginCol = pTab->aCol[iCol].zName;
95590        }
95591        zOriginTab = pTab->zName;
95592        if( pNC->pParse ){
95593          int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
95594          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
95595        }
95596      }
95597      break;
95598    }
95599#ifndef SQLITE_OMIT_SUBQUERY
95600    case TK_SELECT: {
95601      /* The expression is a sub-select. Return the declaration type and
95602      ** origin info for the single column in the result set of the SELECT
95603      ** statement.
95604      */
95605      NameContext sNC;
95606      Select *pS = pExpr->x.pSelect;
95607      Expr *p = pS->pEList->a[0].pExpr;
95608      assert( ExprHasProperty(pExpr, EP_xIsSelect) );
95609      sNC.pSrcList = pS->pSrc;
95610      sNC.pNext = pNC;
95611      sNC.pParse = pNC->pParse;
95612      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol);
95613      break;
95614    }
95615#endif
95616  }
95617
95618  if( pzOriginDb ){
95619    assert( pzOriginTab && pzOriginCol );
95620    *pzOriginDb = zOriginDb;
95621    *pzOriginTab = zOriginTab;
95622    *pzOriginCol = zOriginCol;
95623  }
95624  return zType;
95625}
95626
95627/*
95628** Generate code that will tell the VDBE the declaration types of columns
95629** in the result set.
95630*/
95631static void generateColumnTypes(
95632  Parse *pParse,      /* Parser context */
95633  SrcList *pTabList,  /* List of tables */
95634  ExprList *pEList    /* Expressions defining the result set */
95635){
95636#ifndef SQLITE_OMIT_DECLTYPE
95637  Vdbe *v = pParse->pVdbe;
95638  int i;
95639  NameContext sNC;
95640  sNC.pSrcList = pTabList;
95641  sNC.pParse = pParse;
95642  for(i=0; i<pEList->nExpr; i++){
95643    Expr *p = pEList->a[i].pExpr;
95644    const char *zType;
95645#ifdef SQLITE_ENABLE_COLUMN_METADATA
95646    const char *zOrigDb = 0;
95647    const char *zOrigTab = 0;
95648    const char *zOrigCol = 0;
95649    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
95650
95651    /* The vdbe must make its own copy of the column-type and other
95652    ** column specific strings, in case the schema is reset before this
95653    ** virtual machine is deleted.
95654    */
95655    sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
95656    sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
95657    sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
95658#else
95659    zType = columnType(&sNC, p, 0, 0, 0);
95660#endif
95661    sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
95662  }
95663#endif /* SQLITE_OMIT_DECLTYPE */
95664}
95665
95666/*
95667** Generate code that will tell the VDBE the names of columns
95668** in the result set.  This information is used to provide the
95669** azCol[] values in the callback.
95670*/
95671static void generateColumnNames(
95672  Parse *pParse,      /* Parser context */
95673  SrcList *pTabList,  /* List of tables */
95674  ExprList *pEList    /* Expressions defining the result set */
95675){
95676  Vdbe *v = pParse->pVdbe;
95677  int i, j;
95678  sqlite3 *db = pParse->db;
95679  int fullNames, shortNames;
95680
95681#ifndef SQLITE_OMIT_EXPLAIN
95682  /* If this is an EXPLAIN, skip this step */
95683  if( pParse->explain ){
95684    return;
95685  }
95686#endif
95687
95688  if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
95689  pParse->colNamesSet = 1;
95690  fullNames = (db->flags & SQLITE_FullColNames)!=0;
95691  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
95692  sqlite3VdbeSetNumCols(v, pEList->nExpr);
95693  for(i=0; i<pEList->nExpr; i++){
95694    Expr *p;
95695    p = pEList->a[i].pExpr;
95696    if( NEVER(p==0) ) continue;
95697    if( pEList->a[i].zName ){
95698      char *zName = pEList->a[i].zName;
95699      sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
95700    }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
95701      Table *pTab;
95702      char *zCol;
95703      int iCol = p->iColumn;
95704      for(j=0; ALWAYS(j<pTabList->nSrc); j++){
95705        if( pTabList->a[j].iCursor==p->iTable ) break;
95706      }
95707      assert( j<pTabList->nSrc );
95708      pTab = pTabList->a[j].pTab;
95709      if( iCol<0 ) iCol = pTab->iPKey;
95710      assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
95711      if( iCol<0 ){
95712        zCol = "rowid";
95713      }else{
95714        zCol = pTab->aCol[iCol].zName;
95715      }
95716      if( !shortNames && !fullNames ){
95717        sqlite3VdbeSetColName(v, i, COLNAME_NAME,
95718            sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
95719      }else if( fullNames ){
95720        char *zName = 0;
95721        zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
95722        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
95723      }else{
95724        sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
95725      }
95726    }else{
95727      sqlite3VdbeSetColName(v, i, COLNAME_NAME,
95728          sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
95729    }
95730  }
95731  generateColumnTypes(pParse, pTabList, pEList);
95732}
95733
95734/*
95735** Given a an expression list (which is really the list of expressions
95736** that form the result set of a SELECT statement) compute appropriate
95737** column names for a table that would hold the expression list.
95738**
95739** All column names will be unique.
95740**
95741** Only the column names are computed.  Column.zType, Column.zColl,
95742** and other fields of Column are zeroed.
95743**
95744** Return SQLITE_OK on success.  If a memory allocation error occurs,
95745** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
95746*/
95747static int selectColumnsFromExprList(
95748  Parse *pParse,          /* Parsing context */
95749  ExprList *pEList,       /* Expr list from which to derive column names */
95750  int *pnCol,             /* Write the number of columns here */
95751  Column **paCol          /* Write the new column list here */
95752){
95753  sqlite3 *db = pParse->db;   /* Database connection */
95754  int i, j;                   /* Loop counters */
95755  int cnt;                    /* Index added to make the name unique */
95756  Column *aCol, *pCol;        /* For looping over result columns */
95757  int nCol;                   /* Number of columns in the result set */
95758  Expr *p;                    /* Expression for a single result column */
95759  char *zName;                /* Column name */
95760  int nName;                  /* Size of name in zName[] */
95761
95762  *pnCol = nCol = pEList ? pEList->nExpr : 0;
95763  aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
95764  if( aCol==0 ) return SQLITE_NOMEM;
95765  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95766    /* Get an appropriate name for the column
95767    */
95768    p = pEList->a[i].pExpr;
95769    assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
95770               || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
95771    if( (zName = pEList->a[i].zName)!=0 ){
95772      /* If the column contains an "AS <name>" phrase, use <name> as the name */
95773      zName = sqlite3DbStrDup(db, zName);
95774    }else{
95775      Expr *pColExpr = p;  /* The expression that is the result column name */
95776      Table *pTab;         /* Table associated with this expression */
95777      while( pColExpr->op==TK_DOT ){
95778        pColExpr = pColExpr->pRight;
95779        assert( pColExpr!=0 );
95780      }
95781      if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
95782        /* For columns use the column name name */
95783        int iCol = pColExpr->iColumn;
95784        pTab = pColExpr->pTab;
95785        if( iCol<0 ) iCol = pTab->iPKey;
95786        zName = sqlite3MPrintf(db, "%s",
95787                 iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
95788      }else if( pColExpr->op==TK_ID ){
95789        assert( !ExprHasProperty(pColExpr, EP_IntValue) );
95790        zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
95791      }else{
95792        /* Use the original text of the column expression as its name */
95793        zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
95794      }
95795    }
95796    if( db->mallocFailed ){
95797      sqlite3DbFree(db, zName);
95798      break;
95799    }
95800
95801    /* Make sure the column name is unique.  If the name is not unique,
95802    ** append a integer to the name so that it becomes unique.
95803    */
95804    nName = sqlite3Strlen30(zName);
95805    for(j=cnt=0; j<i; j++){
95806      if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
95807        char *zNewName;
95808        zName[nName] = 0;
95809        zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
95810        sqlite3DbFree(db, zName);
95811        zName = zNewName;
95812        j = -1;
95813        if( zName==0 ) break;
95814      }
95815    }
95816    pCol->zName = zName;
95817  }
95818  if( db->mallocFailed ){
95819    for(j=0; j<i; j++){
95820      sqlite3DbFree(db, aCol[j].zName);
95821    }
95822    sqlite3DbFree(db, aCol);
95823    *paCol = 0;
95824    *pnCol = 0;
95825    return SQLITE_NOMEM;
95826  }
95827  return SQLITE_OK;
95828}
95829
95830/*
95831** Add type and collation information to a column list based on
95832** a SELECT statement.
95833**
95834** The column list presumably came from selectColumnNamesFromExprList().
95835** The column list has only names, not types or collations.  This
95836** routine goes through and adds the types and collations.
95837**
95838** This routine requires that all identifiers in the SELECT
95839** statement be resolved.
95840*/
95841static void selectAddColumnTypeAndCollation(
95842  Parse *pParse,        /* Parsing contexts */
95843  int nCol,             /* Number of columns */
95844  Column *aCol,         /* List of columns */
95845  Select *pSelect       /* SELECT used to determine types and collations */
95846){
95847  sqlite3 *db = pParse->db;
95848  NameContext sNC;
95849  Column *pCol;
95850  CollSeq *pColl;
95851  int i;
95852  Expr *p;
95853  struct ExprList_item *a;
95854
95855  assert( pSelect!=0 );
95856  assert( (pSelect->selFlags & SF_Resolved)!=0 );
95857  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
95858  if( db->mallocFailed ) return;
95859  memset(&sNC, 0, sizeof(sNC));
95860  sNC.pSrcList = pSelect->pSrc;
95861  a = pSelect->pEList->a;
95862  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
95863    p = a[i].pExpr;
95864    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
95865    pCol->affinity = sqlite3ExprAffinity(p);
95866    if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
95867    pColl = sqlite3ExprCollSeq(pParse, p);
95868    if( pColl ){
95869      pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
95870    }
95871  }
95872}
95873
95874/*
95875** Given a SELECT statement, generate a Table structure that describes
95876** the result set of that SELECT.
95877*/
95878SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
95879  Table *pTab;
95880  sqlite3 *db = pParse->db;
95881  int savedFlags;
95882
95883  savedFlags = db->flags;
95884  db->flags &= ~SQLITE_FullColNames;
95885  db->flags |= SQLITE_ShortColNames;
95886  sqlite3SelectPrep(pParse, pSelect, 0);
95887  if( pParse->nErr ) return 0;
95888  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
95889  db->flags = savedFlags;
95890  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
95891  if( pTab==0 ){
95892    return 0;
95893  }
95894  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
95895  ** is disabled */
95896  assert( db->lookaside.bEnabled==0 );
95897  pTab->nRef = 1;
95898  pTab->zName = 0;
95899  pTab->nRowEst = 1000000;
95900  selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
95901  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
95902  pTab->iPKey = -1;
95903  if( db->mallocFailed ){
95904    sqlite3DeleteTable(db, pTab);
95905    return 0;
95906  }
95907  return pTab;
95908}
95909
95910/*
95911** Get a VDBE for the given parser context.  Create a new one if necessary.
95912** If an error occurs, return NULL and leave a message in pParse.
95913*/
95914SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
95915  Vdbe *v = pParse->pVdbe;
95916  if( v==0 ){
95917    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
95918#ifndef SQLITE_OMIT_TRACE
95919    if( v ){
95920      sqlite3VdbeAddOp0(v, OP_Trace);
95921    }
95922#endif
95923  }
95924  return v;
95925}
95926
95927
95928/*
95929** Compute the iLimit and iOffset fields of the SELECT based on the
95930** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
95931** that appear in the original SQL statement after the LIMIT and OFFSET
95932** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset
95933** are the integer memory register numbers for counters used to compute
95934** the limit and offset.  If there is no limit and/or offset, then
95935** iLimit and iOffset are negative.
95936**
95937** This routine changes the values of iLimit and iOffset only if
95938** a limit or offset is defined by pLimit and pOffset.  iLimit and
95939** iOffset should have been preset to appropriate default values
95940** (usually but not always -1) prior to calling this routine.
95941** Only if pLimit!=0 or pOffset!=0 do the limit registers get
95942** redefined.  The UNION ALL operator uses this property to force
95943** the reuse of the same limit and offset registers across multiple
95944** SELECT statements.
95945*/
95946static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
95947  Vdbe *v = 0;
95948  int iLimit = 0;
95949  int iOffset;
95950  int addr1, n;
95951  if( p->iLimit ) return;
95952
95953  /*
95954  ** "LIMIT -1" always shows all rows.  There is some
95955  ** contraversy about what the correct behavior should be.
95956  ** The current implementation interprets "LIMIT 0" to mean
95957  ** no rows.
95958  */
95959  sqlite3ExprCacheClear(pParse);
95960  assert( p->pOffset==0 || p->pLimit!=0 );
95961  if( p->pLimit ){
95962    p->iLimit = iLimit = ++pParse->nMem;
95963    v = sqlite3GetVdbe(pParse);
95964    if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
95965    if( sqlite3ExprIsInteger(p->pLimit, &n) ){
95966      sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
95967      VdbeComment((v, "LIMIT counter"));
95968      if( n==0 ){
95969        sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
95970      }else{
95971        if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
95972      }
95973    }else{
95974      sqlite3ExprCode(pParse, p->pLimit, iLimit);
95975      sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
95976      VdbeComment((v, "LIMIT counter"));
95977      sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
95978    }
95979    if( p->pOffset ){
95980      p->iOffset = iOffset = ++pParse->nMem;
95981      pParse->nMem++;   /* Allocate an extra register for limit+offset */
95982      sqlite3ExprCode(pParse, p->pOffset, iOffset);
95983      sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
95984      VdbeComment((v, "OFFSET counter"));
95985      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
95986      sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
95987      sqlite3VdbeJumpHere(v, addr1);
95988      sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
95989      VdbeComment((v, "LIMIT+OFFSET"));
95990      addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
95991      sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
95992      sqlite3VdbeJumpHere(v, addr1);
95993    }
95994  }
95995}
95996
95997#ifndef SQLITE_OMIT_COMPOUND_SELECT
95998/*
95999** Return the appropriate collating sequence for the iCol-th column of
96000** the result set for the compound-select statement "p".  Return NULL if
96001** the column has no default collating sequence.
96002**
96003** The collating sequence for the compound select is taken from the
96004** left-most term of the select that has a collating sequence.
96005*/
96006static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
96007  CollSeq *pRet;
96008  if( p->pPrior ){
96009    pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
96010  }else{
96011    pRet = 0;
96012  }
96013  assert( iCol>=0 );
96014  if( pRet==0 && iCol<p->pEList->nExpr ){
96015    pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
96016  }
96017  return pRet;
96018}
96019#endif /* SQLITE_OMIT_COMPOUND_SELECT */
96020
96021/* Forward reference */
96022static int multiSelectOrderBy(
96023  Parse *pParse,        /* Parsing context */
96024  Select *p,            /* The right-most of SELECTs to be coded */
96025  SelectDest *pDest     /* What to do with query results */
96026);
96027
96028
96029#ifndef SQLITE_OMIT_COMPOUND_SELECT
96030/*
96031** This routine is called to process a compound query form from
96032** two or more separate queries using UNION, UNION ALL, EXCEPT, or
96033** INTERSECT
96034**
96035** "p" points to the right-most of the two queries.  the query on the
96036** left is p->pPrior.  The left query could also be a compound query
96037** in which case this routine will be called recursively.
96038**
96039** The results of the total query are to be written into a destination
96040** of type eDest with parameter iParm.
96041**
96042** Example 1:  Consider a three-way compound SQL statement.
96043**
96044**     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
96045**
96046** This statement is parsed up as follows:
96047**
96048**     SELECT c FROM t3
96049**      |
96050**      `----->  SELECT b FROM t2
96051**                |
96052**                `------>  SELECT a FROM t1
96053**
96054** The arrows in the diagram above represent the Select.pPrior pointer.
96055** So if this routine is called with p equal to the t3 query, then
96056** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
96057**
96058** Notice that because of the way SQLite parses compound SELECTs, the
96059** individual selects always group from left to right.
96060*/
96061static int multiSelect(
96062  Parse *pParse,        /* Parsing context */
96063  Select *p,            /* The right-most of SELECTs to be coded */
96064  SelectDest *pDest     /* What to do with query results */
96065){
96066  int rc = SQLITE_OK;   /* Success code from a subroutine */
96067  Select *pPrior;       /* Another SELECT immediately to our left */
96068  Vdbe *v;              /* Generate code to this VDBE */
96069  SelectDest dest;      /* Alternative data destination */
96070  Select *pDelete = 0;  /* Chain of simple selects to delete */
96071  sqlite3 *db;          /* Database connection */
96072#ifndef SQLITE_OMIT_EXPLAIN
96073  int iSub1;            /* EQP id of left-hand query */
96074  int iSub2;            /* EQP id of right-hand query */
96075#endif
96076
96077  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
96078  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
96079  */
96080  assert( p && p->pPrior );  /* Calling function guarantees this much */
96081  db = pParse->db;
96082  pPrior = p->pPrior;
96083  assert( pPrior->pRightmost!=pPrior );
96084  assert( pPrior->pRightmost==p->pRightmost );
96085  dest = *pDest;
96086  if( pPrior->pOrderBy ){
96087    sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
96088      selectOpName(p->op));
96089    rc = 1;
96090    goto multi_select_end;
96091  }
96092  if( pPrior->pLimit ){
96093    sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
96094      selectOpName(p->op));
96095    rc = 1;
96096    goto multi_select_end;
96097  }
96098
96099  v = sqlite3GetVdbe(pParse);
96100  assert( v!=0 );  /* The VDBE already created by calling function */
96101
96102  /* Create the destination temporary table if necessary
96103  */
96104  if( dest.eDest==SRT_EphemTab ){
96105    assert( p->pEList );
96106    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
96107    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
96108    dest.eDest = SRT_Table;
96109  }
96110
96111  /* Make sure all SELECTs in the statement have the same number of elements
96112  ** in their result sets.
96113  */
96114  assert( p->pEList && pPrior->pEList );
96115  if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
96116    if( p->selFlags & SF_Values ){
96117      sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
96118    }else{
96119      sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
96120        " do not have the same number of result columns", selectOpName(p->op));
96121    }
96122    rc = 1;
96123    goto multi_select_end;
96124  }
96125
96126  /* Compound SELECTs that have an ORDER BY clause are handled separately.
96127  */
96128  if( p->pOrderBy ){
96129    return multiSelectOrderBy(pParse, p, pDest);
96130  }
96131
96132  /* Generate code for the left and right SELECT statements.
96133  */
96134  switch( p->op ){
96135    case TK_ALL: {
96136      int addr = 0;
96137      int nLimit;
96138      assert( !pPrior->pLimit );
96139      pPrior->pLimit = p->pLimit;
96140      pPrior->pOffset = p->pOffset;
96141      explainSetInteger(iSub1, pParse->iNextSelectId);
96142      rc = sqlite3Select(pParse, pPrior, &dest);
96143      p->pLimit = 0;
96144      p->pOffset = 0;
96145      if( rc ){
96146        goto multi_select_end;
96147      }
96148      p->pPrior = 0;
96149      p->iLimit = pPrior->iLimit;
96150      p->iOffset = pPrior->iOffset;
96151      if( p->iLimit ){
96152        addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
96153        VdbeComment((v, "Jump ahead if LIMIT reached"));
96154      }
96155      explainSetInteger(iSub2, pParse->iNextSelectId);
96156      rc = sqlite3Select(pParse, p, &dest);
96157      testcase( rc!=SQLITE_OK );
96158      pDelete = p->pPrior;
96159      p->pPrior = pPrior;
96160      p->nSelectRow += pPrior->nSelectRow;
96161      if( pPrior->pLimit
96162       && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
96163       && p->nSelectRow > (double)nLimit
96164      ){
96165        p->nSelectRow = (double)nLimit;
96166      }
96167      if( addr ){
96168        sqlite3VdbeJumpHere(v, addr);
96169      }
96170      break;
96171    }
96172    case TK_EXCEPT:
96173    case TK_UNION: {
96174      int unionTab;    /* Cursor number of the temporary table holding result */
96175      u8 op = 0;       /* One of the SRT_ operations to apply to self */
96176      int priorOp;     /* The SRT_ operation to apply to prior selects */
96177      Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
96178      int addr;
96179      SelectDest uniondest;
96180
96181      testcase( p->op==TK_EXCEPT );
96182      testcase( p->op==TK_UNION );
96183      priorOp = SRT_Union;
96184      if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
96185        /* We can reuse a temporary table generated by a SELECT to our
96186        ** right.
96187        */
96188        assert( p->pRightmost!=p );  /* Can only happen for leftward elements
96189                                     ** of a 3-way or more compound */
96190        assert( p->pLimit==0 );      /* Not allowed on leftward elements */
96191        assert( p->pOffset==0 );     /* Not allowed on leftward elements */
96192        unionTab = dest.iParm;
96193      }else{
96194        /* We will need to create our own temporary table to hold the
96195        ** intermediate results.
96196        */
96197        unionTab = pParse->nTab++;
96198        assert( p->pOrderBy==0 );
96199        addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
96200        assert( p->addrOpenEphm[0] == -1 );
96201        p->addrOpenEphm[0] = addr;
96202        p->pRightmost->selFlags |= SF_UsesEphemeral;
96203        assert( p->pEList );
96204      }
96205
96206      /* Code the SELECT statements to our left
96207      */
96208      assert( !pPrior->pOrderBy );
96209      sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
96210      explainSetInteger(iSub1, pParse->iNextSelectId);
96211      rc = sqlite3Select(pParse, pPrior, &uniondest);
96212      if( rc ){
96213        goto multi_select_end;
96214      }
96215
96216      /* Code the current SELECT statement
96217      */
96218      if( p->op==TK_EXCEPT ){
96219        op = SRT_Except;
96220      }else{
96221        assert( p->op==TK_UNION );
96222        op = SRT_Union;
96223      }
96224      p->pPrior = 0;
96225      pLimit = p->pLimit;
96226      p->pLimit = 0;
96227      pOffset = p->pOffset;
96228      p->pOffset = 0;
96229      uniondest.eDest = op;
96230      explainSetInteger(iSub2, pParse->iNextSelectId);
96231      rc = sqlite3Select(pParse, p, &uniondest);
96232      testcase( rc!=SQLITE_OK );
96233      /* Query flattening in sqlite3Select() might refill p->pOrderBy.
96234      ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
96235      sqlite3ExprListDelete(db, p->pOrderBy);
96236      pDelete = p->pPrior;
96237      p->pPrior = pPrior;
96238      p->pOrderBy = 0;
96239      if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
96240      sqlite3ExprDelete(db, p->pLimit);
96241      p->pLimit = pLimit;
96242      p->pOffset = pOffset;
96243      p->iLimit = 0;
96244      p->iOffset = 0;
96245
96246      /* Convert the data in the temporary table into whatever form
96247      ** it is that we currently need.
96248      */
96249      assert( unionTab==dest.iParm || dest.eDest!=priorOp );
96250      if( dest.eDest!=priorOp ){
96251        int iCont, iBreak, iStart;
96252        assert( p->pEList );
96253        if( dest.eDest==SRT_Output ){
96254          Select *pFirst = p;
96255          while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96256          generateColumnNames(pParse, 0, pFirst->pEList);
96257        }
96258        iBreak = sqlite3VdbeMakeLabel(v);
96259        iCont = sqlite3VdbeMakeLabel(v);
96260        computeLimitRegisters(pParse, p, iBreak);
96261        sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
96262        iStart = sqlite3VdbeCurrentAddr(v);
96263        selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
96264                        0, -1, &dest, iCont, iBreak);
96265        sqlite3VdbeResolveLabel(v, iCont);
96266        sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
96267        sqlite3VdbeResolveLabel(v, iBreak);
96268        sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
96269      }
96270      break;
96271    }
96272    default: assert( p->op==TK_INTERSECT ); {
96273      int tab1, tab2;
96274      int iCont, iBreak, iStart;
96275      Expr *pLimit, *pOffset;
96276      int addr;
96277      SelectDest intersectdest;
96278      int r1;
96279
96280      /* INTERSECT is different from the others since it requires
96281      ** two temporary tables.  Hence it has its own case.  Begin
96282      ** by allocating the tables we will need.
96283      */
96284      tab1 = pParse->nTab++;
96285      tab2 = pParse->nTab++;
96286      assert( p->pOrderBy==0 );
96287
96288      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
96289      assert( p->addrOpenEphm[0] == -1 );
96290      p->addrOpenEphm[0] = addr;
96291      p->pRightmost->selFlags |= SF_UsesEphemeral;
96292      assert( p->pEList );
96293
96294      /* Code the SELECTs to our left into temporary table "tab1".
96295      */
96296      sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
96297      explainSetInteger(iSub1, pParse->iNextSelectId);
96298      rc = sqlite3Select(pParse, pPrior, &intersectdest);
96299      if( rc ){
96300        goto multi_select_end;
96301      }
96302
96303      /* Code the current SELECT into temporary table "tab2"
96304      */
96305      addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
96306      assert( p->addrOpenEphm[1] == -1 );
96307      p->addrOpenEphm[1] = addr;
96308      p->pPrior = 0;
96309      pLimit = p->pLimit;
96310      p->pLimit = 0;
96311      pOffset = p->pOffset;
96312      p->pOffset = 0;
96313      intersectdest.iParm = tab2;
96314      explainSetInteger(iSub2, pParse->iNextSelectId);
96315      rc = sqlite3Select(pParse, p, &intersectdest);
96316      testcase( rc!=SQLITE_OK );
96317      pDelete = p->pPrior;
96318      p->pPrior = pPrior;
96319      if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96320      sqlite3ExprDelete(db, p->pLimit);
96321      p->pLimit = pLimit;
96322      p->pOffset = pOffset;
96323
96324      /* Generate code to take the intersection of the two temporary
96325      ** tables.
96326      */
96327      assert( p->pEList );
96328      if( dest.eDest==SRT_Output ){
96329        Select *pFirst = p;
96330        while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96331        generateColumnNames(pParse, 0, pFirst->pEList);
96332      }
96333      iBreak = sqlite3VdbeMakeLabel(v);
96334      iCont = sqlite3VdbeMakeLabel(v);
96335      computeLimitRegisters(pParse, p, iBreak);
96336      sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
96337      r1 = sqlite3GetTempReg(pParse);
96338      iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
96339      sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
96340      sqlite3ReleaseTempReg(pParse, r1);
96341      selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
96342                      0, -1, &dest, iCont, iBreak);
96343      sqlite3VdbeResolveLabel(v, iCont);
96344      sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
96345      sqlite3VdbeResolveLabel(v, iBreak);
96346      sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
96347      sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
96348      break;
96349    }
96350  }
96351
96352  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
96353
96354  /* Compute collating sequences used by
96355  ** temporary tables needed to implement the compound select.
96356  ** Attach the KeyInfo structure to all temporary tables.
96357  **
96358  ** This section is run by the right-most SELECT statement only.
96359  ** SELECT statements to the left always skip this part.  The right-most
96360  ** SELECT might also skip this part if it has no ORDER BY clause and
96361  ** no temp tables are required.
96362  */
96363  if( p->selFlags & SF_UsesEphemeral ){
96364    int i;                        /* Loop counter */
96365    KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
96366    Select *pLoop;                /* For looping through SELECT statements */
96367    CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
96368    int nCol;                     /* Number of columns in result set */
96369
96370    assert( p->pRightmost==p );
96371    nCol = p->pEList->nExpr;
96372    pKeyInfo = sqlite3DbMallocZero(db,
96373                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
96374    if( !pKeyInfo ){
96375      rc = SQLITE_NOMEM;
96376      goto multi_select_end;
96377    }
96378
96379    pKeyInfo->enc = ENC(db);
96380    pKeyInfo->nField = (u16)nCol;
96381
96382    for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
96383      *apColl = multiSelectCollSeq(pParse, p, i);
96384      if( 0==*apColl ){
96385        *apColl = db->pDfltColl;
96386      }
96387    }
96388
96389    for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
96390      for(i=0; i<2; i++){
96391        int addr = pLoop->addrOpenEphm[i];
96392        if( addr<0 ){
96393          /* If [0] is unused then [1] is also unused.  So we can
96394          ** always safely abort as soon as the first unused slot is found */
96395          assert( pLoop->addrOpenEphm[1]<0 );
96396          break;
96397        }
96398        sqlite3VdbeChangeP2(v, addr, nCol);
96399        sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
96400        pLoop->addrOpenEphm[i] = -1;
96401      }
96402    }
96403    sqlite3DbFree(db, pKeyInfo);
96404  }
96405
96406multi_select_end:
96407  pDest->iMem = dest.iMem;
96408  pDest->nMem = dest.nMem;
96409  sqlite3SelectDelete(db, pDelete);
96410  return rc;
96411}
96412#endif /* SQLITE_OMIT_COMPOUND_SELECT */
96413
96414/*
96415** Code an output subroutine for a coroutine implementation of a
96416** SELECT statment.
96417**
96418** The data to be output is contained in pIn->iMem.  There are
96419** pIn->nMem columns to be output.  pDest is where the output should
96420** be sent.
96421**
96422** regReturn is the number of the register holding the subroutine
96423** return address.
96424**
96425** If regPrev>0 then it is the first register in a vector that
96426** records the previous output.  mem[regPrev] is a flag that is false
96427** if there has been no previous output.  If regPrev>0 then code is
96428** generated to suppress duplicates.  pKeyInfo is used for comparing
96429** keys.
96430**
96431** If the LIMIT found in p->iLimit is reached, jump immediately to
96432** iBreak.
96433*/
96434static int generateOutputSubroutine(
96435  Parse *pParse,          /* Parsing context */
96436  Select *p,              /* The SELECT statement */
96437  SelectDest *pIn,        /* Coroutine supplying data */
96438  SelectDest *pDest,      /* Where to send the data */
96439  int regReturn,          /* The return address register */
96440  int regPrev,            /* Previous result register.  No uniqueness if 0 */
96441  KeyInfo *pKeyInfo,      /* For comparing with previous entry */
96442  int p4type,             /* The p4 type for pKeyInfo */
96443  int iBreak              /* Jump here if we hit the LIMIT */
96444){
96445  Vdbe *v = pParse->pVdbe;
96446  int iContinue;
96447  int addr;
96448
96449  addr = sqlite3VdbeCurrentAddr(v);
96450  iContinue = sqlite3VdbeMakeLabel(v);
96451
96452  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
96453  */
96454  if( regPrev ){
96455    int j1, j2;
96456    j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
96457    j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
96458                              (char*)pKeyInfo, p4type);
96459    sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
96460    sqlite3VdbeJumpHere(v, j1);
96461    sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
96462    sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
96463  }
96464  if( pParse->db->mallocFailed ) return 0;
96465
96466  /* Suppress the the first OFFSET entries if there is an OFFSET clause
96467  */
96468  codeOffset(v, p, iContinue);
96469
96470  switch( pDest->eDest ){
96471    /* Store the result as data using a unique key.
96472    */
96473    case SRT_Table:
96474    case SRT_EphemTab: {
96475      int r1 = sqlite3GetTempReg(pParse);
96476      int r2 = sqlite3GetTempReg(pParse);
96477      testcase( pDest->eDest==SRT_Table );
96478      testcase( pDest->eDest==SRT_EphemTab );
96479      sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
96480      sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
96481      sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
96482      sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96483      sqlite3ReleaseTempReg(pParse, r2);
96484      sqlite3ReleaseTempReg(pParse, r1);
96485      break;
96486    }
96487
96488#ifndef SQLITE_OMIT_SUBQUERY
96489    /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96490    ** then there should be a single item on the stack.  Write this
96491    ** item into the set table with bogus data.
96492    */
96493    case SRT_Set: {
96494      int r1;
96495      assert( pIn->nMem==1 );
96496      p->affinity =
96497         sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
96498      r1 = sqlite3GetTempReg(pParse);
96499      sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
96500      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
96501      sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
96502      sqlite3ReleaseTempReg(pParse, r1);
96503      break;
96504    }
96505
96506#if 0  /* Never occurs on an ORDER BY query */
96507    /* If any row exist in the result set, record that fact and abort.
96508    */
96509    case SRT_Exists: {
96510      sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
96511      /* The LIMIT clause will terminate the loop for us */
96512      break;
96513    }
96514#endif
96515
96516    /* If this is a scalar select that is part of an expression, then
96517    ** store the results in the appropriate memory cell and break out
96518    ** of the scan loop.
96519    */
96520    case SRT_Mem: {
96521      assert( pIn->nMem==1 );
96522      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
96523      /* The LIMIT clause will jump out of the loop for us */
96524      break;
96525    }
96526#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
96527
96528    /* The results are stored in a sequence of registers
96529    ** starting at pDest->iMem.  Then the co-routine yields.
96530    */
96531    case SRT_Coroutine: {
96532      if( pDest->iMem==0 ){
96533        pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
96534        pDest->nMem = pIn->nMem;
96535      }
96536      sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
96537      sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
96538      break;
96539    }
96540
96541    /* If none of the above, then the result destination must be
96542    ** SRT_Output.  This routine is never called with any other
96543    ** destination other than the ones handled above or SRT_Output.
96544    **
96545    ** For SRT_Output, results are stored in a sequence of registers.
96546    ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
96547    ** return the next row of result.
96548    */
96549    default: {
96550      assert( pDest->eDest==SRT_Output );
96551      sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
96552      sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
96553      break;
96554    }
96555  }
96556
96557  /* Jump to the end of the loop if the LIMIT is reached.
96558  */
96559  if( p->iLimit ){
96560    sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96561  }
96562
96563  /* Generate the subroutine return
96564  */
96565  sqlite3VdbeResolveLabel(v, iContinue);
96566  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
96567
96568  return addr;
96569}
96570
96571/*
96572** Alternative compound select code generator for cases when there
96573** is an ORDER BY clause.
96574**
96575** We assume a query of the following form:
96576**
96577**      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
96578**
96579** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
96580** is to code both <selectA> and <selectB> with the ORDER BY clause as
96581** co-routines.  Then run the co-routines in parallel and merge the results
96582** into the output.  In addition to the two coroutines (called selectA and
96583** selectB) there are 7 subroutines:
96584**
96585**    outA:    Move the output of the selectA coroutine into the output
96586**             of the compound query.
96587**
96588**    outB:    Move the output of the selectB coroutine into the output
96589**             of the compound query.  (Only generated for UNION and
96590**             UNION ALL.  EXCEPT and INSERTSECT never output a row that
96591**             appears only in B.)
96592**
96593**    AltB:    Called when there is data from both coroutines and A<B.
96594**
96595**    AeqB:    Called when there is data from both coroutines and A==B.
96596**
96597**    AgtB:    Called when there is data from both coroutines and A>B.
96598**
96599**    EofA:    Called when data is exhausted from selectA.
96600**
96601**    EofB:    Called when data is exhausted from selectB.
96602**
96603** The implementation of the latter five subroutines depend on which
96604** <operator> is used:
96605**
96606**
96607**             UNION ALL         UNION            EXCEPT          INTERSECT
96608**          -------------  -----------------  --------------  -----------------
96609**   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
96610**
96611**   AeqB:   outA, nextA         nextA             nextA         outA, nextA
96612**
96613**   AgtB:   outB, nextB      outB, nextB          nextB            nextB
96614**
96615**   EofA:   outB, nextB      outB, nextB          halt             halt
96616**
96617**   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
96618**
96619** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
96620** causes an immediate jump to EofA and an EOF on B following nextB causes
96621** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
96622** following nextX causes a jump to the end of the select processing.
96623**
96624** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
96625** within the output subroutine.  The regPrev register set holds the previously
96626** output value.  A comparison is made against this value and the output
96627** is skipped if the next results would be the same as the previous.
96628**
96629** The implementation plan is to implement the two coroutines and seven
96630** subroutines first, then put the control logic at the bottom.  Like this:
96631**
96632**          goto Init
96633**     coA: coroutine for left query (A)
96634**     coB: coroutine for right query (B)
96635**    outA: output one row of A
96636**    outB: output one row of B (UNION and UNION ALL only)
96637**    EofA: ...
96638**    EofB: ...
96639**    AltB: ...
96640**    AeqB: ...
96641**    AgtB: ...
96642**    Init: initialize coroutine registers
96643**          yield coA
96644**          if eof(A) goto EofA
96645**          yield coB
96646**          if eof(B) goto EofB
96647**    Cmpr: Compare A, B
96648**          Jump AltB, AeqB, AgtB
96649**     End: ...
96650**
96651** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
96652** actually called using Gosub and they do not Return.  EofA and EofB loop
96653** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
96654** and AgtB jump to either L2 or to one of EofA or EofB.
96655*/
96656#ifndef SQLITE_OMIT_COMPOUND_SELECT
96657static int multiSelectOrderBy(
96658  Parse *pParse,        /* Parsing context */
96659  Select *p,            /* The right-most of SELECTs to be coded */
96660  SelectDest *pDest     /* What to do with query results */
96661){
96662  int i, j;             /* Loop counters */
96663  Select *pPrior;       /* Another SELECT immediately to our left */
96664  Vdbe *v;              /* Generate code to this VDBE */
96665  SelectDest destA;     /* Destination for coroutine A */
96666  SelectDest destB;     /* Destination for coroutine B */
96667  int regAddrA;         /* Address register for select-A coroutine */
96668  int regEofA;          /* Flag to indicate when select-A is complete */
96669  int regAddrB;         /* Address register for select-B coroutine */
96670  int regEofB;          /* Flag to indicate when select-B is complete */
96671  int addrSelectA;      /* Address of the select-A coroutine */
96672  int addrSelectB;      /* Address of the select-B coroutine */
96673  int regOutA;          /* Address register for the output-A subroutine */
96674  int regOutB;          /* Address register for the output-B subroutine */
96675  int addrOutA;         /* Address of the output-A subroutine */
96676  int addrOutB = 0;     /* Address of the output-B subroutine */
96677  int addrEofA;         /* Address of the select-A-exhausted subroutine */
96678  int addrEofB;         /* Address of the select-B-exhausted subroutine */
96679  int addrAltB;         /* Address of the A<B subroutine */
96680  int addrAeqB;         /* Address of the A==B subroutine */
96681  int addrAgtB;         /* Address of the A>B subroutine */
96682  int regLimitA;        /* Limit register for select-A */
96683  int regLimitB;        /* Limit register for select-A */
96684  int regPrev;          /* A range of registers to hold previous output */
96685  int savedLimit;       /* Saved value of p->iLimit */
96686  int savedOffset;      /* Saved value of p->iOffset */
96687  int labelCmpr;        /* Label for the start of the merge algorithm */
96688  int labelEnd;         /* Label for the end of the overall SELECT stmt */
96689  int j1;               /* Jump instructions that get retargetted */
96690  int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
96691  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
96692  KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
96693  sqlite3 *db;          /* Database connection */
96694  ExprList *pOrderBy;   /* The ORDER BY clause */
96695  int nOrderBy;         /* Number of terms in the ORDER BY clause */
96696  int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
96697#ifndef SQLITE_OMIT_EXPLAIN
96698  int iSub1;            /* EQP id of left-hand query */
96699  int iSub2;            /* EQP id of right-hand query */
96700#endif
96701
96702  assert( p->pOrderBy!=0 );
96703  assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
96704  db = pParse->db;
96705  v = pParse->pVdbe;
96706  assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
96707  labelEnd = sqlite3VdbeMakeLabel(v);
96708  labelCmpr = sqlite3VdbeMakeLabel(v);
96709
96710
96711  /* Patch up the ORDER BY clause
96712  */
96713  op = p->op;
96714  pPrior = p->pPrior;
96715  assert( pPrior->pOrderBy==0 );
96716  pOrderBy = p->pOrderBy;
96717  assert( pOrderBy );
96718  nOrderBy = pOrderBy->nExpr;
96719
96720  /* For operators other than UNION ALL we have to make sure that
96721  ** the ORDER BY clause covers every term of the result set.  Add
96722  ** terms to the ORDER BY clause as necessary.
96723  */
96724  if( op!=TK_ALL ){
96725    for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
96726      struct ExprList_item *pItem;
96727      for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
96728        assert( pItem->iOrderByCol>0 );
96729        if( pItem->iOrderByCol==i ) break;
96730      }
96731      if( j==nOrderBy ){
96732        Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
96733        if( pNew==0 ) return SQLITE_NOMEM;
96734        pNew->flags |= EP_IntValue;
96735        pNew->u.iValue = i;
96736        pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
96737        if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
96738      }
96739    }
96740  }
96741
96742  /* Compute the comparison permutation and keyinfo that is used with
96743  ** the permutation used to determine if the next
96744  ** row of results comes from selectA or selectB.  Also add explicit
96745  ** collations to the ORDER BY clause terms so that when the subqueries
96746  ** to the right and the left are evaluated, they use the correct
96747  ** collation.
96748  */
96749  aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
96750  if( aPermute ){
96751    struct ExprList_item *pItem;
96752    for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
96753      assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
96754      aPermute[i] = pItem->iOrderByCol - 1;
96755    }
96756    pKeyMerge =
96757      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
96758    if( pKeyMerge ){
96759      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
96760      pKeyMerge->nField = (u16)nOrderBy;
96761      pKeyMerge->enc = ENC(db);
96762      for(i=0; i<nOrderBy; i++){
96763        CollSeq *pColl;
96764        Expr *pTerm = pOrderBy->a[i].pExpr;
96765        if( pTerm->flags & EP_ExpCollate ){
96766          pColl = pTerm->pColl;
96767        }else{
96768          pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
96769          pTerm->flags |= EP_ExpCollate;
96770          pTerm->pColl = pColl;
96771        }
96772        pKeyMerge->aColl[i] = pColl;
96773        pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
96774      }
96775    }
96776  }else{
96777    pKeyMerge = 0;
96778  }
96779
96780  /* Reattach the ORDER BY clause to the query.
96781  */
96782  p->pOrderBy = pOrderBy;
96783  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
96784
96785  /* Allocate a range of temporary registers and the KeyInfo needed
96786  ** for the logic that removes duplicate result rows when the
96787  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
96788  */
96789  if( op==TK_ALL ){
96790    regPrev = 0;
96791  }else{
96792    int nExpr = p->pEList->nExpr;
96793    assert( nOrderBy>=nExpr || db->mallocFailed );
96794    regPrev = sqlite3GetTempRange(pParse, nExpr+1);
96795    sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
96796    pKeyDup = sqlite3DbMallocZero(db,
96797                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
96798    if( pKeyDup ){
96799      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
96800      pKeyDup->nField = (u16)nExpr;
96801      pKeyDup->enc = ENC(db);
96802      for(i=0; i<nExpr; i++){
96803        pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
96804        pKeyDup->aSortOrder[i] = 0;
96805      }
96806    }
96807  }
96808
96809  /* Separate the left and the right query from one another
96810  */
96811  p->pPrior = 0;
96812  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
96813  if( pPrior->pPrior==0 ){
96814    sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
96815  }
96816
96817  /* Compute the limit registers */
96818  computeLimitRegisters(pParse, p, labelEnd);
96819  if( p->iLimit && op==TK_ALL ){
96820    regLimitA = ++pParse->nMem;
96821    regLimitB = ++pParse->nMem;
96822    sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
96823                                  regLimitA);
96824    sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
96825  }else{
96826    regLimitA = regLimitB = 0;
96827  }
96828  sqlite3ExprDelete(db, p->pLimit);
96829  p->pLimit = 0;
96830  sqlite3ExprDelete(db, p->pOffset);
96831  p->pOffset = 0;
96832
96833  regAddrA = ++pParse->nMem;
96834  regEofA = ++pParse->nMem;
96835  regAddrB = ++pParse->nMem;
96836  regEofB = ++pParse->nMem;
96837  regOutA = ++pParse->nMem;
96838  regOutB = ++pParse->nMem;
96839  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
96840  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
96841
96842  /* Jump past the various subroutines and coroutines to the main
96843  ** merge loop
96844  */
96845  j1 = sqlite3VdbeAddOp0(v, OP_Goto);
96846  addrSelectA = sqlite3VdbeCurrentAddr(v);
96847
96848
96849  /* Generate a coroutine to evaluate the SELECT statement to the
96850  ** left of the compound operator - the "A" select.
96851  */
96852  VdbeNoopComment((v, "Begin coroutine for left SELECT"));
96853  pPrior->iLimit = regLimitA;
96854  explainSetInteger(iSub1, pParse->iNextSelectId);
96855  sqlite3Select(pParse, pPrior, &destA);
96856  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
96857  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96858  VdbeNoopComment((v, "End coroutine for left SELECT"));
96859
96860  /* Generate a coroutine to evaluate the SELECT statement on
96861  ** the right - the "B" select
96862  */
96863  addrSelectB = sqlite3VdbeCurrentAddr(v);
96864  VdbeNoopComment((v, "Begin coroutine for right SELECT"));
96865  savedLimit = p->iLimit;
96866  savedOffset = p->iOffset;
96867  p->iLimit = regLimitB;
96868  p->iOffset = 0;
96869  explainSetInteger(iSub2, pParse->iNextSelectId);
96870  sqlite3Select(pParse, p, &destB);
96871  p->iLimit = savedLimit;
96872  p->iOffset = savedOffset;
96873  sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
96874  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96875  VdbeNoopComment((v, "End coroutine for right SELECT"));
96876
96877  /* Generate a subroutine that outputs the current row of the A
96878  ** select as the next output row of the compound select.
96879  */
96880  VdbeNoopComment((v, "Output routine for A"));
96881  addrOutA = generateOutputSubroutine(pParse,
96882                 p, &destA, pDest, regOutA,
96883                 regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
96884
96885  /* Generate a subroutine that outputs the current row of the B
96886  ** select as the next output row of the compound select.
96887  */
96888  if( op==TK_ALL || op==TK_UNION ){
96889    VdbeNoopComment((v, "Output routine for B"));
96890    addrOutB = generateOutputSubroutine(pParse,
96891                 p, &destB, pDest, regOutB,
96892                 regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
96893  }
96894
96895  /* Generate a subroutine to run when the results from select A
96896  ** are exhausted and only data in select B remains.
96897  */
96898  VdbeNoopComment((v, "eof-A subroutine"));
96899  if( op==TK_EXCEPT || op==TK_INTERSECT ){
96900    addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
96901  }else{
96902    addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
96903    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96904    sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96905    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
96906    p->nSelectRow += pPrior->nSelectRow;
96907  }
96908
96909  /* Generate a subroutine to run when the results from select B
96910  ** are exhausted and only data in select A remains.
96911  */
96912  if( op==TK_INTERSECT ){
96913    addrEofB = addrEofA;
96914    if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
96915  }else{
96916    VdbeNoopComment((v, "eof-B subroutine"));
96917    addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
96918    sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96919    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96920    sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
96921  }
96922
96923  /* Generate code to handle the case of A<B
96924  */
96925  VdbeNoopComment((v, "A-lt-B subroutine"));
96926  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
96927  sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96928  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96929  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96930
96931  /* Generate code to handle the case of A==B
96932  */
96933  if( op==TK_ALL ){
96934    addrAeqB = addrAltB;
96935  }else if( op==TK_INTERSECT ){
96936    addrAeqB = addrAltB;
96937    addrAltB++;
96938  }else{
96939    VdbeNoopComment((v, "A-eq-B subroutine"));
96940    addrAeqB =
96941    sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
96942    sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96943    sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96944  }
96945
96946  /* Generate code to handle the case of A>B
96947  */
96948  VdbeNoopComment((v, "A-gt-B subroutine"));
96949  addrAgtB = sqlite3VdbeCurrentAddr(v);
96950  if( op==TK_ALL || op==TK_UNION ){
96951    sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
96952  }
96953  sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
96954  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96955  sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
96956
96957  /* This code runs once to initialize everything.
96958  */
96959  sqlite3VdbeJumpHere(v, j1);
96960  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
96961  sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
96962  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
96963  sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
96964  sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
96965  sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
96966
96967  /* Implement the main merge loop
96968  */
96969  sqlite3VdbeResolveLabel(v, labelCmpr);
96970  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
96971  sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
96972                         (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
96973  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
96974
96975  /* Release temporary registers
96976  */
96977  if( regPrev ){
96978    sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
96979  }
96980
96981  /* Jump to the this point in order to terminate the query.
96982  */
96983  sqlite3VdbeResolveLabel(v, labelEnd);
96984
96985  /* Set the number of output columns
96986  */
96987  if( pDest->eDest==SRT_Output ){
96988    Select *pFirst = pPrior;
96989    while( pFirst->pPrior ) pFirst = pFirst->pPrior;
96990    generateColumnNames(pParse, 0, pFirst->pEList);
96991  }
96992
96993  /* Reassembly the compound query so that it will be freed correctly
96994  ** by the calling function */
96995  if( p->pPrior ){
96996    sqlite3SelectDelete(db, p->pPrior);
96997  }
96998  p->pPrior = pPrior;
96999
97000  /*** TBD:  Insert subroutine calls to close cursors on incomplete
97001  **** subqueries ****/
97002  explainComposite(pParse, p->op, iSub1, iSub2, 0);
97003  return SQLITE_OK;
97004}
97005#endif
97006
97007#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
97008/* Forward Declarations */
97009static void substExprList(sqlite3*, ExprList*, int, ExprList*);
97010static void substSelect(sqlite3*, Select *, int, ExprList *);
97011
97012/*
97013** Scan through the expression pExpr.  Replace every reference to
97014** a column in table number iTable with a copy of the iColumn-th
97015** entry in pEList.  (But leave references to the ROWID column
97016** unchanged.)
97017**
97018** This routine is part of the flattening procedure.  A subquery
97019** whose result set is defined by pEList appears as entry in the
97020** FROM clause of a SELECT such that the VDBE cursor assigned to that
97021** FORM clause entry is iTable.  This routine make the necessary
97022** changes to pExpr so that it refers directly to the source table
97023** of the subquery rather the result set of the subquery.
97024*/
97025static Expr *substExpr(
97026  sqlite3 *db,        /* Report malloc errors to this connection */
97027  Expr *pExpr,        /* Expr in which substitution occurs */
97028  int iTable,         /* Table to be substituted */
97029  ExprList *pEList    /* Substitute expressions */
97030){
97031  if( pExpr==0 ) return 0;
97032  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
97033    if( pExpr->iColumn<0 ){
97034      pExpr->op = TK_NULL;
97035    }else{
97036      Expr *pNew;
97037      assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
97038      assert( pExpr->pLeft==0 && pExpr->pRight==0 );
97039      pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
97040      if( pNew && pExpr->pColl ){
97041        pNew->pColl = pExpr->pColl;
97042      }
97043      sqlite3ExprDelete(db, pExpr);
97044      pExpr = pNew;
97045    }
97046  }else{
97047    pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
97048    pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
97049    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
97050      substSelect(db, pExpr->x.pSelect, iTable, pEList);
97051    }else{
97052      substExprList(db, pExpr->x.pList, iTable, pEList);
97053    }
97054  }
97055  return pExpr;
97056}
97057static void substExprList(
97058  sqlite3 *db,         /* Report malloc errors here */
97059  ExprList *pList,     /* List to scan and in which to make substitutes */
97060  int iTable,          /* Table to be substituted */
97061  ExprList *pEList     /* Substitute values */
97062){
97063  int i;
97064  if( pList==0 ) return;
97065  for(i=0; i<pList->nExpr; i++){
97066    pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
97067  }
97068}
97069static void substSelect(
97070  sqlite3 *db,         /* Report malloc errors here */
97071  Select *p,           /* SELECT statement in which to make substitutions */
97072  int iTable,          /* Table to be replaced */
97073  ExprList *pEList     /* Substitute values */
97074){
97075  SrcList *pSrc;
97076  struct SrcList_item *pItem;
97077  int i;
97078  if( !p ) return;
97079  substExprList(db, p->pEList, iTable, pEList);
97080  substExprList(db, p->pGroupBy, iTable, pEList);
97081  substExprList(db, p->pOrderBy, iTable, pEList);
97082  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
97083  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
97084  substSelect(db, p->pPrior, iTable, pEList);
97085  pSrc = p->pSrc;
97086  assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
97087  if( ALWAYS(pSrc) ){
97088    for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
97089      substSelect(db, pItem->pSelect, iTable, pEList);
97090    }
97091  }
97092}
97093#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
97094
97095#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
97096/*
97097** This routine attempts to flatten subqueries as a performance optimization.
97098** This routine returns 1 if it makes changes and 0 if no flattening occurs.
97099**
97100** To understand the concept of flattening, consider the following
97101** query:
97102**
97103**     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
97104**
97105** The default way of implementing this query is to execute the
97106** subquery first and store the results in a temporary table, then
97107** run the outer query on that temporary table.  This requires two
97108** passes over the data.  Furthermore, because the temporary table
97109** has no indices, the WHERE clause on the outer query cannot be
97110** optimized.
97111**
97112** This routine attempts to rewrite queries such as the above into
97113** a single flat select, like this:
97114**
97115**     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
97116**
97117** The code generated for this simpification gives the same result
97118** but only has to scan the data once.  And because indices might
97119** exist on the table t1, a complete scan of the data might be
97120** avoided.
97121**
97122** Flattening is only attempted if all of the following are true:
97123**
97124**   (1)  The subquery and the outer query do not both use aggregates.
97125**
97126**   (2)  The subquery is not an aggregate or the outer query is not a join.
97127**
97128**   (3)  The subquery is not the right operand of a left outer join
97129**        (Originally ticket #306.  Strengthened by ticket #3300)
97130**
97131**   (4)  The subquery is not DISTINCT.
97132**
97133**  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
97134**        sub-queries that were excluded from this optimization. Restriction
97135**        (4) has since been expanded to exclude all DISTINCT subqueries.
97136**
97137**   (6)  The subquery does not use aggregates or the outer query is not
97138**        DISTINCT.
97139**
97140**   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
97141**        A FROM clause, consider adding a FROM close with the special
97142**        table sqlite_once that consists of a single row containing a
97143**        single NULL.
97144**
97145**   (8)  The subquery does not use LIMIT or the outer query is not a join.
97146**
97147**   (9)  The subquery does not use LIMIT or the outer query does not use
97148**        aggregates.
97149**
97150**  (10)  The subquery does not use aggregates or the outer query does not
97151**        use LIMIT.
97152**
97153**  (11)  The subquery and the outer query do not both have ORDER BY clauses.
97154**
97155**  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
97156**        a separate restriction deriving from ticket #350.
97157**
97158**  (13)  The subquery and outer query do not both use LIMIT.
97159**
97160**  (14)  The subquery does not use OFFSET.
97161**
97162**  (15)  The outer query is not part of a compound select or the
97163**        subquery does not have a LIMIT clause.
97164**        (See ticket #2339 and ticket [02a8e81d44]).
97165**
97166**  (16)  The outer query is not an aggregate or the subquery does
97167**        not contain ORDER BY.  (Ticket #2942)  This used to not matter
97168**        until we introduced the group_concat() function.
97169**
97170**  (17)  The sub-query is not a compound select, or it is a UNION ALL
97171**        compound clause made up entirely of non-aggregate queries, and
97172**        the parent query:
97173**
97174**          * is not itself part of a compound select,
97175**          * is not an aggregate or DISTINCT query, and
97176**          * is not a join
97177**
97178**        The parent and sub-query may contain WHERE clauses. Subject to
97179**        rules (11), (13) and (14), they may also contain ORDER BY,
97180**        LIMIT and OFFSET clauses.  The subquery cannot use any compound
97181**        operator other than UNION ALL because all the other compound
97182**        operators have an implied DISTINCT which is disallowed by
97183**        restriction (4).
97184**
97185**  (18)  If the sub-query is a compound select, then all terms of the
97186**        ORDER by clause of the parent must be simple references to
97187**        columns of the sub-query.
97188**
97189**  (19)  The subquery does not use LIMIT or the outer query does not
97190**        have a WHERE clause.
97191**
97192**  (20)  If the sub-query is a compound select, then it must not use
97193**        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
97194**        somewhat by saying that the terms of the ORDER BY clause must
97195**        appear as unmodified result columns in the outer query.  But we
97196**        have other optimizations in mind to deal with that case.
97197**
97198**  (21)  The subquery does not use LIMIT or the outer query is not
97199**        DISTINCT.  (See ticket [752e1646fc]).
97200**
97201** In this routine, the "p" parameter is a pointer to the outer query.
97202** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
97203** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
97204**
97205** If flattening is not attempted, this routine is a no-op and returns 0.
97206** If flattening is attempted this routine returns 1.
97207**
97208** All of the expression analysis must occur on both the outer query and
97209** the subquery before this routine runs.
97210*/
97211static int flattenSubquery(
97212  Parse *pParse,       /* Parsing context */
97213  Select *p,           /* The parent or outer SELECT statement */
97214  int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
97215  int isAgg,           /* True if outer SELECT uses aggregate functions */
97216  int subqueryIsAgg    /* True if the subquery uses aggregate functions */
97217){
97218  const char *zSavedAuthContext = pParse->zAuthContext;
97219  Select *pParent;
97220  Select *pSub;       /* The inner query or "subquery" */
97221  Select *pSub1;      /* Pointer to the rightmost select in sub-query */
97222  SrcList *pSrc;      /* The FROM clause of the outer query */
97223  SrcList *pSubSrc;   /* The FROM clause of the subquery */
97224  ExprList *pList;    /* The result set of the outer query */
97225  int iParent;        /* VDBE cursor number of the pSub result set temp table */
97226  int i;              /* Loop counter */
97227  Expr *pWhere;                    /* The WHERE clause */
97228  struct SrcList_item *pSubitem;   /* The subquery */
97229  sqlite3 *db = pParse->db;
97230
97231  /* Check to see if flattening is permitted.  Return 0 if not.
97232  */
97233  assert( p!=0 );
97234  assert( p->pPrior==0 );  /* Unable to flatten compound queries */
97235  if( db->flags & SQLITE_QueryFlattener ) return 0;
97236  pSrc = p->pSrc;
97237  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
97238  pSubitem = &pSrc->a[iFrom];
97239  iParent = pSubitem->iCursor;
97240  pSub = pSubitem->pSelect;
97241  assert( pSub!=0 );
97242  if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
97243  if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
97244  pSubSrc = pSub->pSrc;
97245  assert( pSubSrc );
97246  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
97247  ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
97248  ** because they could be computed at compile-time.  But when LIMIT and OFFSET
97249  ** became arbitrary expressions, we were forced to add restrictions (13)
97250  ** and (14). */
97251  if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
97252  if( pSub->pOffset ) return 0;                          /* Restriction (14) */
97253  if( p->pRightmost && pSub->pLimit ){
97254    return 0;                                            /* Restriction (15) */
97255  }
97256  if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
97257  if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
97258  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
97259     return 0;         /* Restrictions (8)(9) */
97260  }
97261  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
97262     return 0;         /* Restriction (6)  */
97263  }
97264  if( p->pOrderBy && pSub->pOrderBy ){
97265     return 0;                                           /* Restriction (11) */
97266  }
97267  if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
97268  if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
97269  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
97270     return 0;         /* Restriction (21) */
97271  }
97272
97273  /* OBSOLETE COMMENT 1:
97274  ** Restriction 3:  If the subquery is a join, make sure the subquery is
97275  ** not used as the right operand of an outer join.  Examples of why this
97276  ** is not allowed:
97277  **
97278  **         t1 LEFT OUTER JOIN (t2 JOIN t3)
97279  **
97280  ** If we flatten the above, we would get
97281  **
97282  **         (t1 LEFT OUTER JOIN t2) JOIN t3
97283  **
97284  ** which is not at all the same thing.
97285  **
97286  ** OBSOLETE COMMENT 2:
97287  ** Restriction 12:  If the subquery is the right operand of a left outer
97288  ** join, make sure the subquery has no WHERE clause.
97289  ** An examples of why this is not allowed:
97290  **
97291  **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
97292  **
97293  ** If we flatten the above, we would get
97294  **
97295  **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
97296  **
97297  ** But the t2.x>0 test will always fail on a NULL row of t2, which
97298  ** effectively converts the OUTER JOIN into an INNER JOIN.
97299  **
97300  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
97301  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
97302  ** is fraught with danger.  Best to avoid the whole thing.  If the
97303  ** subquery is the right term of a LEFT JOIN, then do not flatten.
97304  */
97305  if( (pSubitem->jointype & JT_OUTER)!=0 ){
97306    return 0;
97307  }
97308
97309  /* Restriction 17: If the sub-query is a compound SELECT, then it must
97310  ** use only the UNION ALL operator. And none of the simple select queries
97311  ** that make up the compound SELECT are allowed to be aggregate or distinct
97312  ** queries.
97313  */
97314  if( pSub->pPrior ){
97315    if( pSub->pOrderBy ){
97316      return 0;  /* Restriction 20 */
97317    }
97318    if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
97319      return 0;
97320    }
97321    for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
97322      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
97323      testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
97324      assert( pSub->pSrc!=0 );
97325      if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
97326       || (pSub1->pPrior && pSub1->op!=TK_ALL)
97327       || pSub1->pSrc->nSrc<1
97328      ){
97329        return 0;
97330      }
97331      testcase( pSub1->pSrc->nSrc>1 );
97332    }
97333
97334    /* Restriction 18. */
97335    if( p->pOrderBy ){
97336      int ii;
97337      for(ii=0; ii<p->pOrderBy->nExpr; ii++){
97338        if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
97339      }
97340    }
97341  }
97342
97343  /***** If we reach this point, flattening is permitted. *****/
97344
97345  /* Authorize the subquery */
97346  pParse->zAuthContext = pSubitem->zName;
97347  sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
97348  pParse->zAuthContext = zSavedAuthContext;
97349
97350  /* If the sub-query is a compound SELECT statement, then (by restrictions
97351  ** 17 and 18 above) it must be a UNION ALL and the parent query must
97352  ** be of the form:
97353  **
97354  **     SELECT <expr-list> FROM (<sub-query>) <where-clause>
97355  **
97356  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
97357  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
97358  ** OFFSET clauses and joins them to the left-hand-side of the original
97359  ** using UNION ALL operators. In this case N is the number of simple
97360  ** select statements in the compound sub-query.
97361  **
97362  ** Example:
97363  **
97364  **     SELECT a+1 FROM (
97365  **        SELECT x FROM tab
97366  **        UNION ALL
97367  **        SELECT y FROM tab
97368  **        UNION ALL
97369  **        SELECT abs(z*2) FROM tab2
97370  **     ) WHERE a!=5 ORDER BY 1
97371  **
97372  ** Transformed into:
97373  **
97374  **     SELECT x+1 FROM tab WHERE x+1!=5
97375  **     UNION ALL
97376  **     SELECT y+1 FROM tab WHERE y+1!=5
97377  **     UNION ALL
97378  **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
97379  **     ORDER BY 1
97380  **
97381  ** We call this the "compound-subquery flattening".
97382  */
97383  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
97384    Select *pNew;
97385    ExprList *pOrderBy = p->pOrderBy;
97386    Expr *pLimit = p->pLimit;
97387    Select *pPrior = p->pPrior;
97388    p->pOrderBy = 0;
97389    p->pSrc = 0;
97390    p->pPrior = 0;
97391    p->pLimit = 0;
97392    pNew = sqlite3SelectDup(db, p, 0);
97393    p->pLimit = pLimit;
97394    p->pOrderBy = pOrderBy;
97395    p->pSrc = pSrc;
97396    p->op = TK_ALL;
97397    p->pRightmost = 0;
97398    if( pNew==0 ){
97399      pNew = pPrior;
97400    }else{
97401      pNew->pPrior = pPrior;
97402      pNew->pRightmost = 0;
97403    }
97404    p->pPrior = pNew;
97405    if( db->mallocFailed ) return 1;
97406  }
97407
97408  /* Begin flattening the iFrom-th entry of the FROM clause
97409  ** in the outer query.
97410  */
97411  pSub = pSub1 = pSubitem->pSelect;
97412
97413  /* Delete the transient table structure associated with the
97414  ** subquery
97415  */
97416  sqlite3DbFree(db, pSubitem->zDatabase);
97417  sqlite3DbFree(db, pSubitem->zName);
97418  sqlite3DbFree(db, pSubitem->zAlias);
97419  pSubitem->zDatabase = 0;
97420  pSubitem->zName = 0;
97421  pSubitem->zAlias = 0;
97422  pSubitem->pSelect = 0;
97423
97424  /* Defer deleting the Table object associated with the
97425  ** subquery until code generation is
97426  ** complete, since there may still exist Expr.pTab entries that
97427  ** refer to the subquery even after flattening.  Ticket #3346.
97428  **
97429  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
97430  */
97431  if( ALWAYS(pSubitem->pTab!=0) ){
97432    Table *pTabToDel = pSubitem->pTab;
97433    if( pTabToDel->nRef==1 ){
97434      Parse *pToplevel = sqlite3ParseToplevel(pParse);
97435      pTabToDel->pNextZombie = pToplevel->pZombieTab;
97436      pToplevel->pZombieTab = pTabToDel;
97437    }else{
97438      pTabToDel->nRef--;
97439    }
97440    pSubitem->pTab = 0;
97441  }
97442
97443  /* The following loop runs once for each term in a compound-subquery
97444  ** flattening (as described above).  If we are doing a different kind
97445  ** of flattening - a flattening other than a compound-subquery flattening -
97446  ** then this loop only runs once.
97447  **
97448  ** This loop moves all of the FROM elements of the subquery into the
97449  ** the FROM clause of the outer query.  Before doing this, remember
97450  ** the cursor number for the original outer query FROM element in
97451  ** iParent.  The iParent cursor will never be used.  Subsequent code
97452  ** will scan expressions looking for iParent references and replace
97453  ** those references with expressions that resolve to the subquery FROM
97454  ** elements we are now copying in.
97455  */
97456  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
97457    int nSubSrc;
97458    u8 jointype = 0;
97459    pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
97460    nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
97461    pSrc = pParent->pSrc;     /* FROM clause of the outer query */
97462
97463    if( pSrc ){
97464      assert( pParent==p );  /* First time through the loop */
97465      jointype = pSubitem->jointype;
97466    }else{
97467      assert( pParent!=p );  /* 2nd and subsequent times through the loop */
97468      pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
97469      if( pSrc==0 ){
97470        assert( db->mallocFailed );
97471        break;
97472      }
97473    }
97474
97475    /* The subquery uses a single slot of the FROM clause of the outer
97476    ** query.  If the subquery has more than one element in its FROM clause,
97477    ** then expand the outer query to make space for it to hold all elements
97478    ** of the subquery.
97479    **
97480    ** Example:
97481    **
97482    **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
97483    **
97484    ** The outer query has 3 slots in its FROM clause.  One slot of the
97485    ** outer query (the middle slot) is used by the subquery.  The next
97486    ** block of code will expand the out query to 4 slots.  The middle
97487    ** slot is expanded to two slots in order to make space for the
97488    ** two elements in the FROM clause of the subquery.
97489    */
97490    if( nSubSrc>1 ){
97491      pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
97492      if( db->mallocFailed ){
97493        break;
97494      }
97495    }
97496
97497    /* Transfer the FROM clause terms from the subquery into the
97498    ** outer query.
97499    */
97500    for(i=0; i<nSubSrc; i++){
97501      sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
97502      pSrc->a[i+iFrom] = pSubSrc->a[i];
97503      memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
97504    }
97505    pSrc->a[iFrom].jointype = jointype;
97506
97507    /* Now begin substituting subquery result set expressions for
97508    ** references to the iParent in the outer query.
97509    **
97510    ** Example:
97511    **
97512    **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
97513    **   \                     \_____________ subquery __________/          /
97514    **    \_____________________ outer query ______________________________/
97515    **
97516    ** We look at every expression in the outer query and every place we see
97517    ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
97518    */
97519    pList = pParent->pEList;
97520    for(i=0; i<pList->nExpr; i++){
97521      if( pList->a[i].zName==0 ){
97522        const char *zSpan = pList->a[i].zSpan;
97523        if( ALWAYS(zSpan) ){
97524          pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
97525        }
97526      }
97527    }
97528    substExprList(db, pParent->pEList, iParent, pSub->pEList);
97529    if( isAgg ){
97530      substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
97531      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97532    }
97533    if( pSub->pOrderBy ){
97534      assert( pParent->pOrderBy==0 );
97535      pParent->pOrderBy = pSub->pOrderBy;
97536      pSub->pOrderBy = 0;
97537    }else if( pParent->pOrderBy ){
97538      substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
97539    }
97540    if( pSub->pWhere ){
97541      pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
97542    }else{
97543      pWhere = 0;
97544    }
97545    if( subqueryIsAgg ){
97546      assert( pParent->pHaving==0 );
97547      pParent->pHaving = pParent->pWhere;
97548      pParent->pWhere = pWhere;
97549      pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
97550      pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
97551                                  sqlite3ExprDup(db, pSub->pHaving, 0));
97552      assert( pParent->pGroupBy==0 );
97553      pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
97554    }else{
97555      pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
97556      pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
97557    }
97558
97559    /* The flattened query is distinct if either the inner or the
97560    ** outer query is distinct.
97561    */
97562    pParent->selFlags |= pSub->selFlags & SF_Distinct;
97563
97564    /*
97565    ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
97566    **
97567    ** One is tempted to try to add a and b to combine the limits.  But this
97568    ** does not work if either limit is negative.
97569    */
97570    if( pSub->pLimit ){
97571      pParent->pLimit = pSub->pLimit;
97572      pSub->pLimit = 0;
97573    }
97574  }
97575
97576  /* Finially, delete what is left of the subquery and return
97577  ** success.
97578  */
97579  sqlite3SelectDelete(db, pSub1);
97580
97581  return 1;
97582}
97583#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
97584
97585/*
97586** Analyze the SELECT statement passed as an argument to see if it
97587** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if
97588** it is, or 0 otherwise. At present, a query is considered to be
97589** a min()/max() query if:
97590**
97591**   1. There is a single object in the FROM clause.
97592**
97593**   2. There is a single expression in the result set, and it is
97594**      either min(x) or max(x), where x is a column reference.
97595*/
97596static u8 minMaxQuery(Select *p){
97597  Expr *pExpr;
97598  ExprList *pEList = p->pEList;
97599
97600  if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
97601  pExpr = pEList->a[0].pExpr;
97602  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97603  if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
97604  pEList = pExpr->x.pList;
97605  if( pEList==0 || pEList->nExpr!=1 ) return 0;
97606  if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
97607  assert( !ExprHasProperty(pExpr, EP_IntValue) );
97608  if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
97609    return WHERE_ORDERBY_MIN;
97610  }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
97611    return WHERE_ORDERBY_MAX;
97612  }
97613  return WHERE_ORDERBY_NORMAL;
97614}
97615
97616/*
97617** The select statement passed as the first argument is an aggregate query.
97618** The second argment is the associated aggregate-info object. This
97619** function tests if the SELECT is of the form:
97620**
97621**   SELECT count(*) FROM <tbl>
97622**
97623** where table is a database table, not a sub-select or view. If the query
97624** does match this pattern, then a pointer to the Table object representing
97625** <tbl> is returned. Otherwise, 0 is returned.
97626*/
97627static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
97628  Table *pTab;
97629  Expr *pExpr;
97630
97631  assert( !p->pGroupBy );
97632
97633  if( p->pWhere || p->pEList->nExpr!=1
97634   || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
97635  ){
97636    return 0;
97637  }
97638  pTab = p->pSrc->a[0].pTab;
97639  pExpr = p->pEList->a[0].pExpr;
97640  assert( pTab && !pTab->pSelect && pExpr );
97641
97642  if( IsVirtual(pTab) ) return 0;
97643  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
97644  if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
97645  if( pExpr->flags&EP_Distinct ) return 0;
97646
97647  return pTab;
97648}
97649
97650/*
97651** If the source-list item passed as an argument was augmented with an
97652** INDEXED BY clause, then try to locate the specified index. If there
97653** was such a clause and the named index cannot be found, return
97654** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
97655** pFrom->pIndex and return SQLITE_OK.
97656*/
97657SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
97658  if( pFrom->pTab && pFrom->zIndex ){
97659    Table *pTab = pFrom->pTab;
97660    char *zIndex = pFrom->zIndex;
97661    Index *pIdx;
97662    for(pIdx=pTab->pIndex;
97663        pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
97664        pIdx=pIdx->pNext
97665    );
97666    if( !pIdx ){
97667      sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
97668      pParse->checkSchema = 1;
97669      return SQLITE_ERROR;
97670    }
97671    pFrom->pIndex = pIdx;
97672  }
97673  return SQLITE_OK;
97674}
97675
97676/*
97677** This routine is a Walker callback for "expanding" a SELECT statement.
97678** "Expanding" means to do the following:
97679**
97680**    (1)  Make sure VDBE cursor numbers have been assigned to every
97681**         element of the FROM clause.
97682**
97683**    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that
97684**         defines FROM clause.  When views appear in the FROM clause,
97685**         fill pTabList->a[].pSelect with a copy of the SELECT statement
97686**         that implements the view.  A copy is made of the view's SELECT
97687**         statement so that we can freely modify or delete that statement
97688**         without worrying about messing up the presistent representation
97689**         of the view.
97690**
97691**    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
97692**         on joins and the ON and USING clause of joins.
97693**
97694**    (4)  Scan the list of columns in the result set (pEList) looking
97695**         for instances of the "*" operator or the TABLE.* operator.
97696**         If found, expand each "*" to be every column in every table
97697**         and TABLE.* to be every column in TABLE.
97698**
97699*/
97700static int selectExpander(Walker *pWalker, Select *p){
97701  Parse *pParse = pWalker->pParse;
97702  int i, j, k;
97703  SrcList *pTabList;
97704  ExprList *pEList;
97705  struct SrcList_item *pFrom;
97706  sqlite3 *db = pParse->db;
97707
97708  if( db->mallocFailed  ){
97709    return WRC_Abort;
97710  }
97711  if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
97712    return WRC_Prune;
97713  }
97714  p->selFlags |= SF_Expanded;
97715  pTabList = p->pSrc;
97716  pEList = p->pEList;
97717
97718  /* Make sure cursor numbers have been assigned to all entries in
97719  ** the FROM clause of the SELECT statement.
97720  */
97721  sqlite3SrcListAssignCursors(pParse, pTabList);
97722
97723  /* Look up every table named in the FROM clause of the select.  If
97724  ** an entry of the FROM clause is a subquery instead of a table or view,
97725  ** then create a transient table structure to describe the subquery.
97726  */
97727  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97728    Table *pTab;
97729    if( pFrom->pTab!=0 ){
97730      /* This statement has already been prepared.  There is no need
97731      ** to go further. */
97732      assert( i==0 );
97733      return WRC_Prune;
97734    }
97735    if( pFrom->zName==0 ){
97736#ifndef SQLITE_OMIT_SUBQUERY
97737      Select *pSel = pFrom->pSelect;
97738      /* A sub-query in the FROM clause of a SELECT */
97739      assert( pSel!=0 );
97740      assert( pFrom->pTab==0 );
97741      sqlite3WalkSelect(pWalker, pSel);
97742      pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
97743      if( pTab==0 ) return WRC_Abort;
97744      pTab->nRef = 1;
97745      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
97746      while( pSel->pPrior ){ pSel = pSel->pPrior; }
97747      selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
97748      pTab->iPKey = -1;
97749      pTab->nRowEst = 1000000;
97750      pTab->tabFlags |= TF_Ephemeral;
97751#endif
97752    }else{
97753      /* An ordinary table or view name in the FROM clause */
97754      assert( pFrom->pTab==0 );
97755      pFrom->pTab = pTab =
97756        sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
97757      if( pTab==0 ) return WRC_Abort;
97758      pTab->nRef++;
97759#if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
97760      if( pTab->pSelect || IsVirtual(pTab) ){
97761        /* We reach here if the named table is a really a view */
97762        if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
97763        assert( pFrom->pSelect==0 );
97764        pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
97765        sqlite3WalkSelect(pWalker, pFrom->pSelect);
97766      }
97767#endif
97768    }
97769
97770    /* Locate the index named by the INDEXED BY clause, if any. */
97771    if( sqlite3IndexedByLookup(pParse, pFrom) ){
97772      return WRC_Abort;
97773    }
97774  }
97775
97776  /* Process NATURAL keywords, and ON and USING clauses of joins.
97777  */
97778  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
97779    return WRC_Abort;
97780  }
97781
97782  /* For every "*" that occurs in the column list, insert the names of
97783  ** all columns in all tables.  And for every TABLE.* insert the names
97784  ** of all columns in TABLE.  The parser inserted a special expression
97785  ** with the TK_ALL operator for each "*" that it found in the column list.
97786  ** The following code just has to locate the TK_ALL expressions and expand
97787  ** each one to the list of all columns in all tables.
97788  **
97789  ** The first loop just checks to see if there are any "*" operators
97790  ** that need expanding.
97791  */
97792  for(k=0; k<pEList->nExpr; k++){
97793    Expr *pE = pEList->a[k].pExpr;
97794    if( pE->op==TK_ALL ) break;
97795    assert( pE->op!=TK_DOT || pE->pRight!=0 );
97796    assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
97797    if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
97798  }
97799  if( k<pEList->nExpr ){
97800    /*
97801    ** If we get here it means the result set contains one or more "*"
97802    ** operators that need to be expanded.  Loop through each expression
97803    ** in the result set and expand them one by one.
97804    */
97805    struct ExprList_item *a = pEList->a;
97806    ExprList *pNew = 0;
97807    int flags = pParse->db->flags;
97808    int longNames = (flags & SQLITE_FullColNames)!=0
97809                      && (flags & SQLITE_ShortColNames)==0;
97810
97811    for(k=0; k<pEList->nExpr; k++){
97812      Expr *pE = a[k].pExpr;
97813      assert( pE->op!=TK_DOT || pE->pRight!=0 );
97814      if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
97815        /* This particular expression does not need to be expanded.
97816        */
97817        pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
97818        if( pNew ){
97819          pNew->a[pNew->nExpr-1].zName = a[k].zName;
97820          pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
97821          a[k].zName = 0;
97822          a[k].zSpan = 0;
97823        }
97824        a[k].pExpr = 0;
97825      }else{
97826        /* This expression is a "*" or a "TABLE.*" and needs to be
97827        ** expanded. */
97828        int tableSeen = 0;      /* Set to 1 when TABLE matches */
97829        char *zTName;            /* text of name of TABLE */
97830        if( pE->op==TK_DOT ){
97831          assert( pE->pLeft!=0 );
97832          assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
97833          zTName = pE->pLeft->u.zToken;
97834        }else{
97835          zTName = 0;
97836        }
97837        for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97838          Table *pTab = pFrom->pTab;
97839          char *zTabName = pFrom->zAlias;
97840          if( zTabName==0 ){
97841            zTabName = pTab->zName;
97842          }
97843          if( db->mallocFailed ) break;
97844          if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
97845            continue;
97846          }
97847          tableSeen = 1;
97848          for(j=0; j<pTab->nCol; j++){
97849            Expr *pExpr, *pRight;
97850            char *zName = pTab->aCol[j].zName;
97851            char *zColname;  /* The computed column name */
97852            char *zToFree;   /* Malloced string that needs to be freed */
97853            Token sColname;  /* Computed column name as a token */
97854
97855            /* If a column is marked as 'hidden' (currently only possible
97856            ** for virtual tables), do not include it in the expanded
97857            ** result-set list.
97858            */
97859            if( IsHiddenColumn(&pTab->aCol[j]) ){
97860              assert(IsVirtual(pTab));
97861              continue;
97862            }
97863
97864            if( i>0 && zTName==0 ){
97865              if( (pFrom->jointype & JT_NATURAL)!=0
97866                && tableAndColumnIndex(pTabList, i, zName, 0, 0)
97867              ){
97868                /* In a NATURAL join, omit the join columns from the
97869                ** table to the right of the join */
97870                continue;
97871              }
97872              if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
97873                /* In a join with a USING clause, omit columns in the
97874                ** using clause from the table on the right. */
97875                continue;
97876              }
97877            }
97878            pRight = sqlite3Expr(db, TK_ID, zName);
97879            zColname = zName;
97880            zToFree = 0;
97881            if( longNames || pTabList->nSrc>1 ){
97882              Expr *pLeft;
97883              pLeft = sqlite3Expr(db, TK_ID, zTabName);
97884              pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
97885              if( longNames ){
97886                zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
97887                zToFree = zColname;
97888              }
97889            }else{
97890              pExpr = pRight;
97891            }
97892            pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
97893            sColname.z = zColname;
97894            sColname.n = sqlite3Strlen30(zColname);
97895            sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
97896            sqlite3DbFree(db, zToFree);
97897          }
97898        }
97899        if( !tableSeen ){
97900          if( zTName ){
97901            sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
97902          }else{
97903            sqlite3ErrorMsg(pParse, "no tables specified");
97904          }
97905        }
97906      }
97907    }
97908    sqlite3ExprListDelete(db, pEList);
97909    p->pEList = pNew;
97910  }
97911#if SQLITE_MAX_COLUMN
97912  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
97913    sqlite3ErrorMsg(pParse, "too many columns in result set");
97914  }
97915#endif
97916  return WRC_Continue;
97917}
97918
97919/*
97920** No-op routine for the parse-tree walker.
97921**
97922** When this routine is the Walker.xExprCallback then expression trees
97923** are walked without any actions being taken at each node.  Presumably,
97924** when this routine is used for Walker.xExprCallback then
97925** Walker.xSelectCallback is set to do something useful for every
97926** subquery in the parser tree.
97927*/
97928static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
97929  UNUSED_PARAMETER2(NotUsed, NotUsed2);
97930  return WRC_Continue;
97931}
97932
97933/*
97934** This routine "expands" a SELECT statement and all of its subqueries.
97935** For additional information on what it means to "expand" a SELECT
97936** statement, see the comment on the selectExpand worker callback above.
97937**
97938** Expanding a SELECT statement is the first step in processing a
97939** SELECT statement.  The SELECT statement must be expanded before
97940** name resolution is performed.
97941**
97942** If anything goes wrong, an error message is written into pParse.
97943** The calling function can detect the problem by looking at pParse->nErr
97944** and/or pParse->db->mallocFailed.
97945*/
97946static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
97947  Walker w;
97948  w.xSelectCallback = selectExpander;
97949  w.xExprCallback = exprWalkNoop;
97950  w.pParse = pParse;
97951  sqlite3WalkSelect(&w, pSelect);
97952}
97953
97954
97955#ifndef SQLITE_OMIT_SUBQUERY
97956/*
97957** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
97958** interface.
97959**
97960** For each FROM-clause subquery, add Column.zType and Column.zColl
97961** information to the Table structure that represents the result set
97962** of that subquery.
97963**
97964** The Table structure that represents the result set was constructed
97965** by selectExpander() but the type and collation information was omitted
97966** at that point because identifiers had not yet been resolved.  This
97967** routine is called after identifier resolution.
97968*/
97969static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
97970  Parse *pParse;
97971  int i;
97972  SrcList *pTabList;
97973  struct SrcList_item *pFrom;
97974
97975  assert( p->selFlags & SF_Resolved );
97976  if( (p->selFlags & SF_HasTypeInfo)==0 ){
97977    p->selFlags |= SF_HasTypeInfo;
97978    pParse = pWalker->pParse;
97979    pTabList = p->pSrc;
97980    for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
97981      Table *pTab = pFrom->pTab;
97982      if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
97983        /* A sub-query in the FROM clause of a SELECT */
97984        Select *pSel = pFrom->pSelect;
97985        assert( pSel );
97986        while( pSel->pPrior ) pSel = pSel->pPrior;
97987        selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
97988      }
97989    }
97990  }
97991  return WRC_Continue;
97992}
97993#endif
97994
97995
97996/*
97997** This routine adds datatype and collating sequence information to
97998** the Table structures of all FROM-clause subqueries in a
97999** SELECT statement.
98000**
98001** Use this routine after name resolution.
98002*/
98003static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
98004#ifndef SQLITE_OMIT_SUBQUERY
98005  Walker w;
98006  w.xSelectCallback = selectAddSubqueryTypeInfo;
98007  w.xExprCallback = exprWalkNoop;
98008  w.pParse = pParse;
98009  sqlite3WalkSelect(&w, pSelect);
98010#endif
98011}
98012
98013
98014/*
98015** This routine sets of a SELECT statement for processing.  The
98016** following is accomplished:
98017**
98018**     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
98019**     *  Ephemeral Table objects are created for all FROM-clause subqueries.
98020**     *  ON and USING clauses are shifted into WHERE statements
98021**     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
98022**     *  Identifiers in expression are matched to tables.
98023**
98024** This routine acts recursively on all subqueries within the SELECT.
98025*/
98026SQLITE_PRIVATE void sqlite3SelectPrep(
98027  Parse *pParse,         /* The parser context */
98028  Select *p,             /* The SELECT statement being coded. */
98029  NameContext *pOuterNC  /* Name context for container */
98030){
98031  sqlite3 *db;
98032  if( NEVER(p==0) ) return;
98033  db = pParse->db;
98034  if( p->selFlags & SF_HasTypeInfo ) return;
98035  sqlite3SelectExpand(pParse, p);
98036  if( pParse->nErr || db->mallocFailed ) return;
98037  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
98038  if( pParse->nErr || db->mallocFailed ) return;
98039  sqlite3SelectAddTypeInfo(pParse, p);
98040}
98041
98042/*
98043** Reset the aggregate accumulator.
98044**
98045** The aggregate accumulator is a set of memory cells that hold
98046** intermediate results while calculating an aggregate.  This
98047** routine simply stores NULLs in all of those memory cells.
98048*/
98049static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
98050  Vdbe *v = pParse->pVdbe;
98051  int i;
98052  struct AggInfo_func *pFunc;
98053  if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
98054    return;
98055  }
98056  for(i=0; i<pAggInfo->nColumn; i++){
98057    sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
98058  }
98059  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
98060    sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
98061    if( pFunc->iDistinct>=0 ){
98062      Expr *pE = pFunc->pExpr;
98063      assert( !ExprHasProperty(pE, EP_xIsSelect) );
98064      if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
98065        sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
98066           "argument");
98067        pFunc->iDistinct = -1;
98068      }else{
98069        KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
98070        sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
98071                          (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98072      }
98073    }
98074  }
98075}
98076
98077/*
98078** Invoke the OP_AggFinalize opcode for every aggregate function
98079** in the AggInfo structure.
98080*/
98081static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
98082  Vdbe *v = pParse->pVdbe;
98083  int i;
98084  struct AggInfo_func *pF;
98085  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
98086    ExprList *pList = pF->pExpr->x.pList;
98087    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
98088    sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
98089                      (void*)pF->pFunc, P4_FUNCDEF);
98090  }
98091}
98092
98093/*
98094** Update the accumulator memory cells for an aggregate based on
98095** the current cursor position.
98096*/
98097static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
98098  Vdbe *v = pParse->pVdbe;
98099  int i;
98100  int regHit = 0;
98101  int addrHitTest = 0;
98102  struct AggInfo_func *pF;
98103  struct AggInfo_col *pC;
98104
98105  pAggInfo->directMode = 1;
98106  sqlite3ExprCacheClear(pParse);
98107  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
98108    int nArg;
98109    int addrNext = 0;
98110    int regAgg;
98111    ExprList *pList = pF->pExpr->x.pList;
98112    assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
98113    if( pList ){
98114      nArg = pList->nExpr;
98115      regAgg = sqlite3GetTempRange(pParse, nArg);
98116      sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
98117    }else{
98118      nArg = 0;
98119      regAgg = 0;
98120    }
98121    if( pF->iDistinct>=0 ){
98122      addrNext = sqlite3VdbeMakeLabel(v);
98123      assert( nArg==1 );
98124      codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
98125    }
98126    if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
98127      CollSeq *pColl = 0;
98128      struct ExprList_item *pItem;
98129      int j;
98130      assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
98131      for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
98132        pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
98133      }
98134      if( !pColl ){
98135        pColl = pParse->db->pDfltColl;
98136      }
98137      if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
98138      sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
98139    }
98140    sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
98141                      (void*)pF->pFunc, P4_FUNCDEF);
98142    sqlite3VdbeChangeP5(v, (u8)nArg);
98143    sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
98144    sqlite3ReleaseTempRange(pParse, regAgg, nArg);
98145    if( addrNext ){
98146      sqlite3VdbeResolveLabel(v, addrNext);
98147      sqlite3ExprCacheClear(pParse);
98148    }
98149  }
98150
98151  /* Before populating the accumulator registers, clear the column cache.
98152  ** Otherwise, if any of the required column values are already present
98153  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
98154  ** to pC->iMem. But by the time the value is used, the original register
98155  ** may have been used, invalidating the underlying buffer holding the
98156  ** text or blob value. See ticket [883034dcb5].
98157  **
98158  ** Another solution would be to change the OP_SCopy used to copy cached
98159  ** values to an OP_Copy.
98160  */
98161  if( regHit ){
98162    addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
98163  }
98164  sqlite3ExprCacheClear(pParse);
98165  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
98166    sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
98167  }
98168  pAggInfo->directMode = 0;
98169  sqlite3ExprCacheClear(pParse);
98170  if( addrHitTest ){
98171    sqlite3VdbeJumpHere(v, addrHitTest);
98172  }
98173}
98174
98175/*
98176** Add a single OP_Explain instruction to the VDBE to explain a simple
98177** count(*) query ("SELECT count(*) FROM pTab").
98178*/
98179#ifndef SQLITE_OMIT_EXPLAIN
98180static void explainSimpleCount(
98181  Parse *pParse,                  /* Parse context */
98182  Table *pTab,                    /* Table being queried */
98183  Index *pIdx                     /* Index used to optimize scan, or NULL */
98184){
98185  if( pParse->explain==2 ){
98186    char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
98187        pTab->zName,
98188        pIdx ? "USING COVERING INDEX " : "",
98189        pIdx ? pIdx->zName : "",
98190        pTab->nRowEst
98191    );
98192    sqlite3VdbeAddOp4(
98193        pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
98194    );
98195  }
98196}
98197#else
98198# define explainSimpleCount(a,b,c)
98199#endif
98200
98201/*
98202** Generate code for the SELECT statement given in the p argument.
98203**
98204** The results are distributed in various ways depending on the
98205** contents of the SelectDest structure pointed to by argument pDest
98206** as follows:
98207**
98208**     pDest->eDest    Result
98209**     ------------    -------------------------------------------
98210**     SRT_Output      Generate a row of output (using the OP_ResultRow
98211**                     opcode) for each row in the result set.
98212**
98213**     SRT_Mem         Only valid if the result is a single column.
98214**                     Store the first column of the first result row
98215**                     in register pDest->iParm then abandon the rest
98216**                     of the query.  This destination implies "LIMIT 1".
98217**
98218**     SRT_Set         The result must be a single column.  Store each
98219**                     row of result as the key in table pDest->iParm.
98220**                     Apply the affinity pDest->affinity before storing
98221**                     results.  Used to implement "IN (SELECT ...)".
98222**
98223**     SRT_Union       Store results as a key in a temporary table pDest->iParm.
98224**
98225**     SRT_Except      Remove results from the temporary table pDest->iParm.
98226**
98227**     SRT_Table       Store results in temporary table pDest->iParm.
98228**                     This is like SRT_EphemTab except that the table
98229**                     is assumed to already be open.
98230**
98231**     SRT_EphemTab    Create an temporary table pDest->iParm and store
98232**                     the result there. The cursor is left open after
98233**                     returning.  This is like SRT_Table except that
98234**                     this destination uses OP_OpenEphemeral to create
98235**                     the table first.
98236**
98237**     SRT_Coroutine   Generate a co-routine that returns a new row of
98238**                     results each time it is invoked.  The entry point
98239**                     of the co-routine is stored in register pDest->iParm.
98240**
98241**     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
98242**                     set is not empty.
98243**
98244**     SRT_Discard     Throw the results away.  This is used by SELECT
98245**                     statements within triggers whose only purpose is
98246**                     the side-effects of functions.
98247**
98248** This routine returns the number of errors.  If any errors are
98249** encountered, then an appropriate error message is left in
98250** pParse->zErrMsg.
98251**
98252** This routine does NOT free the Select structure passed in.  The
98253** calling function needs to do that.
98254*/
98255SQLITE_PRIVATE int sqlite3Select(
98256  Parse *pParse,         /* The parser context */
98257  Select *p,             /* The SELECT statement being coded. */
98258  SelectDest *pDest      /* What to do with the query results */
98259){
98260  int i, j;              /* Loop counters */
98261  WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
98262  Vdbe *v;               /* The virtual machine under construction */
98263  int isAgg;             /* True for select lists like "count(*)" */
98264  ExprList *pEList;      /* List of columns to extract. */
98265  SrcList *pTabList;     /* List of tables to select from */
98266  Expr *pWhere;          /* The WHERE clause.  May be NULL */
98267  ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
98268  ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
98269  Expr *pHaving;         /* The HAVING clause.  May be NULL */
98270  int isDistinct;        /* True if the DISTINCT keyword is present */
98271  int distinct;          /* Table to use for the distinct set */
98272  int rc = 1;            /* Value to return from this function */
98273  int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
98274  int addrDistinctIndex; /* Address of an OP_OpenEphemeral instruction */
98275  AggInfo sAggInfo;      /* Information used by aggregate queries */
98276  int iEnd;              /* Address of the end of the query */
98277  sqlite3 *db;           /* The database connection */
98278
98279#ifndef SQLITE_OMIT_EXPLAIN
98280  int iRestoreSelectId = pParse->iSelectId;
98281  pParse->iSelectId = pParse->iNextSelectId++;
98282#endif
98283
98284  db = pParse->db;
98285  if( p==0 || db->mallocFailed || pParse->nErr ){
98286    return 1;
98287  }
98288  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
98289  memset(&sAggInfo, 0, sizeof(sAggInfo));
98290
98291  if( IgnorableOrderby(pDest) ){
98292    assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
98293           pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
98294    /* If ORDER BY makes no difference in the output then neither does
98295    ** DISTINCT so it can be removed too. */
98296    sqlite3ExprListDelete(db, p->pOrderBy);
98297    p->pOrderBy = 0;
98298    p->selFlags &= ~SF_Distinct;
98299  }
98300  sqlite3SelectPrep(pParse, p, 0);
98301  pOrderBy = p->pOrderBy;
98302  pTabList = p->pSrc;
98303  pEList = p->pEList;
98304  if( pParse->nErr || db->mallocFailed ){
98305    goto select_end;
98306  }
98307  isAgg = (p->selFlags & SF_Aggregate)!=0;
98308  assert( pEList!=0 );
98309
98310  /* Begin generating code.
98311  */
98312  v = sqlite3GetVdbe(pParse);
98313  if( v==0 ) goto select_end;
98314
98315  /* If writing to memory or generating a set
98316  ** only a single column may be output.
98317  */
98318#ifndef SQLITE_OMIT_SUBQUERY
98319  if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
98320    goto select_end;
98321  }
98322#endif
98323
98324  /* Generate code for all sub-queries in the FROM clause
98325  */
98326#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98327  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
98328    struct SrcList_item *pItem = &pTabList->a[i];
98329    SelectDest dest;
98330    Select *pSub = pItem->pSelect;
98331    int isAggSub;
98332
98333    if( pSub==0 ) continue;
98334    if( pItem->addrFillSub ){
98335      sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
98336      continue;
98337    }
98338
98339    /* Increment Parse.nHeight by the height of the largest expression
98340    ** tree refered to by this, the parent select. The child select
98341    ** may contain expression trees of at most
98342    ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
98343    ** more conservative than necessary, but much easier than enforcing
98344    ** an exact limit.
98345    */
98346    pParse->nHeight += sqlite3SelectExprHeight(p);
98347
98348    isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
98349    if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
98350      /* This subquery can be absorbed into its parent. */
98351      if( isAggSub ){
98352        isAgg = 1;
98353        p->selFlags |= SF_Aggregate;
98354      }
98355      i = -1;
98356    }else{
98357      /* Generate a subroutine that will fill an ephemeral table with
98358      ** the content of this subquery.  pItem->addrFillSub will point
98359      ** to the address of the generated subroutine.  pItem->regReturn
98360      ** is a register allocated to hold the subroutine return address
98361      */
98362      int topAddr;
98363      int onceAddr = 0;
98364      int retAddr;
98365      assert( pItem->addrFillSub==0 );
98366      pItem->regReturn = ++pParse->nMem;
98367      topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
98368      pItem->addrFillSub = topAddr+1;
98369      VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
98370      if( pItem->isCorrelated==0 ){
98371        /* If the subquery is no correlated and if we are not inside of
98372        ** a trigger, then we only need to compute the value of the subquery
98373        ** once. */
98374        onceAddr = sqlite3CodeOnce(pParse);
98375      }
98376      sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
98377      explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
98378      sqlite3Select(pParse, pSub, &dest);
98379      pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
98380      if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
98381      retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
98382      VdbeComment((v, "end %s", pItem->pTab->zName));
98383      sqlite3VdbeChangeP1(v, topAddr, retAddr);
98384      sqlite3ClearTempRegCache(pParse);
98385    }
98386    if( /*pParse->nErr ||*/ db->mallocFailed ){
98387      goto select_end;
98388    }
98389    pParse->nHeight -= sqlite3SelectExprHeight(p);
98390    pTabList = p->pSrc;
98391    if( !IgnorableOrderby(pDest) ){
98392      pOrderBy = p->pOrderBy;
98393    }
98394  }
98395  pEList = p->pEList;
98396#endif
98397  pWhere = p->pWhere;
98398  pGroupBy = p->pGroupBy;
98399  pHaving = p->pHaving;
98400  isDistinct = (p->selFlags & SF_Distinct)!=0;
98401
98402#ifndef SQLITE_OMIT_COMPOUND_SELECT
98403  /* If there is are a sequence of queries, do the earlier ones first.
98404  */
98405  if( p->pPrior ){
98406    if( p->pRightmost==0 ){
98407      Select *pLoop, *pRight = 0;
98408      int cnt = 0;
98409      int mxSelect;
98410      for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
98411        pLoop->pRightmost = p;
98412        pLoop->pNext = pRight;
98413        pRight = pLoop;
98414      }
98415      mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
98416      if( mxSelect && cnt>mxSelect ){
98417        sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
98418        goto select_end;
98419      }
98420    }
98421    rc = multiSelect(pParse, p, pDest);
98422    explainSetInteger(pParse->iSelectId, iRestoreSelectId);
98423    return rc;
98424  }
98425#endif
98426
98427  /* If there is both a GROUP BY and an ORDER BY clause and they are
98428  ** identical, then disable the ORDER BY clause since the GROUP BY
98429  ** will cause elements to come out in the correct order.  This is
98430  ** an optimization - the correct answer should result regardless.
98431  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
98432  ** to disable this optimization for testing purposes.
98433  */
98434  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
98435         && (db->flags & SQLITE_GroupByOrder)==0 ){
98436    pOrderBy = 0;
98437  }
98438
98439  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
98440  ** if the select-list is the same as the ORDER BY list, then this query
98441  ** can be rewritten as a GROUP BY. In other words, this:
98442  **
98443  **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
98444  **
98445  ** is transformed to:
98446  **
98447  **     SELECT xyz FROM ... GROUP BY xyz
98448  **
98449  ** The second form is preferred as a single index (or temp-table) may be
98450  ** used for both the ORDER BY and DISTINCT processing. As originally
98451  ** written the query must use a temp-table for at least one of the ORDER
98452  ** BY and DISTINCT, and an index or separate temp-table for the other.
98453  */
98454  if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
98455   && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
98456  ){
98457    p->selFlags &= ~SF_Distinct;
98458    p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
98459    pGroupBy = p->pGroupBy;
98460    pOrderBy = 0;
98461  }
98462
98463  /* If there is an ORDER BY clause, then this sorting
98464  ** index might end up being unused if the data can be
98465  ** extracted in pre-sorted order.  If that is the case, then the
98466  ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
98467  ** we figure out that the sorting index is not needed.  The addrSortIndex
98468  ** variable is used to facilitate that change.
98469  */
98470  if( pOrderBy ){
98471    KeyInfo *pKeyInfo;
98472    pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
98473    pOrderBy->iECursor = pParse->nTab++;
98474    p->addrOpenEphm[2] = addrSortIndex =
98475      sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
98476                           pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
98477                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98478  }else{
98479    addrSortIndex = -1;
98480  }
98481
98482  /* If the output is destined for a temporary table, open that table.
98483  */
98484  if( pDest->eDest==SRT_EphemTab ){
98485    sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
98486  }
98487
98488  /* Set the limiter.
98489  */
98490  iEnd = sqlite3VdbeMakeLabel(v);
98491  p->nSelectRow = (double)LARGEST_INT64;
98492  computeLimitRegisters(pParse, p, iEnd);
98493  if( p->iLimit==0 && addrSortIndex>=0 ){
98494    sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
98495    p->selFlags |= SF_UseSorter;
98496  }
98497
98498  /* Open a virtual index to use for the distinct set.
98499  */
98500  if( p->selFlags & SF_Distinct ){
98501    KeyInfo *pKeyInfo;
98502    distinct = pParse->nTab++;
98503    pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
98504    addrDistinctIndex = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
98505        (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98506    sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
98507  }else{
98508    distinct = addrDistinctIndex = -1;
98509  }
98510
98511  /* Aggregate and non-aggregate queries are handled differently */
98512  if( !isAgg && pGroupBy==0 ){
98513    ExprList *pDist = (isDistinct ? p->pEList : 0);
98514
98515    /* Begin the database scan. */
98516    pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, pDist, 0);
98517    if( pWInfo==0 ) goto select_end;
98518    if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
98519
98520    /* If sorting index that was created by a prior OP_OpenEphemeral
98521    ** instruction ended up not being needed, then change the OP_OpenEphemeral
98522    ** into an OP_Noop.
98523    */
98524    if( addrSortIndex>=0 && pOrderBy==0 ){
98525      sqlite3VdbeChangeToNoop(v, addrSortIndex);
98526      p->addrOpenEphm[2] = -1;
98527    }
98528
98529    if( pWInfo->eDistinct ){
98530      VdbeOp *pOp;                /* No longer required OpenEphemeral instr. */
98531
98532      assert( addrDistinctIndex>=0 );
98533      pOp = sqlite3VdbeGetOp(v, addrDistinctIndex);
98534
98535      assert( isDistinct );
98536      assert( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
98537           || pWInfo->eDistinct==WHERE_DISTINCT_UNIQUE
98538      );
98539      distinct = -1;
98540      if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED ){
98541        int iJump;
98542        int iExpr;
98543        int iFlag = ++pParse->nMem;
98544        int iBase = pParse->nMem+1;
98545        int iBase2 = iBase + pEList->nExpr;
98546        pParse->nMem += (pEList->nExpr*2);
98547
98548        /* Change the OP_OpenEphemeral coded earlier to an OP_Integer. The
98549        ** OP_Integer initializes the "first row" flag.  */
98550        pOp->opcode = OP_Integer;
98551        pOp->p1 = 1;
98552        pOp->p2 = iFlag;
98553
98554        sqlite3ExprCodeExprList(pParse, pEList, iBase, 1);
98555        iJump = sqlite3VdbeCurrentAddr(v) + 1 + pEList->nExpr + 1 + 1;
98556        sqlite3VdbeAddOp2(v, OP_If, iFlag, iJump-1);
98557        for(iExpr=0; iExpr<pEList->nExpr; iExpr++){
98558          CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[iExpr].pExpr);
98559          sqlite3VdbeAddOp3(v, OP_Ne, iBase+iExpr, iJump, iBase2+iExpr);
98560          sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
98561          sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
98562        }
98563        sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iContinue);
98564
98565        sqlite3VdbeAddOp2(v, OP_Integer, 0, iFlag);
98566        assert( sqlite3VdbeCurrentAddr(v)==iJump );
98567        sqlite3VdbeAddOp3(v, OP_Move, iBase, iBase2, pEList->nExpr);
98568      }else{
98569        pOp->opcode = OP_Noop;
98570      }
98571    }
98572
98573    /* Use the standard inner loop. */
98574    selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, pDest,
98575                    pWInfo->iContinue, pWInfo->iBreak);
98576
98577    /* End the database scan loop.
98578    */
98579    sqlite3WhereEnd(pWInfo);
98580  }else{
98581    /* This is the processing for aggregate queries */
98582    NameContext sNC;    /* Name context for processing aggregate information */
98583    int iAMem;          /* First Mem address for storing current GROUP BY */
98584    int iBMem;          /* First Mem address for previous GROUP BY */
98585    int iUseFlag;       /* Mem address holding flag indicating that at least
98586                        ** one row of the input to the aggregator has been
98587                        ** processed */
98588    int iAbortFlag;     /* Mem address which causes query abort if positive */
98589    int groupBySort;    /* Rows come from source in GROUP BY order */
98590    int addrEnd;        /* End of processing for this SELECT */
98591    int sortPTab = 0;   /* Pseudotable used to decode sorting results */
98592    int sortOut = 0;    /* Output register from the sorter */
98593
98594    /* Remove any and all aliases between the result set and the
98595    ** GROUP BY clause.
98596    */
98597    if( pGroupBy ){
98598      int k;                        /* Loop counter */
98599      struct ExprList_item *pItem;  /* For looping over expression in a list */
98600
98601      for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
98602        pItem->iAlias = 0;
98603      }
98604      for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
98605        pItem->iAlias = 0;
98606      }
98607      if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
98608    }else{
98609      p->nSelectRow = (double)1;
98610    }
98611
98612
98613    /* Create a label to jump to when we want to abort the query */
98614    addrEnd = sqlite3VdbeMakeLabel(v);
98615
98616    /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
98617    ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
98618    ** SELECT statement.
98619    */
98620    memset(&sNC, 0, sizeof(sNC));
98621    sNC.pParse = pParse;
98622    sNC.pSrcList = pTabList;
98623    sNC.pAggInfo = &sAggInfo;
98624    sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
98625    sAggInfo.pGroupBy = pGroupBy;
98626    sqlite3ExprAnalyzeAggList(&sNC, pEList);
98627    sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
98628    if( pHaving ){
98629      sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
98630    }
98631    sAggInfo.nAccumulator = sAggInfo.nColumn;
98632    for(i=0; i<sAggInfo.nFunc; i++){
98633      assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
98634      sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
98635    }
98636    if( db->mallocFailed ) goto select_end;
98637
98638    /* Processing for aggregates with GROUP BY is very different and
98639    ** much more complex than aggregates without a GROUP BY.
98640    */
98641    if( pGroupBy ){
98642      KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
98643      int j1;             /* A-vs-B comparision jump */
98644      int addrOutputRow;  /* Start of subroutine that outputs a result row */
98645      int regOutputRow;   /* Return address register for output subroutine */
98646      int addrSetAbort;   /* Set the abort flag and return */
98647      int addrTopOfLoop;  /* Top of the input loop */
98648      int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
98649      int addrReset;      /* Subroutine for resetting the accumulator */
98650      int regReset;       /* Return address register for reset subroutine */
98651
98652      /* If there is a GROUP BY clause we might need a sorting index to
98653      ** implement it.  Allocate that sorting index now.  If it turns out
98654      ** that we do not need it after all, the OP_SorterOpen instruction
98655      ** will be converted into a Noop.
98656      */
98657      sAggInfo.sortingIdx = pParse->nTab++;
98658      pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
98659      addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
98660          sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
98661          0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
98662
98663      /* Initialize memory locations used by GROUP BY aggregate processing
98664      */
98665      iUseFlag = ++pParse->nMem;
98666      iAbortFlag = ++pParse->nMem;
98667      regOutputRow = ++pParse->nMem;
98668      addrOutputRow = sqlite3VdbeMakeLabel(v);
98669      regReset = ++pParse->nMem;
98670      addrReset = sqlite3VdbeMakeLabel(v);
98671      iAMem = pParse->nMem + 1;
98672      pParse->nMem += pGroupBy->nExpr;
98673      iBMem = pParse->nMem + 1;
98674      pParse->nMem += pGroupBy->nExpr;
98675      sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
98676      VdbeComment((v, "clear abort flag"));
98677      sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
98678      VdbeComment((v, "indicate accumulator empty"));
98679      sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
98680
98681      /* Begin a loop that will extract all source rows in GROUP BY order.
98682      ** This might involve two separate loops with an OP_Sort in between, or
98683      ** it might be a single loop that uses an index to extract information
98684      ** in the right order to begin with.
98685      */
98686      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98687      pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0, 0);
98688      if( pWInfo==0 ) goto select_end;
98689      if( pGroupBy==0 ){
98690        /* The optimizer is able to deliver rows in group by order so
98691        ** we do not have to sort.  The OP_OpenEphemeral table will be
98692        ** cancelled later because we still need to use the pKeyInfo
98693        */
98694        pGroupBy = p->pGroupBy;
98695        groupBySort = 0;
98696      }else{
98697        /* Rows are coming out in undetermined order.  We have to push
98698        ** each row into a sorting index, terminate the first loop,
98699        ** then loop over the sorting index in order to get the output
98700        ** in sorted order
98701        */
98702        int regBase;
98703        int regRecord;
98704        int nCol;
98705        int nGroupBy;
98706
98707        explainTempTable(pParse,
98708            isDistinct && !(p->selFlags&SF_Distinct)?"DISTINCT":"GROUP BY");
98709
98710        groupBySort = 1;
98711        nGroupBy = pGroupBy->nExpr;
98712        nCol = nGroupBy + 1;
98713        j = nGroupBy+1;
98714        for(i=0; i<sAggInfo.nColumn; i++){
98715          if( sAggInfo.aCol[i].iSorterColumn>=j ){
98716            nCol++;
98717            j++;
98718          }
98719        }
98720        regBase = sqlite3GetTempRange(pParse, nCol);
98721        sqlite3ExprCacheClear(pParse);
98722        sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
98723        sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
98724        j = nGroupBy+1;
98725        for(i=0; i<sAggInfo.nColumn; i++){
98726          struct AggInfo_col *pCol = &sAggInfo.aCol[i];
98727          if( pCol->iSorterColumn>=j ){
98728            int r1 = j + regBase;
98729            int r2;
98730
98731            r2 = sqlite3ExprCodeGetColumn(pParse,
98732                               pCol->pTab, pCol->iColumn, pCol->iTable, r1);
98733            if( r1!=r2 ){
98734              sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
98735            }
98736            j++;
98737          }
98738        }
98739        regRecord = sqlite3GetTempReg(pParse);
98740        sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
98741        sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
98742        sqlite3ReleaseTempReg(pParse, regRecord);
98743        sqlite3ReleaseTempRange(pParse, regBase, nCol);
98744        sqlite3WhereEnd(pWInfo);
98745        sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
98746        sortOut = sqlite3GetTempReg(pParse);
98747        sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
98748        sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
98749        VdbeComment((v, "GROUP BY sort"));
98750        sAggInfo.useSortingIdx = 1;
98751        sqlite3ExprCacheClear(pParse);
98752      }
98753
98754      /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
98755      ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
98756      ** Then compare the current GROUP BY terms against the GROUP BY terms
98757      ** from the previous row currently stored in a0, a1, a2...
98758      */
98759      addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
98760      sqlite3ExprCacheClear(pParse);
98761      if( groupBySort ){
98762        sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
98763      }
98764      for(j=0; j<pGroupBy->nExpr; j++){
98765        if( groupBySort ){
98766          sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
98767          if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
98768        }else{
98769          sAggInfo.directMode = 1;
98770          sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
98771        }
98772      }
98773      sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
98774                          (char*)pKeyInfo, P4_KEYINFO);
98775      j1 = sqlite3VdbeCurrentAddr(v);
98776      sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
98777
98778      /* Generate code that runs whenever the GROUP BY changes.
98779      ** Changes in the GROUP BY are detected by the previous code
98780      ** block.  If there were no changes, this block is skipped.
98781      **
98782      ** This code copies current group by terms in b0,b1,b2,...
98783      ** over to a0,a1,a2.  It then calls the output subroutine
98784      ** and resets the aggregate accumulator registers in preparation
98785      ** for the next GROUP BY batch.
98786      */
98787      sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
98788      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98789      VdbeComment((v, "output one row"));
98790      sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
98791      VdbeComment((v, "check abort flag"));
98792      sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
98793      VdbeComment((v, "reset accumulator"));
98794
98795      /* Update the aggregate accumulators based on the content of
98796      ** the current row
98797      */
98798      sqlite3VdbeJumpHere(v, j1);
98799      updateAccumulator(pParse, &sAggInfo);
98800      sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
98801      VdbeComment((v, "indicate data in accumulator"));
98802
98803      /* End of the loop
98804      */
98805      if( groupBySort ){
98806        sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
98807      }else{
98808        sqlite3WhereEnd(pWInfo);
98809        sqlite3VdbeChangeToNoop(v, addrSortingIdx);
98810      }
98811
98812      /* Output the final row of result
98813      */
98814      sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
98815      VdbeComment((v, "output final row"));
98816
98817      /* Jump over the subroutines
98818      */
98819      sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
98820
98821      /* Generate a subroutine that outputs a single row of the result
98822      ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
98823      ** is less than or equal to zero, the subroutine is a no-op.  If
98824      ** the processing calls for the query to abort, this subroutine
98825      ** increments the iAbortFlag memory location before returning in
98826      ** order to signal the caller to abort.
98827      */
98828      addrSetAbort = sqlite3VdbeCurrentAddr(v);
98829      sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
98830      VdbeComment((v, "set abort flag"));
98831      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
98832      sqlite3VdbeResolveLabel(v, addrOutputRow);
98833      addrOutputRow = sqlite3VdbeCurrentAddr(v);
98834      sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
98835      VdbeComment((v, "Groupby result generator entry point"));
98836      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
98837      finalizeAggFunctions(pParse, &sAggInfo);
98838      sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
98839      selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
98840                      distinct, pDest,
98841                      addrOutputRow+1, addrSetAbort);
98842      sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
98843      VdbeComment((v, "end groupby result generator"));
98844
98845      /* Generate a subroutine that will reset the group-by accumulator
98846      */
98847      sqlite3VdbeResolveLabel(v, addrReset);
98848      resetAccumulator(pParse, &sAggInfo);
98849      sqlite3VdbeAddOp1(v, OP_Return, regReset);
98850
98851    } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
98852    else {
98853      ExprList *pDel = 0;
98854#ifndef SQLITE_OMIT_BTREECOUNT
98855      Table *pTab;
98856      if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
98857        /* If isSimpleCount() returns a pointer to a Table structure, then
98858        ** the SQL statement is of the form:
98859        **
98860        **   SELECT count(*) FROM <tbl>
98861        **
98862        ** where the Table structure returned represents table <tbl>.
98863        **
98864        ** This statement is so common that it is optimized specially. The
98865        ** OP_Count instruction is executed either on the intkey table that
98866        ** contains the data for table <tbl> or on one of its indexes. It
98867        ** is better to execute the op on an index, as indexes are almost
98868        ** always spread across less pages than their corresponding tables.
98869        */
98870        const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
98871        const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
98872        Index *pIdx;                         /* Iterator variable */
98873        KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
98874        Index *pBest = 0;                    /* Best index found so far */
98875        int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
98876
98877        sqlite3CodeVerifySchema(pParse, iDb);
98878        sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
98879
98880        /* Search for the index that has the least amount of columns. If
98881        ** there is such an index, and it has less columns than the table
98882        ** does, then we can assume that it consumes less space on disk and
98883        ** will therefore be cheaper to scan to determine the query result.
98884        ** In this case set iRoot to the root page number of the index b-tree
98885        ** and pKeyInfo to the KeyInfo structure required to navigate the
98886        ** index.
98887        **
98888        ** (2011-04-15) Do not do a full scan of an unordered index.
98889        **
98890        ** In practice the KeyInfo structure will not be used. It is only
98891        ** passed to keep OP_OpenRead happy.
98892        */
98893        for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98894          if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
98895            pBest = pIdx;
98896          }
98897        }
98898        if( pBest && pBest->nColumn<pTab->nCol ){
98899          iRoot = pBest->tnum;
98900          pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
98901        }
98902
98903        /* Open a read-only cursor, execute the OP_Count, close the cursor. */
98904        sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
98905        if( pKeyInfo ){
98906          sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
98907        }
98908        sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
98909        sqlite3VdbeAddOp1(v, OP_Close, iCsr);
98910        explainSimpleCount(pParse, pTab, pBest);
98911      }else
98912#endif /* SQLITE_OMIT_BTREECOUNT */
98913      {
98914        /* Check if the query is of one of the following forms:
98915        **
98916        **   SELECT min(x) FROM ...
98917        **   SELECT max(x) FROM ...
98918        **
98919        ** If it is, then ask the code in where.c to attempt to sort results
98920        ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
98921        ** If where.c is able to produce results sorted in this order, then
98922        ** add vdbe code to break out of the processing loop after the
98923        ** first iteration (since the first iteration of the loop is
98924        ** guaranteed to operate on the row with the minimum or maximum
98925        ** value of x, the only row required).
98926        **
98927        ** A special flag must be passed to sqlite3WhereBegin() to slightly
98928        ** modify behaviour as follows:
98929        **
98930        **   + If the query is a "SELECT min(x)", then the loop coded by
98931        **     where.c should not iterate over any values with a NULL value
98932        **     for x.
98933        **
98934        **   + The optimizer code in where.c (the thing that decides which
98935        **     index or indices to use) should place a different priority on
98936        **     satisfying the 'ORDER BY' clause than it does in other cases.
98937        **     Refer to code and comments in where.c for details.
98938        */
98939        ExprList *pMinMax = 0;
98940        u8 flag = minMaxQuery(p);
98941        if( flag ){
98942          assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
98943          pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
98944          pDel = pMinMax;
98945          if( pMinMax && !db->mallocFailed ){
98946            pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
98947            pMinMax->a[0].pExpr->op = TK_COLUMN;
98948          }
98949        }
98950
98951        /* This case runs if the aggregate has no GROUP BY clause.  The
98952        ** processing is much simpler since there is only a single row
98953        ** of output.
98954        */
98955        resetAccumulator(pParse, &sAggInfo);
98956        pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, 0, flag);
98957        if( pWInfo==0 ){
98958          sqlite3ExprListDelete(db, pDel);
98959          goto select_end;
98960        }
98961        updateAccumulator(pParse, &sAggInfo);
98962        if( !pMinMax && flag ){
98963          sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
98964          VdbeComment((v, "%s() by index",
98965                (flag==WHERE_ORDERBY_MIN?"min":"max")));
98966        }
98967        sqlite3WhereEnd(pWInfo);
98968        finalizeAggFunctions(pParse, &sAggInfo);
98969      }
98970
98971      pOrderBy = 0;
98972      sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
98973      selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1,
98974                      pDest, addrEnd, addrEnd);
98975      sqlite3ExprListDelete(db, pDel);
98976    }
98977    sqlite3VdbeResolveLabel(v, addrEnd);
98978
98979  } /* endif aggregate query */
98980
98981  if( distinct>=0 ){
98982    explainTempTable(pParse, "DISTINCT");
98983  }
98984
98985  /* If there is an ORDER BY clause, then we need to sort the results
98986  ** and send them to the callback one by one.
98987  */
98988  if( pOrderBy ){
98989    explainTempTable(pParse, "ORDER BY");
98990    generateSortTail(pParse, p, v, pEList->nExpr, pDest);
98991  }
98992
98993  /* Jump here to skip this query
98994  */
98995  sqlite3VdbeResolveLabel(v, iEnd);
98996
98997  /* The SELECT was successfully coded.   Set the return code to 0
98998  ** to indicate no errors.
98999  */
99000  rc = 0;
99001
99002  /* Control jumps to here if an error is encountered above, or upon
99003  ** successful coding of the SELECT.
99004  */
99005select_end:
99006  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
99007
99008  /* Identify column names if results of the SELECT are to be output.
99009  */
99010  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
99011    generateColumnNames(pParse, pTabList, pEList);
99012  }
99013
99014  sqlite3DbFree(db, sAggInfo.aCol);
99015  sqlite3DbFree(db, sAggInfo.aFunc);
99016  return rc;
99017}
99018
99019#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
99020/*
99021** Generate a human-readable description of a the Select object.
99022*/
99023static void explainOneSelect(Vdbe *pVdbe, Select *p){
99024  sqlite3ExplainPrintf(pVdbe, "SELECT ");
99025  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
99026    if( p->selFlags & SF_Distinct ){
99027      sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
99028    }
99029    if( p->selFlags & SF_Aggregate ){
99030      sqlite3ExplainPrintf(pVdbe, "agg_flag ");
99031    }
99032    sqlite3ExplainNL(pVdbe);
99033    sqlite3ExplainPrintf(pVdbe, "   ");
99034  }
99035  sqlite3ExplainExprList(pVdbe, p->pEList);
99036  sqlite3ExplainNL(pVdbe);
99037  if( p->pSrc && p->pSrc->nSrc ){
99038    int i;
99039    sqlite3ExplainPrintf(pVdbe, "FROM ");
99040    sqlite3ExplainPush(pVdbe);
99041    for(i=0; i<p->pSrc->nSrc; i++){
99042      struct SrcList_item *pItem = &p->pSrc->a[i];
99043      sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
99044      if( pItem->pSelect ){
99045        sqlite3ExplainSelect(pVdbe, pItem->pSelect);
99046        if( pItem->pTab ){
99047          sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
99048        }
99049      }else if( pItem->zName ){
99050        sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
99051      }
99052      if( pItem->zAlias ){
99053        sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
99054      }
99055      if( pItem->jointype & JT_LEFT ){
99056        sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
99057      }
99058      sqlite3ExplainNL(pVdbe);
99059    }
99060    sqlite3ExplainPop(pVdbe);
99061  }
99062  if( p->pWhere ){
99063    sqlite3ExplainPrintf(pVdbe, "WHERE ");
99064    sqlite3ExplainExpr(pVdbe, p->pWhere);
99065    sqlite3ExplainNL(pVdbe);
99066  }
99067  if( p->pGroupBy ){
99068    sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
99069    sqlite3ExplainExprList(pVdbe, p->pGroupBy);
99070    sqlite3ExplainNL(pVdbe);
99071  }
99072  if( p->pHaving ){
99073    sqlite3ExplainPrintf(pVdbe, "HAVING ");
99074    sqlite3ExplainExpr(pVdbe, p->pHaving);
99075    sqlite3ExplainNL(pVdbe);
99076  }
99077  if( p->pOrderBy ){
99078    sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
99079    sqlite3ExplainExprList(pVdbe, p->pOrderBy);
99080    sqlite3ExplainNL(pVdbe);
99081  }
99082  if( p->pLimit ){
99083    sqlite3ExplainPrintf(pVdbe, "LIMIT ");
99084    sqlite3ExplainExpr(pVdbe, p->pLimit);
99085    sqlite3ExplainNL(pVdbe);
99086  }
99087  if( p->pOffset ){
99088    sqlite3ExplainPrintf(pVdbe, "OFFSET ");
99089    sqlite3ExplainExpr(pVdbe, p->pOffset);
99090    sqlite3ExplainNL(pVdbe);
99091  }
99092}
99093SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
99094  if( p==0 ){
99095    sqlite3ExplainPrintf(pVdbe, "(null-select)");
99096    return;
99097  }
99098  while( p->pPrior ) p = p->pPrior;
99099  sqlite3ExplainPush(pVdbe);
99100  while( p ){
99101    explainOneSelect(pVdbe, p);
99102    p = p->pNext;
99103    if( p==0 ) break;
99104    sqlite3ExplainNL(pVdbe);
99105    sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
99106  }
99107  sqlite3ExplainPrintf(pVdbe, "END");
99108  sqlite3ExplainPop(pVdbe);
99109}
99110
99111/* End of the structure debug printing code
99112*****************************************************************************/
99113#endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
99114
99115/************** End of select.c **********************************************/
99116/************** Begin file table.c *******************************************/
99117/*
99118** 2001 September 15
99119**
99120** The author disclaims copyright to this source code.  In place of
99121** a legal notice, here is a blessing:
99122**
99123**    May you do good and not evil.
99124**    May you find forgiveness for yourself and forgive others.
99125**    May you share freely, never taking more than you give.
99126**
99127*************************************************************************
99128** This file contains the sqlite3_get_table() and sqlite3_free_table()
99129** interface routines.  These are just wrappers around the main
99130** interface routine of sqlite3_exec().
99131**
99132** These routines are in a separate files so that they will not be linked
99133** if they are not used.
99134*/
99135/* #include <stdlib.h> */
99136/* #include <string.h> */
99137
99138#ifndef SQLITE_OMIT_GET_TABLE
99139
99140/*
99141** This structure is used to pass data from sqlite3_get_table() through
99142** to the callback function is uses to build the result.
99143*/
99144typedef struct TabResult {
99145  char **azResult;   /* Accumulated output */
99146  char *zErrMsg;     /* Error message text, if an error occurs */
99147  int nAlloc;        /* Slots allocated for azResult[] */
99148  int nRow;          /* Number of rows in the result */
99149  int nColumn;       /* Number of columns in the result */
99150  int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
99151  int rc;            /* Return code from sqlite3_exec() */
99152} TabResult;
99153
99154/*
99155** This routine is called once for each row in the result table.  Its job
99156** is to fill in the TabResult structure appropriately, allocating new
99157** memory as necessary.
99158*/
99159static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
99160  TabResult *p = (TabResult*)pArg;  /* Result accumulator */
99161  int need;                         /* Slots needed in p->azResult[] */
99162  int i;                            /* Loop counter */
99163  char *z;                          /* A single column of result */
99164
99165  /* Make sure there is enough space in p->azResult to hold everything
99166  ** we need to remember from this invocation of the callback.
99167  */
99168  if( p->nRow==0 && argv!=0 ){
99169    need = nCol*2;
99170  }else{
99171    need = nCol;
99172  }
99173  if( p->nData + need > p->nAlloc ){
99174    char **azNew;
99175    p->nAlloc = p->nAlloc*2 + need;
99176    azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
99177    if( azNew==0 ) goto malloc_failed;
99178    p->azResult = azNew;
99179  }
99180
99181  /* If this is the first row, then generate an extra row containing
99182  ** the names of all columns.
99183  */
99184  if( p->nRow==0 ){
99185    p->nColumn = nCol;
99186    for(i=0; i<nCol; i++){
99187      z = sqlite3_mprintf("%s", colv[i]);
99188      if( z==0 ) goto malloc_failed;
99189      p->azResult[p->nData++] = z;
99190    }
99191  }else if( p->nColumn!=nCol ){
99192    sqlite3_free(p->zErrMsg);
99193    p->zErrMsg = sqlite3_mprintf(
99194       "sqlite3_get_table() called with two or more incompatible queries"
99195    );
99196    p->rc = SQLITE_ERROR;
99197    return 1;
99198  }
99199
99200  /* Copy over the row data
99201  */
99202  if( argv!=0 ){
99203    for(i=0; i<nCol; i++){
99204      if( argv[i]==0 ){
99205        z = 0;
99206      }else{
99207        int n = sqlite3Strlen30(argv[i])+1;
99208        z = sqlite3_malloc( n );
99209        if( z==0 ) goto malloc_failed;
99210        memcpy(z, argv[i], n);
99211      }
99212      p->azResult[p->nData++] = z;
99213    }
99214    p->nRow++;
99215  }
99216  return 0;
99217
99218malloc_failed:
99219  p->rc = SQLITE_NOMEM;
99220  return 1;
99221}
99222
99223/*
99224** Query the database.  But instead of invoking a callback for each row,
99225** malloc() for space to hold the result and return the entire results
99226** at the conclusion of the call.
99227**
99228** The result that is written to ***pazResult is held in memory obtained
99229** from malloc().  But the caller cannot free this memory directly.
99230** Instead, the entire table should be passed to sqlite3_free_table() when
99231** the calling procedure is finished using it.
99232*/
99233SQLITE_API int sqlite3_get_table(
99234  sqlite3 *db,                /* The database on which the SQL executes */
99235  const char *zSql,           /* The SQL to be executed */
99236  char ***pazResult,          /* Write the result table here */
99237  int *pnRow,                 /* Write the number of rows in the result here */
99238  int *pnColumn,              /* Write the number of columns of result here */
99239  char **pzErrMsg             /* Write error messages here */
99240){
99241  int rc;
99242  TabResult res;
99243
99244  *pazResult = 0;
99245  if( pnColumn ) *pnColumn = 0;
99246  if( pnRow ) *pnRow = 0;
99247  if( pzErrMsg ) *pzErrMsg = 0;
99248  res.zErrMsg = 0;
99249  res.nRow = 0;
99250  res.nColumn = 0;
99251  res.nData = 1;
99252  res.nAlloc = 20;
99253  res.rc = SQLITE_OK;
99254  res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
99255  if( res.azResult==0 ){
99256     db->errCode = SQLITE_NOMEM;
99257     return SQLITE_NOMEM;
99258  }
99259  res.azResult[0] = 0;
99260  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
99261  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
99262  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
99263  if( (rc&0xff)==SQLITE_ABORT ){
99264    sqlite3_free_table(&res.azResult[1]);
99265    if( res.zErrMsg ){
99266      if( pzErrMsg ){
99267        sqlite3_free(*pzErrMsg);
99268        *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
99269      }
99270      sqlite3_free(res.zErrMsg);
99271    }
99272    db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
99273    return res.rc;
99274  }
99275  sqlite3_free(res.zErrMsg);
99276  if( rc!=SQLITE_OK ){
99277    sqlite3_free_table(&res.azResult[1]);
99278    return rc;
99279  }
99280  if( res.nAlloc>res.nData ){
99281    char **azNew;
99282    azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
99283    if( azNew==0 ){
99284      sqlite3_free_table(&res.azResult[1]);
99285      db->errCode = SQLITE_NOMEM;
99286      return SQLITE_NOMEM;
99287    }
99288    res.azResult = azNew;
99289  }
99290  *pazResult = &res.azResult[1];
99291  if( pnColumn ) *pnColumn = res.nColumn;
99292  if( pnRow ) *pnRow = res.nRow;
99293  return rc;
99294}
99295
99296/*
99297** This routine frees the space the sqlite3_get_table() malloced.
99298*/
99299SQLITE_API void sqlite3_free_table(
99300  char **azResult            /* Result returned from from sqlite3_get_table() */
99301){
99302  if( azResult ){
99303    int i, n;
99304    azResult--;
99305    assert( azResult!=0 );
99306    n = SQLITE_PTR_TO_INT(azResult[0]);
99307    for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
99308    sqlite3_free(azResult);
99309  }
99310}
99311
99312#endif /* SQLITE_OMIT_GET_TABLE */
99313
99314/************** End of table.c ***********************************************/
99315/************** Begin file trigger.c *****************************************/
99316/*
99317**
99318** The author disclaims copyright to this source code.  In place of
99319** a legal notice, here is a blessing:
99320**
99321**    May you do good and not evil.
99322**    May you find forgiveness for yourself and forgive others.
99323**    May you share freely, never taking more than you give.
99324**
99325*************************************************************************
99326** This file contains the implementation for TRIGGERs
99327*/
99328
99329#ifndef SQLITE_OMIT_TRIGGER
99330/*
99331** Delete a linked list of TriggerStep structures.
99332*/
99333SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
99334  while( pTriggerStep ){
99335    TriggerStep * pTmp = pTriggerStep;
99336    pTriggerStep = pTriggerStep->pNext;
99337
99338    sqlite3ExprDelete(db, pTmp->pWhere);
99339    sqlite3ExprListDelete(db, pTmp->pExprList);
99340    sqlite3SelectDelete(db, pTmp->pSelect);
99341    sqlite3IdListDelete(db, pTmp->pIdList);
99342
99343    sqlite3DbFree(db, pTmp);
99344  }
99345}
99346
99347/*
99348** Given table pTab, return a list of all the triggers attached to
99349** the table. The list is connected by Trigger.pNext pointers.
99350**
99351** All of the triggers on pTab that are in the same database as pTab
99352** are already attached to pTab->pTrigger.  But there might be additional
99353** triggers on pTab in the TEMP schema.  This routine prepends all
99354** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
99355** and returns the combined list.
99356**
99357** To state it another way:  This routine returns a list of all triggers
99358** that fire off of pTab.  The list will include any TEMP triggers on
99359** pTab as well as the triggers lised in pTab->pTrigger.
99360*/
99361SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
99362  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
99363  Trigger *pList = 0;                  /* List of triggers to return */
99364
99365  if( pParse->disableTriggers ){
99366    return 0;
99367  }
99368
99369  if( pTmpSchema!=pTab->pSchema ){
99370    HashElem *p;
99371    assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
99372    for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
99373      Trigger *pTrig = (Trigger *)sqliteHashData(p);
99374      if( pTrig->pTabSchema==pTab->pSchema
99375       && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
99376      ){
99377        pTrig->pNext = (pList ? pList : pTab->pTrigger);
99378        pList = pTrig;
99379      }
99380    }
99381  }
99382
99383  return (pList ? pList : pTab->pTrigger);
99384}
99385
99386/*
99387** This is called by the parser when it sees a CREATE TRIGGER statement
99388** up to the point of the BEGIN before the trigger actions.  A Trigger
99389** structure is generated based on the information available and stored
99390** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
99391** sqlite3FinishTrigger() function is called to complete the trigger
99392** construction process.
99393*/
99394SQLITE_PRIVATE void sqlite3BeginTrigger(
99395  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
99396  Token *pName1,      /* The name of the trigger */
99397  Token *pName2,      /* The name of the trigger */
99398  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
99399  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
99400  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
99401  SrcList *pTableName,/* The name of the table/view the trigger applies to */
99402  Expr *pWhen,        /* WHEN clause */
99403  int isTemp,         /* True if the TEMPORARY keyword is present */
99404  int noErr           /* Suppress errors if the trigger already exists */
99405){
99406  Trigger *pTrigger = 0;  /* The new trigger */
99407  Table *pTab;            /* Table that the trigger fires off of */
99408  char *zName = 0;        /* Name of the trigger */
99409  sqlite3 *db = pParse->db;  /* The database connection */
99410  int iDb;                /* The database to store the trigger in */
99411  Token *pName;           /* The unqualified db name */
99412  DbFixer sFix;           /* State vector for the DB fixer */
99413  int iTabDb;             /* Index of the database holding pTab */
99414
99415  assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
99416  assert( pName2!=0 );
99417  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
99418  assert( op>0 && op<0xff );
99419  if( isTemp ){
99420    /* If TEMP was specified, then the trigger name may not be qualified. */
99421    if( pName2->n>0 ){
99422      sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
99423      goto trigger_cleanup;
99424    }
99425    iDb = 1;
99426    pName = pName1;
99427  }else{
99428    /* Figure out the db that the the trigger will be created in */
99429    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99430    if( iDb<0 ){
99431      goto trigger_cleanup;
99432    }
99433  }
99434  if( !pTableName || db->mallocFailed ){
99435    goto trigger_cleanup;
99436  }
99437
99438  /* A long-standing parser bug is that this syntax was allowed:
99439  **
99440  **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
99441  **                                                 ^^^^^^^^
99442  **
99443  ** To maintain backwards compatibility, ignore the database
99444  ** name on pTableName if we are reparsing our of SQLITE_MASTER.
99445  */
99446  if( db->init.busy && iDb!=1 ){
99447    sqlite3DbFree(db, pTableName->a[0].zDatabase);
99448    pTableName->a[0].zDatabase = 0;
99449  }
99450
99451  /* If the trigger name was unqualified, and the table is a temp table,
99452  ** then set iDb to 1 to create the trigger in the temporary database.
99453  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
99454  ** exist, the error is caught by the block below.
99455  */
99456  pTab = sqlite3SrcListLookup(pParse, pTableName);
99457  if( db->init.busy==0 && pName2->n==0 && pTab
99458        && pTab->pSchema==db->aDb[1].pSchema ){
99459    iDb = 1;
99460  }
99461
99462  /* Ensure the table name matches database name and that the table exists */
99463  if( db->mallocFailed ) goto trigger_cleanup;
99464  assert( pTableName->nSrc==1 );
99465  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
99466      sqlite3FixSrcList(&sFix, pTableName) ){
99467    goto trigger_cleanup;
99468  }
99469  pTab = sqlite3SrcListLookup(pParse, pTableName);
99470  if( !pTab ){
99471    /* The table does not exist. */
99472    if( db->init.iDb==1 ){
99473      /* Ticket #3810.
99474      ** Normally, whenever a table is dropped, all associated triggers are
99475      ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
99476      ** and the table is dropped by a different database connection, the
99477      ** trigger is not visible to the database connection that does the
99478      ** drop so the trigger cannot be dropped.  This results in an
99479      ** "orphaned trigger" - a trigger whose associated table is missing.
99480      */
99481      db->init.orphanTrigger = 1;
99482    }
99483    goto trigger_cleanup;
99484  }
99485  if( IsVirtual(pTab) ){
99486    sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
99487    goto trigger_cleanup;
99488  }
99489
99490  /* Check that the trigger name is not reserved and that no trigger of the
99491  ** specified name exists */
99492  zName = sqlite3NameFromToken(db, pName);
99493  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
99494    goto trigger_cleanup;
99495  }
99496  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99497  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
99498                      zName, sqlite3Strlen30(zName)) ){
99499    if( !noErr ){
99500      sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
99501    }else{
99502      assert( !db->init.busy );
99503      sqlite3CodeVerifySchema(pParse, iDb);
99504    }
99505    goto trigger_cleanup;
99506  }
99507
99508  /* Do not create a trigger on a system table */
99509  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
99510    sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
99511    pParse->nErr++;
99512    goto trigger_cleanup;
99513  }
99514
99515  /* INSTEAD of triggers are only for views and views only support INSTEAD
99516  ** of triggers.
99517  */
99518  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
99519    sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
99520        (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
99521    goto trigger_cleanup;
99522  }
99523  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
99524    sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
99525        " trigger on table: %S", pTableName, 0);
99526    goto trigger_cleanup;
99527  }
99528  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99529
99530#ifndef SQLITE_OMIT_AUTHORIZATION
99531  {
99532    int code = SQLITE_CREATE_TRIGGER;
99533    const char *zDb = db->aDb[iTabDb].zName;
99534    const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
99535    if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
99536    if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
99537      goto trigger_cleanup;
99538    }
99539    if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
99540      goto trigger_cleanup;
99541    }
99542  }
99543#endif
99544
99545  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
99546  ** cannot appear on views.  So we might as well translate every
99547  ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
99548  ** elsewhere.
99549  */
99550  if (tr_tm == TK_INSTEAD){
99551    tr_tm = TK_BEFORE;
99552  }
99553
99554  /* Build the Trigger object */
99555  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
99556  if( pTrigger==0 ) goto trigger_cleanup;
99557  pTrigger->zName = zName;
99558  zName = 0;
99559  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
99560  pTrigger->pSchema = db->aDb[iDb].pSchema;
99561  pTrigger->pTabSchema = pTab->pSchema;
99562  pTrigger->op = (u8)op;
99563  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
99564  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
99565  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
99566  assert( pParse->pNewTrigger==0 );
99567  pParse->pNewTrigger = pTrigger;
99568
99569trigger_cleanup:
99570  sqlite3DbFree(db, zName);
99571  sqlite3SrcListDelete(db, pTableName);
99572  sqlite3IdListDelete(db, pColumns);
99573  sqlite3ExprDelete(db, pWhen);
99574  if( !pParse->pNewTrigger ){
99575    sqlite3DeleteTrigger(db, pTrigger);
99576  }else{
99577    assert( pParse->pNewTrigger==pTrigger );
99578  }
99579}
99580
99581/*
99582** This routine is called after all of the trigger actions have been parsed
99583** in order to complete the process of building the trigger.
99584*/
99585SQLITE_PRIVATE void sqlite3FinishTrigger(
99586  Parse *pParse,          /* Parser context */
99587  TriggerStep *pStepList, /* The triggered program */
99588  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
99589){
99590  Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
99591  char *zName;                            /* Name of trigger */
99592  sqlite3 *db = pParse->db;               /* The database */
99593  DbFixer sFix;                           /* Fixer object */
99594  int iDb;                                /* Database containing the trigger */
99595  Token nameToken;                        /* Trigger name for error reporting */
99596
99597  pParse->pNewTrigger = 0;
99598  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
99599  zName = pTrig->zName;
99600  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
99601  pTrig->step_list = pStepList;
99602  while( pStepList ){
99603    pStepList->pTrig = pTrig;
99604    pStepList = pStepList->pNext;
99605  }
99606  nameToken.z = pTrig->zName;
99607  nameToken.n = sqlite3Strlen30(nameToken.z);
99608  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken)
99609          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
99610    goto triggerfinish_cleanup;
99611  }
99612
99613  /* if we are not initializing,
99614  ** build the sqlite_master entry
99615  */
99616  if( !db->init.busy ){
99617    Vdbe *v;
99618    char *z;
99619
99620    /* Make an entry in the sqlite_master table */
99621    v = sqlite3GetVdbe(pParse);
99622    if( v==0 ) goto triggerfinish_cleanup;
99623    sqlite3BeginWriteOperation(pParse, 0, iDb);
99624    z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
99625    sqlite3NestedParse(pParse,
99626       "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
99627       db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
99628       pTrig->table, z);
99629    sqlite3DbFree(db, z);
99630    sqlite3ChangeCookie(pParse, iDb);
99631    sqlite3VdbeAddParseSchemaOp(v, iDb,
99632        sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
99633  }
99634
99635  if( db->init.busy ){
99636    Trigger *pLink = pTrig;
99637    Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
99638    assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99639    pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
99640    if( pTrig ){
99641      db->mallocFailed = 1;
99642    }else if( pLink->pSchema==pLink->pTabSchema ){
99643      Table *pTab;
99644      int n = sqlite3Strlen30(pLink->table);
99645      pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
99646      assert( pTab!=0 );
99647      pLink->pNext = pTab->pTrigger;
99648      pTab->pTrigger = pLink;
99649    }
99650  }
99651
99652triggerfinish_cleanup:
99653  sqlite3DeleteTrigger(db, pTrig);
99654  assert( !pParse->pNewTrigger );
99655  sqlite3DeleteTriggerStep(db, pStepList);
99656}
99657
99658/*
99659** Turn a SELECT statement (that the pSelect parameter points to) into
99660** a trigger step.  Return a pointer to a TriggerStep structure.
99661**
99662** The parser calls this routine when it finds a SELECT statement in
99663** body of a TRIGGER.
99664*/
99665SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
99666  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
99667  if( pTriggerStep==0 ) {
99668    sqlite3SelectDelete(db, pSelect);
99669    return 0;
99670  }
99671  pTriggerStep->op = TK_SELECT;
99672  pTriggerStep->pSelect = pSelect;
99673  pTriggerStep->orconf = OE_Default;
99674  return pTriggerStep;
99675}
99676
99677/*
99678** Allocate space to hold a new trigger step.  The allocated space
99679** holds both the TriggerStep object and the TriggerStep.target.z string.
99680**
99681** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
99682*/
99683static TriggerStep *triggerStepAllocate(
99684  sqlite3 *db,                /* Database connection */
99685  u8 op,                      /* Trigger opcode */
99686  Token *pName                /* The target name */
99687){
99688  TriggerStep *pTriggerStep;
99689
99690  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
99691  if( pTriggerStep ){
99692    char *z = (char*)&pTriggerStep[1];
99693    memcpy(z, pName->z, pName->n);
99694    pTriggerStep->target.z = z;
99695    pTriggerStep->target.n = pName->n;
99696    pTriggerStep->op = op;
99697  }
99698  return pTriggerStep;
99699}
99700
99701/*
99702** Build a trigger step out of an INSERT statement.  Return a pointer
99703** to the new trigger step.
99704**
99705** The parser calls this routine when it sees an INSERT inside the
99706** body of a trigger.
99707*/
99708SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
99709  sqlite3 *db,        /* The database connection */
99710  Token *pTableName,  /* Name of the table into which we insert */
99711  IdList *pColumn,    /* List of columns in pTableName to insert into */
99712  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
99713  Select *pSelect,    /* A SELECT statement that supplies values */
99714  u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
99715){
99716  TriggerStep *pTriggerStep;
99717
99718  assert(pEList == 0 || pSelect == 0);
99719  assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
99720
99721  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
99722  if( pTriggerStep ){
99723    pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99724    pTriggerStep->pIdList = pColumn;
99725    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99726    pTriggerStep->orconf = orconf;
99727  }else{
99728    sqlite3IdListDelete(db, pColumn);
99729  }
99730  sqlite3ExprListDelete(db, pEList);
99731  sqlite3SelectDelete(db, pSelect);
99732
99733  return pTriggerStep;
99734}
99735
99736/*
99737** Construct a trigger step that implements an UPDATE statement and return
99738** a pointer to that trigger step.  The parser calls this routine when it
99739** sees an UPDATE statement inside the body of a CREATE TRIGGER.
99740*/
99741SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
99742  sqlite3 *db,         /* The database connection */
99743  Token *pTableName,   /* Name of the table to be updated */
99744  ExprList *pEList,    /* The SET clause: list of column and new values */
99745  Expr *pWhere,        /* The WHERE clause */
99746  u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
99747){
99748  TriggerStep *pTriggerStep;
99749
99750  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
99751  if( pTriggerStep ){
99752    pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
99753    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99754    pTriggerStep->orconf = orconf;
99755  }
99756  sqlite3ExprListDelete(db, pEList);
99757  sqlite3ExprDelete(db, pWhere);
99758  return pTriggerStep;
99759}
99760
99761/*
99762** Construct a trigger step that implements a DELETE statement and return
99763** a pointer to that trigger step.  The parser calls this routine when it
99764** sees a DELETE statement inside the body of a CREATE TRIGGER.
99765*/
99766SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
99767  sqlite3 *db,            /* Database connection */
99768  Token *pTableName,      /* The table from which rows are deleted */
99769  Expr *pWhere            /* The WHERE clause */
99770){
99771  TriggerStep *pTriggerStep;
99772
99773  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
99774  if( pTriggerStep ){
99775    pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99776    pTriggerStep->orconf = OE_Default;
99777  }
99778  sqlite3ExprDelete(db, pWhere);
99779  return pTriggerStep;
99780}
99781
99782/*
99783** Recursively delete a Trigger structure
99784*/
99785SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
99786  if( pTrigger==0 ) return;
99787  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
99788  sqlite3DbFree(db, pTrigger->zName);
99789  sqlite3DbFree(db, pTrigger->table);
99790  sqlite3ExprDelete(db, pTrigger->pWhen);
99791  sqlite3IdListDelete(db, pTrigger->pColumns);
99792  sqlite3DbFree(db, pTrigger);
99793}
99794
99795/*
99796** This function is called to drop a trigger from the database schema.
99797**
99798** This may be called directly from the parser and therefore identifies
99799** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
99800** same job as this routine except it takes a pointer to the trigger
99801** instead of the trigger name.
99802**/
99803SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
99804  Trigger *pTrigger = 0;
99805  int i;
99806  const char *zDb;
99807  const char *zName;
99808  int nName;
99809  sqlite3 *db = pParse->db;
99810
99811  if( db->mallocFailed ) goto drop_trigger_cleanup;
99812  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
99813    goto drop_trigger_cleanup;
99814  }
99815
99816  assert( pName->nSrc==1 );
99817  zDb = pName->a[0].zDatabase;
99818  zName = pName->a[0].zName;
99819  nName = sqlite3Strlen30(zName);
99820  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
99821  for(i=OMIT_TEMPDB; i<db->nDb; i++){
99822    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
99823    if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
99824    assert( sqlite3SchemaMutexHeld(db, j, 0) );
99825    pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
99826    if( pTrigger ) break;
99827  }
99828  if( !pTrigger ){
99829    if( !noErr ){
99830      sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
99831    }else{
99832      sqlite3CodeVerifyNamedSchema(pParse, zDb);
99833    }
99834    pParse->checkSchema = 1;
99835    goto drop_trigger_cleanup;
99836  }
99837  sqlite3DropTriggerPtr(pParse, pTrigger);
99838
99839drop_trigger_cleanup:
99840  sqlite3SrcListDelete(db, pName);
99841}
99842
99843/*
99844** Return a pointer to the Table structure for the table that a trigger
99845** is set on.
99846*/
99847static Table *tableOfTrigger(Trigger *pTrigger){
99848  int n = sqlite3Strlen30(pTrigger->table);
99849  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
99850}
99851
99852
99853/*
99854** Drop a trigger given a pointer to that trigger.
99855*/
99856SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
99857  Table   *pTable;
99858  Vdbe *v;
99859  sqlite3 *db = pParse->db;
99860  int iDb;
99861
99862  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
99863  assert( iDb>=0 && iDb<db->nDb );
99864  pTable = tableOfTrigger(pTrigger);
99865  assert( pTable );
99866  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
99867#ifndef SQLITE_OMIT_AUTHORIZATION
99868  {
99869    int code = SQLITE_DROP_TRIGGER;
99870    const char *zDb = db->aDb[iDb].zName;
99871    const char *zTab = SCHEMA_TABLE(iDb);
99872    if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
99873    if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
99874      sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
99875      return;
99876    }
99877  }
99878#endif
99879
99880  /* Generate code to destroy the database record of the trigger.
99881  */
99882  assert( pTable!=0 );
99883  if( (v = sqlite3GetVdbe(pParse))!=0 ){
99884    int base;
99885    static const VdbeOpList dropTrigger[] = {
99886      { OP_Rewind,     0, ADDR(9),  0},
99887      { OP_String8,    0, 1,        0}, /* 1 */
99888      { OP_Column,     0, 1,        2},
99889      { OP_Ne,         2, ADDR(8),  1},
99890      { OP_String8,    0, 1,        0}, /* 4: "trigger" */
99891      { OP_Column,     0, 0,        2},
99892      { OP_Ne,         2, ADDR(8),  1},
99893      { OP_Delete,     0, 0,        0},
99894      { OP_Next,       0, ADDR(1),  0}, /* 8 */
99895    };
99896
99897    sqlite3BeginWriteOperation(pParse, 0, iDb);
99898    sqlite3OpenMasterTable(pParse, iDb);
99899    base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
99900    sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
99901    sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
99902    sqlite3ChangeCookie(pParse, iDb);
99903    sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
99904    sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
99905    if( pParse->nMem<3 ){
99906      pParse->nMem = 3;
99907    }
99908  }
99909}
99910
99911/*
99912** Remove a trigger from the hash tables of the sqlite* pointer.
99913*/
99914SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
99915  Trigger *pTrigger;
99916  Hash *pHash;
99917
99918  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99919  pHash = &(db->aDb[iDb].pSchema->trigHash);
99920  pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
99921  if( ALWAYS(pTrigger) ){
99922    if( pTrigger->pSchema==pTrigger->pTabSchema ){
99923      Table *pTab = tableOfTrigger(pTrigger);
99924      Trigger **pp;
99925      for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
99926      *pp = (*pp)->pNext;
99927    }
99928    sqlite3DeleteTrigger(db, pTrigger);
99929    db->flags |= SQLITE_InternChanges;
99930  }
99931}
99932
99933/*
99934** pEList is the SET clause of an UPDATE statement.  Each entry
99935** in pEList is of the format <id>=<expr>.  If any of the entries
99936** in pEList have an <id> which matches an identifier in pIdList,
99937** then return TRUE.  If pIdList==NULL, then it is considered a
99938** wildcard that matches anything.  Likewise if pEList==NULL then
99939** it matches anything so always return true.  Return false only
99940** if there is no match.
99941*/
99942static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
99943  int e;
99944  if( pIdList==0 || NEVER(pEList==0) ) return 1;
99945  for(e=0; e<pEList->nExpr; e++){
99946    if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
99947  }
99948  return 0;
99949}
99950
99951/*
99952** Return a list of all triggers on table pTab if there exists at least
99953** one trigger that must be fired when an operation of type 'op' is
99954** performed on the table, and, if that operation is an UPDATE, if at
99955** least one of the columns in pChanges is being modified.
99956*/
99957SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
99958  Parse *pParse,          /* Parse context */
99959  Table *pTab,            /* The table the contains the triggers */
99960  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
99961  ExprList *pChanges,     /* Columns that change in an UPDATE statement */
99962  int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
99963){
99964  int mask = 0;
99965  Trigger *pList = 0;
99966  Trigger *p;
99967
99968  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
99969    pList = sqlite3TriggerList(pParse, pTab);
99970  }
99971  assert( pList==0 || IsVirtual(pTab)==0 );
99972  for(p=pList; p; p=p->pNext){
99973    if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
99974      mask |= p->tr_tm;
99975    }
99976  }
99977  if( pMask ){
99978    *pMask = mask;
99979  }
99980  return (mask ? pList : 0);
99981}
99982
99983/*
99984** Convert the pStep->target token into a SrcList and return a pointer
99985** to that SrcList.
99986**
99987** This routine adds a specific database name, if needed, to the target when
99988** forming the SrcList.  This prevents a trigger in one database from
99989** referring to a target in another database.  An exception is when the
99990** trigger is in TEMP in which case it can refer to any other database it
99991** wants.
99992*/
99993static SrcList *targetSrcList(
99994  Parse *pParse,       /* The parsing context */
99995  TriggerStep *pStep   /* The trigger containing the target token */
99996){
99997  int iDb;             /* Index of the database to use */
99998  SrcList *pSrc;       /* SrcList to be returned */
99999
100000  pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
100001  if( pSrc ){
100002    assert( pSrc->nSrc>0 );
100003    assert( pSrc->a!=0 );
100004    iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
100005    if( iDb==0 || iDb>=2 ){
100006      sqlite3 *db = pParse->db;
100007      assert( iDb<pParse->db->nDb );
100008      pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
100009    }
100010  }
100011  return pSrc;
100012}
100013
100014/*
100015** Generate VDBE code for the statements inside the body of a single
100016** trigger.
100017*/
100018static int codeTriggerProgram(
100019  Parse *pParse,            /* The parser context */
100020  TriggerStep *pStepList,   /* List of statements inside the trigger body */
100021  int orconf                /* Conflict algorithm. (OE_Abort, etc) */
100022){
100023  TriggerStep *pStep;
100024  Vdbe *v = pParse->pVdbe;
100025  sqlite3 *db = pParse->db;
100026
100027  assert( pParse->pTriggerTab && pParse->pToplevel );
100028  assert( pStepList );
100029  assert( v!=0 );
100030  for(pStep=pStepList; pStep; pStep=pStep->pNext){
100031    /* Figure out the ON CONFLICT policy that will be used for this step
100032    ** of the trigger program. If the statement that caused this trigger
100033    ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
100034    ** the ON CONFLICT policy that was specified as part of the trigger
100035    ** step statement. Example:
100036    **
100037    **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
100038    **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
100039    **   END;
100040    **
100041    **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
100042    **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
100043    */
100044    pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
100045
100046    switch( pStep->op ){
100047      case TK_UPDATE: {
100048        sqlite3Update(pParse,
100049          targetSrcList(pParse, pStep),
100050          sqlite3ExprListDup(db, pStep->pExprList, 0),
100051          sqlite3ExprDup(db, pStep->pWhere, 0),
100052          pParse->eOrconf
100053        );
100054        break;
100055      }
100056      case TK_INSERT: {
100057        sqlite3Insert(pParse,
100058          targetSrcList(pParse, pStep),
100059          sqlite3ExprListDup(db, pStep->pExprList, 0),
100060          sqlite3SelectDup(db, pStep->pSelect, 0),
100061          sqlite3IdListDup(db, pStep->pIdList),
100062          pParse->eOrconf
100063        );
100064        break;
100065      }
100066      case TK_DELETE: {
100067        sqlite3DeleteFrom(pParse,
100068          targetSrcList(pParse, pStep),
100069          sqlite3ExprDup(db, pStep->pWhere, 0)
100070        );
100071        break;
100072      }
100073      default: assert( pStep->op==TK_SELECT ); {
100074        SelectDest sDest;
100075        Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
100076        sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
100077        sqlite3Select(pParse, pSelect, &sDest);
100078        sqlite3SelectDelete(db, pSelect);
100079        break;
100080      }
100081    }
100082    if( pStep->op!=TK_SELECT ){
100083      sqlite3VdbeAddOp0(v, OP_ResetCount);
100084    }
100085  }
100086
100087  return 0;
100088}
100089
100090#ifdef SQLITE_DEBUG
100091/*
100092** This function is used to add VdbeComment() annotations to a VDBE
100093** program. It is not used in production code, only for debugging.
100094*/
100095static const char *onErrorText(int onError){
100096  switch( onError ){
100097    case OE_Abort:    return "abort";
100098    case OE_Rollback: return "rollback";
100099    case OE_Fail:     return "fail";
100100    case OE_Replace:  return "replace";
100101    case OE_Ignore:   return "ignore";
100102    case OE_Default:  return "default";
100103  }
100104  return "n/a";
100105}
100106#endif
100107
100108/*
100109** Parse context structure pFrom has just been used to create a sub-vdbe
100110** (trigger program). If an error has occurred, transfer error information
100111** from pFrom to pTo.
100112*/
100113static void transferParseError(Parse *pTo, Parse *pFrom){
100114  assert( pFrom->zErrMsg==0 || pFrom->nErr );
100115  assert( pTo->zErrMsg==0 || pTo->nErr );
100116  if( pTo->nErr==0 ){
100117    pTo->zErrMsg = pFrom->zErrMsg;
100118    pTo->nErr = pFrom->nErr;
100119  }else{
100120    sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
100121  }
100122}
100123
100124/*
100125** Create and populate a new TriggerPrg object with a sub-program
100126** implementing trigger pTrigger with ON CONFLICT policy orconf.
100127*/
100128static TriggerPrg *codeRowTrigger(
100129  Parse *pParse,       /* Current parse context */
100130  Trigger *pTrigger,   /* Trigger to code */
100131  Table *pTab,         /* The table pTrigger is attached to */
100132  int orconf           /* ON CONFLICT policy to code trigger program with */
100133){
100134  Parse *pTop = sqlite3ParseToplevel(pParse);
100135  sqlite3 *db = pParse->db;   /* Database handle */
100136  TriggerPrg *pPrg;           /* Value to return */
100137  Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
100138  Vdbe *v;                    /* Temporary VM */
100139  NameContext sNC;            /* Name context for sub-vdbe */
100140  SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
100141  Parse *pSubParse;           /* Parse context for sub-vdbe */
100142  int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
100143
100144  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100145  assert( pTop->pVdbe );
100146
100147  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
100148  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
100149  ** list of the top-level Parse object sooner rather than later.  */
100150  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
100151  if( !pPrg ) return 0;
100152  pPrg->pNext = pTop->pTriggerPrg;
100153  pTop->pTriggerPrg = pPrg;
100154  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
100155  if( !pProgram ) return 0;
100156  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
100157  pPrg->pTrigger = pTrigger;
100158  pPrg->orconf = orconf;
100159  pPrg->aColmask[0] = 0xffffffff;
100160  pPrg->aColmask[1] = 0xffffffff;
100161
100162  /* Allocate and populate a new Parse context to use for coding the
100163  ** trigger sub-program.  */
100164  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
100165  if( !pSubParse ) return 0;
100166  memset(&sNC, 0, sizeof(sNC));
100167  sNC.pParse = pSubParse;
100168  pSubParse->db = db;
100169  pSubParse->pTriggerTab = pTab;
100170  pSubParse->pToplevel = pTop;
100171  pSubParse->zAuthContext = pTrigger->zName;
100172  pSubParse->eTriggerOp = pTrigger->op;
100173  pSubParse->nQueryLoop = pParse->nQueryLoop;
100174
100175  v = sqlite3GetVdbe(pSubParse);
100176  if( v ){
100177    VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
100178      pTrigger->zName, onErrorText(orconf),
100179      (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
100180        (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
100181        (pTrigger->op==TK_INSERT ? "INSERT" : ""),
100182        (pTrigger->op==TK_DELETE ? "DELETE" : ""),
100183      pTab->zName
100184    ));
100185#ifndef SQLITE_OMIT_TRACE
100186    sqlite3VdbeChangeP4(v, -1,
100187      sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
100188    );
100189#endif
100190
100191    /* If one was specified, code the WHEN clause. If it evaluates to false
100192    ** (or NULL) the sub-vdbe is immediately halted by jumping to the
100193    ** OP_Halt inserted at the end of the program.  */
100194    if( pTrigger->pWhen ){
100195      pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
100196      if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
100197       && db->mallocFailed==0
100198      ){
100199        iEndTrigger = sqlite3VdbeMakeLabel(v);
100200        sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
100201      }
100202      sqlite3ExprDelete(db, pWhen);
100203    }
100204
100205    /* Code the trigger program into the sub-vdbe. */
100206    codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
100207
100208    /* Insert an OP_Halt at the end of the sub-program. */
100209    if( iEndTrigger ){
100210      sqlite3VdbeResolveLabel(v, iEndTrigger);
100211    }
100212    sqlite3VdbeAddOp0(v, OP_Halt);
100213    VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
100214
100215    transferParseError(pParse, pSubParse);
100216    if( db->mallocFailed==0 ){
100217      pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
100218    }
100219    pProgram->nMem = pSubParse->nMem;
100220    pProgram->nCsr = pSubParse->nTab;
100221    pProgram->nOnce = pSubParse->nOnce;
100222    pProgram->token = (void *)pTrigger;
100223    pPrg->aColmask[0] = pSubParse->oldmask;
100224    pPrg->aColmask[1] = pSubParse->newmask;
100225    sqlite3VdbeDelete(v);
100226  }
100227
100228  assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
100229  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
100230  sqlite3StackFree(db, pSubParse);
100231
100232  return pPrg;
100233}
100234
100235/*
100236** Return a pointer to a TriggerPrg object containing the sub-program for
100237** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
100238** TriggerPrg object exists, a new object is allocated and populated before
100239** being returned.
100240*/
100241static TriggerPrg *getRowTrigger(
100242  Parse *pParse,       /* Current parse context */
100243  Trigger *pTrigger,   /* Trigger to code */
100244  Table *pTab,         /* The table trigger pTrigger is attached to */
100245  int orconf           /* ON CONFLICT algorithm. */
100246){
100247  Parse *pRoot = sqlite3ParseToplevel(pParse);
100248  TriggerPrg *pPrg;
100249
100250  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
100251
100252  /* It may be that this trigger has already been coded (or is in the
100253  ** process of being coded). If this is the case, then an entry with
100254  ** a matching TriggerPrg.pTrigger field will be present somewhere
100255  ** in the Parse.pTriggerPrg list. Search for such an entry.  */
100256  for(pPrg=pRoot->pTriggerPrg;
100257      pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
100258      pPrg=pPrg->pNext
100259  );
100260
100261  /* If an existing TriggerPrg could not be located, create a new one. */
100262  if( !pPrg ){
100263    pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
100264  }
100265
100266  return pPrg;
100267}
100268
100269/*
100270** Generate code for the trigger program associated with trigger p on
100271** table pTab. The reg, orconf and ignoreJump parameters passed to this
100272** function are the same as those described in the header function for
100273** sqlite3CodeRowTrigger()
100274*/
100275SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
100276  Parse *pParse,       /* Parse context */
100277  Trigger *p,          /* Trigger to code */
100278  Table *pTab,         /* The table to code triggers from */
100279  int reg,             /* Reg array containing OLD.* and NEW.* values */
100280  int orconf,          /* ON CONFLICT policy */
100281  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100282){
100283  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
100284  TriggerPrg *pPrg;
100285  pPrg = getRowTrigger(pParse, p, pTab, orconf);
100286  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
100287
100288  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
100289  ** is a pointer to the sub-vdbe containing the trigger program.  */
100290  if( pPrg ){
100291    int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
100292
100293    sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
100294    sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
100295    VdbeComment(
100296        (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
100297
100298    /* Set the P5 operand of the OP_Program instruction to non-zero if
100299    ** recursive invocation of this trigger program is disallowed. Recursive
100300    ** invocation is disallowed if (a) the sub-program is really a trigger,
100301    ** not a foreign key action, and (b) the flag to enable recursive triggers
100302    ** is clear.  */
100303    sqlite3VdbeChangeP5(v, (u8)bRecursive);
100304  }
100305}
100306
100307/*
100308** This is called to code the required FOR EACH ROW triggers for an operation
100309** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
100310** is given by the op paramater. The tr_tm parameter determines whether the
100311** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
100312** parameter pChanges is passed the list of columns being modified.
100313**
100314** If there are no triggers that fire at the specified time for the specified
100315** operation on pTab, this function is a no-op.
100316**
100317** The reg argument is the address of the first in an array of registers
100318** that contain the values substituted for the new.* and old.* references
100319** in the trigger program. If N is the number of columns in table pTab
100320** (a copy of pTab->nCol), then registers are populated as follows:
100321**
100322**   Register       Contains
100323**   ------------------------------------------------------
100324**   reg+0          OLD.rowid
100325**   reg+1          OLD.* value of left-most column of pTab
100326**   ...            ...
100327**   reg+N          OLD.* value of right-most column of pTab
100328**   reg+N+1        NEW.rowid
100329**   reg+N+2        OLD.* value of left-most column of pTab
100330**   ...            ...
100331**   reg+N+N+1      NEW.* value of right-most column of pTab
100332**
100333** For ON DELETE triggers, the registers containing the NEW.* values will
100334** never be accessed by the trigger program, so they are not allocated or
100335** populated by the caller (there is no data to populate them with anyway).
100336** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
100337** are never accessed, and so are not allocated by the caller. So, for an
100338** ON INSERT trigger, the value passed to this function as parameter reg
100339** is not a readable register, although registers (reg+N) through
100340** (reg+N+N+1) are.
100341**
100342** Parameter orconf is the default conflict resolution algorithm for the
100343** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
100344** is the instruction that control should jump to if a trigger program
100345** raises an IGNORE exception.
100346*/
100347SQLITE_PRIVATE void sqlite3CodeRowTrigger(
100348  Parse *pParse,       /* Parse context */
100349  Trigger *pTrigger,   /* List of triggers on table pTab */
100350  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
100351  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100352  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
100353  Table *pTab,         /* The table to code triggers from */
100354  int reg,             /* The first in an array of registers (see above) */
100355  int orconf,          /* ON CONFLICT policy */
100356  int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
100357){
100358  Trigger *p;          /* Used to iterate through pTrigger list */
100359
100360  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
100361  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
100362  assert( (op==TK_UPDATE)==(pChanges!=0) );
100363
100364  for(p=pTrigger; p; p=p->pNext){
100365
100366    /* Sanity checking:  The schema for the trigger and for the table are
100367    ** always defined.  The trigger must be in the same schema as the table
100368    ** or else it must be a TEMP trigger. */
100369    assert( p->pSchema!=0 );
100370    assert( p->pTabSchema!=0 );
100371    assert( p->pSchema==p->pTabSchema
100372         || p->pSchema==pParse->db->aDb[1].pSchema );
100373
100374    /* Determine whether we should code this trigger */
100375    if( p->op==op
100376     && p->tr_tm==tr_tm
100377     && checkColumnOverlap(p->pColumns, pChanges)
100378    ){
100379      sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
100380    }
100381  }
100382}
100383
100384/*
100385** Triggers may access values stored in the old.* or new.* pseudo-table.
100386** This function returns a 32-bit bitmask indicating which columns of the
100387** old.* or new.* tables actually are used by triggers. This information
100388** may be used by the caller, for example, to avoid having to load the entire
100389** old.* record into memory when executing an UPDATE or DELETE command.
100390**
100391** Bit 0 of the returned mask is set if the left-most column of the
100392** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
100393** the second leftmost column value is required, and so on. If there
100394** are more than 32 columns in the table, and at least one of the columns
100395** with an index greater than 32 may be accessed, 0xffffffff is returned.
100396**
100397** It is not possible to determine if the old.rowid or new.rowid column is
100398** accessed by triggers. The caller must always assume that it is.
100399**
100400** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
100401** applies to the old.* table. If 1, the new.* table.
100402**
100403** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
100404** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
100405** included in the returned mask if the TRIGGER_BEFORE bit is set in the
100406** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
100407** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
100408*/
100409SQLITE_PRIVATE u32 sqlite3TriggerColmask(
100410  Parse *pParse,       /* Parse context */
100411  Trigger *pTrigger,   /* List of triggers on table pTab */
100412  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
100413  int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
100414  int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100415  Table *pTab,         /* The table to code triggers from */
100416  int orconf           /* Default ON CONFLICT policy for trigger steps */
100417){
100418  const int op = pChanges ? TK_UPDATE : TK_DELETE;
100419  u32 mask = 0;
100420  Trigger *p;
100421
100422  assert( isNew==1 || isNew==0 );
100423  for(p=pTrigger; p; p=p->pNext){
100424    if( p->op==op && (tr_tm&p->tr_tm)
100425     && checkColumnOverlap(p->pColumns,pChanges)
100426    ){
100427      TriggerPrg *pPrg;
100428      pPrg = getRowTrigger(pParse, p, pTab, orconf);
100429      if( pPrg ){
100430        mask |= pPrg->aColmask[isNew];
100431      }
100432    }
100433  }
100434
100435  return mask;
100436}
100437
100438#endif /* !defined(SQLITE_OMIT_TRIGGER) */
100439
100440/************** End of trigger.c *********************************************/
100441/************** Begin file update.c ******************************************/
100442/*
100443** 2001 September 15
100444**
100445** The author disclaims copyright to this source code.  In place of
100446** a legal notice, here is a blessing:
100447**
100448**    May you do good and not evil.
100449**    May you find forgiveness for yourself and forgive others.
100450**    May you share freely, never taking more than you give.
100451**
100452*************************************************************************
100453** This file contains C code routines that are called by the parser
100454** to handle UPDATE statements.
100455*/
100456
100457#ifndef SQLITE_OMIT_VIRTUALTABLE
100458/* Forward declaration */
100459static void updateVirtualTable(
100460  Parse *pParse,       /* The parsing context */
100461  SrcList *pSrc,       /* The virtual table to be modified */
100462  Table *pTab,         /* The virtual table */
100463  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
100464  Expr *pRowidExpr,    /* Expression used to recompute the rowid */
100465  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
100466  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
100467  int onError          /* ON CONFLICT strategy */
100468);
100469#endif /* SQLITE_OMIT_VIRTUALTABLE */
100470
100471/*
100472** The most recently coded instruction was an OP_Column to retrieve the
100473** i-th column of table pTab. This routine sets the P4 parameter of the
100474** OP_Column to the default value, if any.
100475**
100476** The default value of a column is specified by a DEFAULT clause in the
100477** column definition. This was either supplied by the user when the table
100478** was created, or added later to the table definition by an ALTER TABLE
100479** command. If the latter, then the row-records in the table btree on disk
100480** may not contain a value for the column and the default value, taken
100481** from the P4 parameter of the OP_Column instruction, is returned instead.
100482** If the former, then all row-records are guaranteed to include a value
100483** for the column and the P4 value is not required.
100484**
100485** Column definitions created by an ALTER TABLE command may only have
100486** literal default values specified: a number, null or a string. (If a more
100487** complicated default expression value was provided, it is evaluated
100488** when the ALTER TABLE is executed and one of the literal values written
100489** into the sqlite_master table.)
100490**
100491** Therefore, the P4 parameter is only required if the default value for
100492** the column is a literal number, string or null. The sqlite3ValueFromExpr()
100493** function is capable of transforming these types of expressions into
100494** sqlite3_value objects.
100495**
100496** If parameter iReg is not negative, code an OP_RealAffinity instruction
100497** on register iReg. This is used when an equivalent integer value is
100498** stored in place of an 8-byte floating point value in order to save
100499** space.
100500*/
100501SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
100502  assert( pTab!=0 );
100503  if( !pTab->pSelect ){
100504    sqlite3_value *pValue;
100505    u8 enc = ENC(sqlite3VdbeDb(v));
100506    Column *pCol = &pTab->aCol[i];
100507    VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
100508    assert( i<pTab->nCol );
100509    sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
100510                         pCol->affinity, &pValue);
100511    if( pValue ){
100512      sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
100513    }
100514#ifndef SQLITE_OMIT_FLOATING_POINT
100515    if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
100516      sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
100517    }
100518#endif
100519  }
100520}
100521
100522/*
100523** Process an UPDATE statement.
100524**
100525**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
100526**          \_______/ \________/     \______/       \________________/
100527*            onError   pTabList      pChanges             pWhere
100528*/
100529SQLITE_PRIVATE void sqlite3Update(
100530  Parse *pParse,         /* The parser context */
100531  SrcList *pTabList,     /* The table in which we should change things */
100532  ExprList *pChanges,    /* Things to be changed */
100533  Expr *pWhere,          /* The WHERE clause.  May be null */
100534  int onError            /* How to handle constraint errors */
100535){
100536  int i, j;              /* Loop counters */
100537  Table *pTab;           /* The table to be updated */
100538  int addr = 0;          /* VDBE instruction address of the start of the loop */
100539  WhereInfo *pWInfo;     /* Information about the WHERE clause */
100540  Vdbe *v;               /* The virtual database engine */
100541  Index *pIdx;           /* For looping over indices */
100542  int nIdx;              /* Number of indices that need updating */
100543  int iCur;              /* VDBE Cursor number of pTab */
100544  sqlite3 *db;           /* The database structure */
100545  int *aRegIdx = 0;      /* One register assigned to each index to be updated */
100546  int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
100547                         ** an expression for the i-th column of the table.
100548                         ** aXRef[i]==-1 if the i-th column is not changed. */
100549  int chngRowid;         /* True if the record number is being changed */
100550  Expr *pRowidExpr = 0;  /* Expression defining the new record number */
100551  int openAll = 0;       /* True if all indices need to be opened */
100552  AuthContext sContext;  /* The authorization context */
100553  NameContext sNC;       /* The name-context to resolve expressions in */
100554  int iDb;               /* Database containing the table being updated */
100555  int okOnePass;         /* True for one-pass algorithm without the FIFO */
100556  int hasFK;             /* True if foreign key processing is required */
100557
100558#ifndef SQLITE_OMIT_TRIGGER
100559  int isView;            /* True when updating a view (INSTEAD OF trigger) */
100560  Trigger *pTrigger;     /* List of triggers on pTab, if required */
100561  int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
100562#endif
100563  int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
100564
100565  /* Register Allocations */
100566  int regRowCount = 0;   /* A count of rows changed */
100567  int regOldRowid;       /* The old rowid */
100568  int regNewRowid;       /* The new rowid */
100569  int regNew;            /* Content of the NEW.* table in triggers */
100570  int regOld = 0;        /* Content of OLD.* table in triggers */
100571  int regRowSet = 0;     /* Rowset of rows to be updated */
100572
100573  memset(&sContext, 0, sizeof(sContext));
100574  db = pParse->db;
100575  if( pParse->nErr || db->mallocFailed ){
100576    goto update_cleanup;
100577  }
100578  assert( pTabList->nSrc==1 );
100579
100580  /* Locate the table which we want to update.
100581  */
100582  pTab = sqlite3SrcListLookup(pParse, pTabList);
100583  if( pTab==0 ) goto update_cleanup;
100584  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100585
100586  /* Figure out if we have any triggers and if the table being
100587  ** updated is a view.
100588  */
100589#ifndef SQLITE_OMIT_TRIGGER
100590  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
100591  isView = pTab->pSelect!=0;
100592  assert( pTrigger || tmask==0 );
100593#else
100594# define pTrigger 0
100595# define isView 0
100596# define tmask 0
100597#endif
100598#ifdef SQLITE_OMIT_VIEW
100599# undef isView
100600# define isView 0
100601#endif
100602
100603  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
100604    goto update_cleanup;
100605  }
100606  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
100607    goto update_cleanup;
100608  }
100609  aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
100610  if( aXRef==0 ) goto update_cleanup;
100611  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
100612
100613  /* Allocate a cursors for the main database table and for all indices.
100614  ** The index cursors might not be used, but if they are used they
100615  ** need to occur right after the database cursor.  So go ahead and
100616  ** allocate enough space, just in case.
100617  */
100618  pTabList->a[0].iCursor = iCur = pParse->nTab++;
100619  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100620    pParse->nTab++;
100621  }
100622
100623  /* Initialize the name-context */
100624  memset(&sNC, 0, sizeof(sNC));
100625  sNC.pParse = pParse;
100626  sNC.pSrcList = pTabList;
100627
100628  /* Resolve the column names in all the expressions of the
100629  ** of the UPDATE statement.  Also find the column index
100630  ** for each column to be updated in the pChanges array.  For each
100631  ** column to be updated, make sure we have authorization to change
100632  ** that column.
100633  */
100634  chngRowid = 0;
100635  for(i=0; i<pChanges->nExpr; i++){
100636    if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
100637      goto update_cleanup;
100638    }
100639    for(j=0; j<pTab->nCol; j++){
100640      if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
100641        if( j==pTab->iPKey ){
100642          chngRowid = 1;
100643          pRowidExpr = pChanges->a[i].pExpr;
100644        }
100645        aXRef[j] = i;
100646        break;
100647      }
100648    }
100649    if( j>=pTab->nCol ){
100650      if( sqlite3IsRowid(pChanges->a[i].zName) ){
100651        chngRowid = 1;
100652        pRowidExpr = pChanges->a[i].pExpr;
100653      }else{
100654        sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
100655        pParse->checkSchema = 1;
100656        goto update_cleanup;
100657      }
100658    }
100659#ifndef SQLITE_OMIT_AUTHORIZATION
100660    {
100661      int rc;
100662      rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
100663                           pTab->aCol[j].zName, db->aDb[iDb].zName);
100664      if( rc==SQLITE_DENY ){
100665        goto update_cleanup;
100666      }else if( rc==SQLITE_IGNORE ){
100667        aXRef[j] = -1;
100668      }
100669    }
100670#endif
100671  }
100672
100673  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
100674
100675  /* Allocate memory for the array aRegIdx[].  There is one entry in the
100676  ** array for each index associated with table being updated.  Fill in
100677  ** the value with a register number for indices that are to be used
100678  ** and with zero for unused indices.
100679  */
100680  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
100681  if( nIdx>0 ){
100682    aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
100683    if( aRegIdx==0 ) goto update_cleanup;
100684  }
100685  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
100686    int reg;
100687    if( hasFK || chngRowid ){
100688      reg = ++pParse->nMem;
100689    }else{
100690      reg = 0;
100691      for(i=0; i<pIdx->nColumn; i++){
100692        if( aXRef[pIdx->aiColumn[i]]>=0 ){
100693          reg = ++pParse->nMem;
100694          break;
100695        }
100696      }
100697    }
100698    aRegIdx[j] = reg;
100699  }
100700
100701  /* Begin generating code. */
100702  v = sqlite3GetVdbe(pParse);
100703  if( v==0 ) goto update_cleanup;
100704  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
100705  sqlite3BeginWriteOperation(pParse, 1, iDb);
100706
100707#ifndef SQLITE_OMIT_VIRTUALTABLE
100708  /* Virtual tables must be handled separately */
100709  if( IsVirtual(pTab) ){
100710    updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
100711                       pWhere, onError);
100712    pWhere = 0;
100713    pTabList = 0;
100714    goto update_cleanup;
100715  }
100716#endif
100717
100718  /* Allocate required registers. */
100719  regRowSet = ++pParse->nMem;
100720  regOldRowid = regNewRowid = ++pParse->nMem;
100721  if( pTrigger || hasFK ){
100722    regOld = pParse->nMem + 1;
100723    pParse->nMem += pTab->nCol;
100724  }
100725  if( chngRowid || pTrigger || hasFK ){
100726    regNewRowid = ++pParse->nMem;
100727  }
100728  regNew = pParse->nMem + 1;
100729  pParse->nMem += pTab->nCol;
100730
100731  /* Start the view context. */
100732  if( isView ){
100733    sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
100734  }
100735
100736  /* If we are trying to update a view, realize that view into
100737  ** a ephemeral table.
100738  */
100739#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
100740  if( isView ){
100741    sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
100742  }
100743#endif
100744
100745  /* Resolve the column names in all the expressions in the
100746  ** WHERE clause.
100747  */
100748  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
100749    goto update_cleanup;
100750  }
100751
100752  /* Begin the database scan
100753  */
100754  sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
100755  pWInfo = sqlite3WhereBegin(
100756      pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED
100757  );
100758  if( pWInfo==0 ) goto update_cleanup;
100759  okOnePass = pWInfo->okOnePass;
100760
100761  /* Remember the rowid of every item to be updated.
100762  */
100763  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
100764  if( !okOnePass ){
100765    sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
100766  }
100767
100768  /* End the database scan loop.
100769  */
100770  sqlite3WhereEnd(pWInfo);
100771
100772  /* Initialize the count of updated rows
100773  */
100774  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
100775    regRowCount = ++pParse->nMem;
100776    sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
100777  }
100778
100779  if( !isView ){
100780    /*
100781    ** Open every index that needs updating.  Note that if any
100782    ** index could potentially invoke a REPLACE conflict resolution
100783    ** action, then we need to open all indices because we might need
100784    ** to be deleting some records.
100785    */
100786    if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
100787    if( onError==OE_Replace ){
100788      openAll = 1;
100789    }else{
100790      openAll = 0;
100791      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100792        if( pIdx->onError==OE_Replace ){
100793          openAll = 1;
100794          break;
100795        }
100796      }
100797    }
100798    for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100799      assert( aRegIdx );
100800      if( openAll || aRegIdx[i]>0 ){
100801        KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
100802        sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
100803                       (char*)pKey, P4_KEYINFO_HANDOFF);
100804        assert( pParse->nTab>iCur+i+1 );
100805      }
100806    }
100807  }
100808
100809  /* Top of the update loop */
100810  if( okOnePass ){
100811    int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
100812    addr = sqlite3VdbeAddOp0(v, OP_Goto);
100813    sqlite3VdbeJumpHere(v, a1);
100814  }else{
100815    addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
100816  }
100817
100818  /* Make cursor iCur point to the record that is being updated. If
100819  ** this record does not exist for some reason (deleted by a trigger,
100820  ** for example, then jump to the next iteration of the RowSet loop.  */
100821  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100822
100823  /* If the record number will change, set register regNewRowid to
100824  ** contain the new value. If the record number is not being modified,
100825  ** then regNewRowid is the same register as regOldRowid, which is
100826  ** already populated.  */
100827  assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
100828  if( chngRowid ){
100829    sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
100830    sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
100831  }
100832
100833  /* If there are triggers on this table, populate an array of registers
100834  ** with the required old.* column data.  */
100835  if( hasFK || pTrigger ){
100836    u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
100837    oldmask |= sqlite3TriggerColmask(pParse,
100838        pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
100839    );
100840    for(i=0; i<pTab->nCol; i++){
100841      if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
100842        sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
100843      }else{
100844        sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
100845      }
100846    }
100847    if( chngRowid==0 ){
100848      sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
100849    }
100850  }
100851
100852  /* Populate the array of registers beginning at regNew with the new
100853  ** row data. This array is used to check constaints, create the new
100854  ** table and index records, and as the values for any new.* references
100855  ** made by triggers.
100856  **
100857  ** If there are one or more BEFORE triggers, then do not populate the
100858  ** registers associated with columns that are (a) not modified by
100859  ** this UPDATE statement and (b) not accessed by new.* references. The
100860  ** values for registers not modified by the UPDATE must be reloaded from
100861  ** the database after the BEFORE triggers are fired anyway (as the trigger
100862  ** may have modified them). So not loading those that are not going to
100863  ** be used eliminates some redundant opcodes.
100864  */
100865  newmask = sqlite3TriggerColmask(
100866      pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
100867  );
100868  sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
100869  for(i=0; i<pTab->nCol; i++){
100870    if( i==pTab->iPKey ){
100871      /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
100872    }else{
100873      j = aXRef[i];
100874      if( j>=0 ){
100875        sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
100876      }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
100877        /* This branch loads the value of a column that will not be changed
100878        ** into a register. This is done if there are no BEFORE triggers, or
100879        ** if there are one or more BEFORE triggers that use this value via
100880        ** a new.* reference in a trigger program.
100881        */
100882        testcase( i==31 );
100883        testcase( i==32 );
100884        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100885        sqlite3ColumnDefault(v, pTab, i, regNew+i);
100886      }
100887    }
100888  }
100889
100890  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
100891  ** verified. One could argue that this is wrong.
100892  */
100893  if( tmask&TRIGGER_BEFORE ){
100894    sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
100895    sqlite3TableAffinityStr(v, pTab);
100896    sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
100897        TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
100898
100899    /* The row-trigger may have deleted the row being updated. In this
100900    ** case, jump to the next row. No updates or AFTER triggers are
100901    ** required. This behaviour - what happens when the row being updated
100902    ** is deleted or renamed by a BEFORE trigger - is left undefined in the
100903    ** documentation.
100904    */
100905    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
100906
100907    /* If it did not delete it, the row-trigger may still have modified
100908    ** some of the columns of the row being updated. Load the values for
100909    ** all columns not modified by the update statement into their
100910    ** registers in case this has happened.
100911    */
100912    for(i=0; i<pTab->nCol; i++){
100913      if( aXRef[i]<0 && i!=pTab->iPKey ){
100914        sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
100915        sqlite3ColumnDefault(v, pTab, i, regNew+i);
100916      }
100917    }
100918  }
100919
100920  if( !isView ){
100921    int j1;                       /* Address of jump instruction */
100922
100923    /* Do constraint checks. */
100924    sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
100925        aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
100926
100927    /* Do FK constraint checks. */
100928    if( hasFK ){
100929      sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
100930    }
100931
100932    /* Delete the index entries associated with the current record.  */
100933    j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
100934    sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
100935
100936    /* If changing the record number, delete the old record.  */
100937    if( hasFK || chngRowid ){
100938      sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
100939    }
100940    sqlite3VdbeJumpHere(v, j1);
100941
100942    if( hasFK ){
100943      sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
100944    }
100945
100946    /* Insert the new index entries and the new record. */
100947    sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
100948
100949    /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
100950    ** handle rows (possibly in other tables) that refer via a foreign key
100951    ** to the row just updated. */
100952    if( hasFK ){
100953      sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
100954    }
100955  }
100956
100957  /* Increment the row counter
100958  */
100959  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
100960    sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
100961  }
100962
100963  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
100964      TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
100965
100966  /* Repeat the above with the next record to be updated, until
100967  ** all record selected by the WHERE clause have been updated.
100968  */
100969  sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
100970  sqlite3VdbeJumpHere(v, addr);
100971
100972  /* Close all tables */
100973  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100974    assert( aRegIdx );
100975    if( openAll || aRegIdx[i]>0 ){
100976      sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
100977    }
100978  }
100979  sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
100980
100981  /* Update the sqlite_sequence table by storing the content of the
100982  ** maximum rowid counter values recorded while inserting into
100983  ** autoincrement tables.
100984  */
100985  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
100986    sqlite3AutoincrementEnd(pParse);
100987  }
100988
100989  /*
100990  ** Return the number of rows that were changed. If this routine is
100991  ** generating code because of a call to sqlite3NestedParse(), do not
100992  ** invoke the callback function.
100993  */
100994  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
100995    sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
100996    sqlite3VdbeSetNumCols(v, 1);
100997    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
100998  }
100999
101000update_cleanup:
101001  sqlite3AuthContextPop(&sContext);
101002  sqlite3DbFree(db, aRegIdx);
101003  sqlite3DbFree(db, aXRef);
101004  sqlite3SrcListDelete(db, pTabList);
101005  sqlite3ExprListDelete(db, pChanges);
101006  sqlite3ExprDelete(db, pWhere);
101007  return;
101008}
101009/* Make sure "isView" and other macros defined above are undefined. Otherwise
101010** thely may interfere with compilation of other functions in this file
101011** (or in another file, if this file becomes part of the amalgamation).  */
101012#ifdef isView
101013 #undef isView
101014#endif
101015#ifdef pTrigger
101016 #undef pTrigger
101017#endif
101018
101019#ifndef SQLITE_OMIT_VIRTUALTABLE
101020/*
101021** Generate code for an UPDATE of a virtual table.
101022**
101023** The strategy is that we create an ephemerial table that contains
101024** for each row to be changed:
101025**
101026**   (A)  The original rowid of that row.
101027**   (B)  The revised rowid for the row. (note1)
101028**   (C)  The content of every column in the row.
101029**
101030** Then we loop over this ephemeral table and for each row in
101031** the ephermeral table call VUpdate.
101032**
101033** When finished, drop the ephemeral table.
101034**
101035** (note1) Actually, if we know in advance that (A) is always the same
101036** as (B) we only store (A), then duplicate (A) when pulling
101037** it out of the ephemeral table before calling VUpdate.
101038*/
101039static void updateVirtualTable(
101040  Parse *pParse,       /* The parsing context */
101041  SrcList *pSrc,       /* The virtual table to be modified */
101042  Table *pTab,         /* The virtual table */
101043  ExprList *pChanges,  /* The columns to change in the UPDATE statement */
101044  Expr *pRowid,        /* Expression used to recompute the rowid */
101045  int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
101046  Expr *pWhere,        /* WHERE clause of the UPDATE statement */
101047  int onError          /* ON CONFLICT strategy */
101048){
101049  Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
101050  ExprList *pEList = 0;     /* The result set of the SELECT statement */
101051  Select *pSelect = 0;      /* The SELECT statement */
101052  Expr *pExpr;              /* Temporary expression */
101053  int ephemTab;             /* Table holding the result of the SELECT */
101054  int i;                    /* Loop counter */
101055  int addr;                 /* Address of top of loop */
101056  int iReg;                 /* First register in set passed to OP_VUpdate */
101057  sqlite3 *db = pParse->db; /* Database connection */
101058  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
101059  SelectDest dest;
101060
101061  /* Construct the SELECT statement that will find the new values for
101062  ** all updated rows.
101063  */
101064  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
101065  if( pRowid ){
101066    pEList = sqlite3ExprListAppend(pParse, pEList,
101067                                   sqlite3ExprDup(db, pRowid, 0));
101068  }
101069  assert( pTab->iPKey<0 );
101070  for(i=0; i<pTab->nCol; i++){
101071    if( aXRef[i]>=0 ){
101072      pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
101073    }else{
101074      pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
101075    }
101076    pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
101077  }
101078  pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
101079
101080  /* Create the ephemeral table into which the update results will
101081  ** be stored.
101082  */
101083  assert( v );
101084  ephemTab = pParse->nTab++;
101085  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
101086  sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
101087
101088  /* fill the ephemeral table
101089  */
101090  sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
101091  sqlite3Select(pParse, pSelect, &dest);
101092
101093  /* Generate code to scan the ephemeral table and call VUpdate. */
101094  iReg = ++pParse->nMem;
101095  pParse->nMem += pTab->nCol+1;
101096  addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
101097  sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
101098  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
101099  for(i=0; i<pTab->nCol; i++){
101100    sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
101101  }
101102  sqlite3VtabMakeWritable(pParse, pTab);
101103  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
101104  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
101105  sqlite3MayAbort(pParse);
101106  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
101107  sqlite3VdbeJumpHere(v, addr);
101108  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
101109
101110  /* Cleanup */
101111  sqlite3SelectDelete(db, pSelect);
101112}
101113#endif /* SQLITE_OMIT_VIRTUALTABLE */
101114
101115/************** End of update.c **********************************************/
101116/************** Begin file vacuum.c ******************************************/
101117/*
101118** 2003 April 6
101119**
101120** The author disclaims copyright to this source code.  In place of
101121** a legal notice, here is a blessing:
101122**
101123**    May you do good and not evil.
101124**    May you find forgiveness for yourself and forgive others.
101125**    May you share freely, never taking more than you give.
101126**
101127*************************************************************************
101128** This file contains code used to implement the VACUUM command.
101129**
101130** Most of the code in this file may be omitted by defining the
101131** SQLITE_OMIT_VACUUM macro.
101132*/
101133
101134#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
101135/*
101136** Finalize a prepared statement.  If there was an error, store the
101137** text of the error message in *pzErrMsg.  Return the result code.
101138*/
101139static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
101140  int rc;
101141  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
101142  if( rc ){
101143    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101144  }
101145  return rc;
101146}
101147
101148/*
101149** Execute zSql on database db. Return an error code.
101150*/
101151static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101152  sqlite3_stmt *pStmt;
101153  VVA_ONLY( int rc; )
101154  if( !zSql ){
101155    return SQLITE_NOMEM;
101156  }
101157  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
101158    sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
101159    return sqlite3_errcode(db);
101160  }
101161  VVA_ONLY( rc = ) sqlite3_step(pStmt);
101162  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
101163  return vacuumFinalize(db, pStmt, pzErrMsg);
101164}
101165
101166/*
101167** Execute zSql on database db. The statement returns exactly
101168** one column. Execute this as SQL on the same database.
101169*/
101170static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
101171  sqlite3_stmt *pStmt;
101172  int rc;
101173
101174  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
101175  if( rc!=SQLITE_OK ) return rc;
101176
101177  while( SQLITE_ROW==sqlite3_step(pStmt) ){
101178    rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
101179    if( rc!=SQLITE_OK ){
101180      vacuumFinalize(db, pStmt, pzErrMsg);
101181      return rc;
101182    }
101183  }
101184
101185  return vacuumFinalize(db, pStmt, pzErrMsg);
101186}
101187
101188/*
101189** The non-standard VACUUM command is used to clean up the database,
101190** collapse free space, etc.  It is modelled after the VACUUM command
101191** in PostgreSQL.
101192**
101193** In version 1.0.x of SQLite, the VACUUM command would call
101194** gdbm_reorganize() on all the database tables.  But beginning
101195** with 2.0.0, SQLite no longer uses GDBM so this command has
101196** become a no-op.
101197*/
101198SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
101199  Vdbe *v = sqlite3GetVdbe(pParse);
101200  if( v ){
101201    sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
101202  }
101203  return;
101204}
101205
101206/*
101207** This routine implements the OP_Vacuum opcode of the VDBE.
101208*/
101209SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
101210  int rc = SQLITE_OK;     /* Return code from service routines */
101211  Btree *pMain;           /* The database being vacuumed */
101212  Btree *pTemp;           /* The temporary database we vacuum into */
101213  char *zSql = 0;         /* SQL statements */
101214  int saved_flags;        /* Saved value of the db->flags */
101215  int saved_nChange;      /* Saved value of db->nChange */
101216  int saved_nTotalChange; /* Saved value of db->nTotalChange */
101217  void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
101218  Db *pDb = 0;            /* Database to detach at end of vacuum */
101219  int isMemDb;            /* True if vacuuming a :memory: database */
101220  int nRes;               /* Bytes of reserved space at the end of each page */
101221  int nDb;                /* Number of attached databases */
101222
101223  if( !db->autoCommit ){
101224    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
101225    return SQLITE_ERROR;
101226  }
101227  if( db->activeVdbeCnt>1 ){
101228    sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
101229    return SQLITE_ERROR;
101230  }
101231
101232  /* Save the current value of the database flags so that it can be
101233  ** restored before returning. Then set the writable-schema flag, and
101234  ** disable CHECK and foreign key constraints.  */
101235  saved_flags = db->flags;
101236  saved_nChange = db->nChange;
101237  saved_nTotalChange = db->nTotalChange;
101238  saved_xTrace = db->xTrace;
101239  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
101240  db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
101241  db->xTrace = 0;
101242
101243  pMain = db->aDb[0].pBt;
101244  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
101245
101246  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
101247  ** can be set to 'off' for this file, as it is not recovered if a crash
101248  ** occurs anyway. The integrity of the database is maintained by a
101249  ** (possibly synchronous) transaction opened on the main database before
101250  ** sqlite3BtreeCopyFile() is called.
101251  **
101252  ** An optimisation would be to use a non-journaled pager.
101253  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
101254  ** that actually made the VACUUM run slower.  Very little journalling
101255  ** actually occurs when doing a vacuum since the vacuum_db is initially
101256  ** empty.  Only the journal header is written.  Apparently it takes more
101257  ** time to parse and run the PRAGMA to turn journalling off than it does
101258  ** to write the journal header file.
101259  */
101260  nDb = db->nDb;
101261  if( sqlite3TempInMemory(db) ){
101262    zSql = "ATTACH ':memory:' AS vacuum_db;";
101263  }else{
101264    zSql = "ATTACH '' AS vacuum_db;";
101265  }
101266  rc = execSql(db, pzErrMsg, zSql);
101267  if( db->nDb>nDb ){
101268    pDb = &db->aDb[db->nDb-1];
101269    assert( strcmp(pDb->zName,"vacuum_db")==0 );
101270  }
101271  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101272  pTemp = db->aDb[db->nDb-1].pBt;
101273
101274  /* The call to execSql() to attach the temp database has left the file
101275  ** locked (as there was more than one active statement when the transaction
101276  ** to read the schema was concluded. Unlock it here so that this doesn't
101277  ** cause problems for the call to BtreeSetPageSize() below.  */
101278  sqlite3BtreeCommit(pTemp);
101279
101280  nRes = sqlite3BtreeGetReserve(pMain);
101281
101282  /* A VACUUM cannot change the pagesize of an encrypted database. */
101283#ifdef SQLITE_HAS_CODEC
101284  if( db->nextPagesize ){
101285    extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
101286    int nKey;
101287    char *zKey;
101288    sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
101289    if( nKey ) db->nextPagesize = 0;
101290  }
101291#endif
101292
101293  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
101294  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101295
101296  /* Begin a transaction and take an exclusive lock on the main database
101297  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
101298  ** to ensure that we do not try to change the page-size on a WAL database.
101299  */
101300  rc = execSql(db, pzErrMsg, "BEGIN;");
101301  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101302  rc = sqlite3BtreeBeginTrans(pMain, 2);
101303  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101304
101305  /* Do not attempt to change the page size for a WAL database */
101306  if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
101307                                               ==PAGER_JOURNALMODE_WAL ){
101308    db->nextPagesize = 0;
101309  }
101310
101311  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
101312   || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
101313   || NEVER(db->mallocFailed)
101314  ){
101315    rc = SQLITE_NOMEM;
101316    goto end_of_vacuum;
101317  }
101318
101319#ifndef SQLITE_OMIT_AUTOVACUUM
101320  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
101321                                           sqlite3BtreeGetAutoVacuum(pMain));
101322#endif
101323
101324  /* Query the schema of the main database. Create a mirror schema
101325  ** in the temporary database.
101326  */
101327  rc = execExecSql(db, pzErrMsg,
101328      "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
101329      "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
101330      "   AND rootpage>0"
101331  );
101332  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101333  rc = execExecSql(db, pzErrMsg,
101334      "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
101335      "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
101336  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101337  rc = execExecSql(db, pzErrMsg,
101338      "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
101339      "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
101340  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101341
101342  /* Loop through the tables in the main database. For each, do
101343  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
101344  ** the contents to the temporary database.
101345  */
101346  rc = execExecSql(db, pzErrMsg,
101347      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101348      "|| ' SELECT * FROM main.' || quote(name) || ';'"
101349      "FROM main.sqlite_master "
101350      "WHERE type = 'table' AND name!='sqlite_sequence' "
101351      "  AND rootpage>0"
101352  );
101353  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101354
101355  /* Copy over the sequence table
101356  */
101357  rc = execExecSql(db, pzErrMsg,
101358      "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
101359      "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
101360  );
101361  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101362  rc = execExecSql(db, pzErrMsg,
101363      "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
101364      "|| ' SELECT * FROM main.' || quote(name) || ';' "
101365      "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
101366  );
101367  if( rc!=SQLITE_OK ) goto end_of_vacuum;
101368
101369
101370  /* Copy the triggers, views, and virtual tables from the main database
101371  ** over to the temporary database.  None of these objects has any
101372  ** associated storage, so all we have to do is copy their entries
101373  ** from the SQLITE_MASTER table.
101374  */
101375  rc = execSql(db, pzErrMsg,
101376      "INSERT INTO vacuum_db.sqlite_master "
101377      "  SELECT type, name, tbl_name, rootpage, sql"
101378      "    FROM main.sqlite_master"
101379      "   WHERE type='view' OR type='trigger'"
101380      "      OR (type='table' AND rootpage=0)"
101381  );
101382  if( rc ) goto end_of_vacuum;
101383
101384  /* At this point, there is a write transaction open on both the
101385  ** vacuum database and the main database. Assuming no error occurs,
101386  ** both transactions are closed by this block - the main database
101387  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
101388  ** call to sqlite3BtreeCommit().
101389  */
101390  {
101391    u32 meta;
101392    int i;
101393
101394    /* This array determines which meta meta values are preserved in the
101395    ** vacuum.  Even entries are the meta value number and odd entries
101396    ** are an increment to apply to the meta value after the vacuum.
101397    ** The increment is used to increase the schema cookie so that other
101398    ** connections to the same database will know to reread the schema.
101399    */
101400    static const unsigned char aCopy[] = {
101401       BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
101402       BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
101403       BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
101404       BTREE_USER_VERSION,       0,  /* Preserve the user version */
101405    };
101406
101407    assert( 1==sqlite3BtreeIsInTrans(pTemp) );
101408    assert( 1==sqlite3BtreeIsInTrans(pMain) );
101409
101410    /* Copy Btree meta values */
101411    for(i=0; i<ArraySize(aCopy); i+=2){
101412      /* GetMeta() and UpdateMeta() cannot fail in this context because
101413      ** we already have page 1 loaded into cache and marked dirty. */
101414      sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
101415      rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
101416      if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
101417    }
101418
101419    rc = sqlite3BtreeCopyFile(pMain, pTemp);
101420    if( rc!=SQLITE_OK ) goto end_of_vacuum;
101421    rc = sqlite3BtreeCommit(pTemp);
101422    if( rc!=SQLITE_OK ) goto end_of_vacuum;
101423#ifndef SQLITE_OMIT_AUTOVACUUM
101424    sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
101425#endif
101426  }
101427
101428  assert( rc==SQLITE_OK );
101429  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
101430
101431end_of_vacuum:
101432  /* Restore the original value of db->flags */
101433  db->flags = saved_flags;
101434  db->nChange = saved_nChange;
101435  db->nTotalChange = saved_nTotalChange;
101436  db->xTrace = saved_xTrace;
101437  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
101438
101439  /* Currently there is an SQL level transaction open on the vacuum
101440  ** database. No locks are held on any other files (since the main file
101441  ** was committed at the btree level). So it safe to end the transaction
101442  ** by manually setting the autoCommit flag to true and detaching the
101443  ** vacuum database. The vacuum_db journal file is deleted when the pager
101444  ** is closed by the DETACH.
101445  */
101446  db->autoCommit = 1;
101447
101448  if( pDb ){
101449    sqlite3BtreeClose(pDb->pBt);
101450    pDb->pBt = 0;
101451    pDb->pSchema = 0;
101452  }
101453
101454  /* This both clears the schemas and reduces the size of the db->aDb[]
101455  ** array. */
101456  sqlite3ResetInternalSchema(db, -1);
101457
101458  return rc;
101459}
101460
101461#endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
101462
101463/************** End of vacuum.c **********************************************/
101464/************** Begin file vtab.c ********************************************/
101465/*
101466** 2006 June 10
101467**
101468** The author disclaims copyright to this source code.  In place of
101469** a legal notice, here is a blessing:
101470**
101471**    May you do good and not evil.
101472**    May you find forgiveness for yourself and forgive others.
101473**    May you share freely, never taking more than you give.
101474**
101475*************************************************************************
101476** This file contains code used to help implement virtual tables.
101477*/
101478#ifndef SQLITE_OMIT_VIRTUALTABLE
101479
101480/*
101481** Before a virtual table xCreate() or xConnect() method is invoked, the
101482** sqlite3.pVtabCtx member variable is set to point to an instance of
101483** this struct allocated on the stack. It is used by the implementation of
101484** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
101485** are invoked only from within xCreate and xConnect methods.
101486*/
101487struct VtabCtx {
101488  Table *pTab;
101489  VTable *pVTable;
101490};
101491
101492/*
101493** The actual function that does the work of creating a new module.
101494** This function implements the sqlite3_create_module() and
101495** sqlite3_create_module_v2() interfaces.
101496*/
101497static int createModule(
101498  sqlite3 *db,                    /* Database in which module is registered */
101499  const char *zName,              /* Name assigned to this module */
101500  const sqlite3_module *pModule,  /* The definition of the module */
101501  void *pAux,                     /* Context pointer for xCreate/xConnect */
101502  void (*xDestroy)(void *)        /* Module destructor function */
101503){
101504  int rc, nName;
101505  Module *pMod;
101506
101507  sqlite3_mutex_enter(db->mutex);
101508  nName = sqlite3Strlen30(zName);
101509  pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
101510  if( pMod ){
101511    Module *pDel;
101512    char *zCopy = (char *)(&pMod[1]);
101513    memcpy(zCopy, zName, nName+1);
101514    pMod->zName = zCopy;
101515    pMod->pModule = pModule;
101516    pMod->pAux = pAux;
101517    pMod->xDestroy = xDestroy;
101518    pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
101519    if( pDel && pDel->xDestroy ){
101520      sqlite3ResetInternalSchema(db, -1);
101521      pDel->xDestroy(pDel->pAux);
101522    }
101523    sqlite3DbFree(db, pDel);
101524    if( pDel==pMod ){
101525      db->mallocFailed = 1;
101526    }
101527  }else if( xDestroy ){
101528    xDestroy(pAux);
101529  }
101530  rc = sqlite3ApiExit(db, SQLITE_OK);
101531  sqlite3_mutex_leave(db->mutex);
101532  return rc;
101533}
101534
101535
101536/*
101537** External API function used to create a new virtual-table module.
101538*/
101539SQLITE_API int sqlite3_create_module(
101540  sqlite3 *db,                    /* Database in which module is registered */
101541  const char *zName,              /* Name assigned to this module */
101542  const sqlite3_module *pModule,  /* The definition of the module */
101543  void *pAux                      /* Context pointer for xCreate/xConnect */
101544){
101545  return createModule(db, zName, pModule, pAux, 0);
101546}
101547
101548/*
101549** External API function used to create a new virtual-table module.
101550*/
101551SQLITE_API int sqlite3_create_module_v2(
101552  sqlite3 *db,                    /* Database in which module is registered */
101553  const char *zName,              /* Name assigned to this module */
101554  const sqlite3_module *pModule,  /* The definition of the module */
101555  void *pAux,                     /* Context pointer for xCreate/xConnect */
101556  void (*xDestroy)(void *)        /* Module destructor function */
101557){
101558  return createModule(db, zName, pModule, pAux, xDestroy);
101559}
101560
101561/*
101562** Lock the virtual table so that it cannot be disconnected.
101563** Locks nest.  Every lock should have a corresponding unlock.
101564** If an unlock is omitted, resources leaks will occur.
101565**
101566** If a disconnect is attempted while a virtual table is locked,
101567** the disconnect is deferred until all locks have been removed.
101568*/
101569SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
101570  pVTab->nRef++;
101571}
101572
101573
101574/*
101575** pTab is a pointer to a Table structure representing a virtual-table.
101576** Return a pointer to the VTable object used by connection db to access
101577** this virtual-table, if one has been created, or NULL otherwise.
101578*/
101579SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
101580  VTable *pVtab;
101581  assert( IsVirtual(pTab) );
101582  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
101583  return pVtab;
101584}
101585
101586/*
101587** Decrement the ref-count on a virtual table object. When the ref-count
101588** reaches zero, call the xDisconnect() method to delete the object.
101589*/
101590SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
101591  sqlite3 *db = pVTab->db;
101592
101593  assert( db );
101594  assert( pVTab->nRef>0 );
101595  assert( sqlite3SafetyCheckOk(db) );
101596
101597  pVTab->nRef--;
101598  if( pVTab->nRef==0 ){
101599    sqlite3_vtab *p = pVTab->pVtab;
101600    if( p ){
101601      p->pModule->xDisconnect(p);
101602    }
101603    sqlite3DbFree(db, pVTab);
101604  }
101605}
101606
101607/*
101608** Table p is a virtual table. This function moves all elements in the
101609** p->pVTable list to the sqlite3.pDisconnect lists of their associated
101610** database connections to be disconnected at the next opportunity.
101611** Except, if argument db is not NULL, then the entry associated with
101612** connection db is left in the p->pVTable list.
101613*/
101614static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
101615  VTable *pRet = 0;
101616  VTable *pVTable = p->pVTable;
101617  p->pVTable = 0;
101618
101619  /* Assert that the mutex (if any) associated with the BtShared database
101620  ** that contains table p is held by the caller. See header comments
101621  ** above function sqlite3VtabUnlockList() for an explanation of why
101622  ** this makes it safe to access the sqlite3.pDisconnect list of any
101623  ** database connection that may have an entry in the p->pVTable list.
101624  */
101625  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
101626
101627  while( pVTable ){
101628    sqlite3 *db2 = pVTable->db;
101629    VTable *pNext = pVTable->pNext;
101630    assert( db2 );
101631    if( db2==db ){
101632      pRet = pVTable;
101633      p->pVTable = pRet;
101634      pRet->pNext = 0;
101635    }else{
101636      pVTable->pNext = db2->pDisconnect;
101637      db2->pDisconnect = pVTable;
101638    }
101639    pVTable = pNext;
101640  }
101641
101642  assert( !db || pRet );
101643  return pRet;
101644}
101645
101646
101647/*
101648** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
101649**
101650** This function may only be called when the mutexes associated with all
101651** shared b-tree databases opened using connection db are held by the
101652** caller. This is done to protect the sqlite3.pDisconnect list. The
101653** sqlite3.pDisconnect list is accessed only as follows:
101654**
101655**   1) By this function. In this case, all BtShared mutexes and the mutex
101656**      associated with the database handle itself must be held.
101657**
101658**   2) By function vtabDisconnectAll(), when it adds a VTable entry to
101659**      the sqlite3.pDisconnect list. In this case either the BtShared mutex
101660**      associated with the database the virtual table is stored in is held
101661**      or, if the virtual table is stored in a non-sharable database, then
101662**      the database handle mutex is held.
101663**
101664** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
101665** by multiple threads. It is thread-safe.
101666*/
101667SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
101668  VTable *p = db->pDisconnect;
101669  db->pDisconnect = 0;
101670
101671  assert( sqlite3BtreeHoldsAllMutexes(db) );
101672  assert( sqlite3_mutex_held(db->mutex) );
101673
101674  if( p ){
101675    sqlite3ExpirePreparedStatements(db);
101676    do {
101677      VTable *pNext = p->pNext;
101678      sqlite3VtabUnlock(p);
101679      p = pNext;
101680    }while( p );
101681  }
101682}
101683
101684/*
101685** Clear any and all virtual-table information from the Table record.
101686** This routine is called, for example, just before deleting the Table
101687** record.
101688**
101689** Since it is a virtual-table, the Table structure contains a pointer
101690** to the head of a linked list of VTable structures. Each VTable
101691** structure is associated with a single sqlite3* user of the schema.
101692** The reference count of the VTable structure associated with database
101693** connection db is decremented immediately (which may lead to the
101694** structure being xDisconnected and free). Any other VTable structures
101695** in the list are moved to the sqlite3.pDisconnect list of the associated
101696** database connection.
101697*/
101698SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
101699  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
101700  if( p->azModuleArg ){
101701    int i;
101702    for(i=0; i<p->nModuleArg; i++){
101703      sqlite3DbFree(db, p->azModuleArg[i]);
101704    }
101705    sqlite3DbFree(db, p->azModuleArg);
101706  }
101707}
101708
101709/*
101710** Add a new module argument to pTable->azModuleArg[].
101711** The string is not copied - the pointer is stored.  The
101712** string will be freed automatically when the table is
101713** deleted.
101714*/
101715static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
101716  int i = pTable->nModuleArg++;
101717  int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
101718  char **azModuleArg;
101719  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
101720  if( azModuleArg==0 ){
101721    int j;
101722    for(j=0; j<i; j++){
101723      sqlite3DbFree(db, pTable->azModuleArg[j]);
101724    }
101725    sqlite3DbFree(db, zArg);
101726    sqlite3DbFree(db, pTable->azModuleArg);
101727    pTable->nModuleArg = 0;
101728  }else{
101729    azModuleArg[i] = zArg;
101730    azModuleArg[i+1] = 0;
101731  }
101732  pTable->azModuleArg = azModuleArg;
101733}
101734
101735/*
101736** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
101737** statement.  The module name has been parsed, but the optional list
101738** of parameters that follow the module name are still pending.
101739*/
101740SQLITE_PRIVATE void sqlite3VtabBeginParse(
101741  Parse *pParse,        /* Parsing context */
101742  Token *pName1,        /* Name of new table, or database name */
101743  Token *pName2,        /* Name of new table or NULL */
101744  Token *pModuleName,   /* Name of the module for the virtual table */
101745  int ifNotExists       /* No error if the table already exists */
101746){
101747  int iDb;              /* The database the table is being created in */
101748  Table *pTable;        /* The new virtual table */
101749  sqlite3 *db;          /* Database connection */
101750
101751  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
101752  pTable = pParse->pNewTable;
101753  if( pTable==0 ) return;
101754  assert( 0==pTable->pIndex );
101755
101756  db = pParse->db;
101757  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
101758  assert( iDb>=0 );
101759
101760  pTable->tabFlags |= TF_Virtual;
101761  pTable->nModuleArg = 0;
101762  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
101763  addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
101764  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
101765  pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
101766
101767#ifndef SQLITE_OMIT_AUTHORIZATION
101768  /* Creating a virtual table invokes the authorization callback twice.
101769  ** The first invocation, to obtain permission to INSERT a row into the
101770  ** sqlite_master table, has already been made by sqlite3StartTable().
101771  ** The second call, to obtain permission to create the table, is made now.
101772  */
101773  if( pTable->azModuleArg ){
101774    sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
101775            pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
101776  }
101777#endif
101778}
101779
101780/*
101781** This routine takes the module argument that has been accumulating
101782** in pParse->zArg[] and appends it to the list of arguments on the
101783** virtual table currently under construction in pParse->pTable.
101784*/
101785static void addArgumentToVtab(Parse *pParse){
101786  if( pParse->sArg.z && pParse->pNewTable ){
101787    const char *z = (const char*)pParse->sArg.z;
101788    int n = pParse->sArg.n;
101789    sqlite3 *db = pParse->db;
101790    addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
101791  }
101792}
101793
101794/*
101795** The parser calls this routine after the CREATE VIRTUAL TABLE statement
101796** has been completely parsed.
101797*/
101798SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
101799  Table *pTab = pParse->pNewTable;  /* The table being constructed */
101800  sqlite3 *db = pParse->db;         /* The database connection */
101801
101802  if( pTab==0 ) return;
101803  addArgumentToVtab(pParse);
101804  pParse->sArg.z = 0;
101805  if( pTab->nModuleArg<1 ) return;
101806
101807  /* If the CREATE VIRTUAL TABLE statement is being entered for the
101808  ** first time (in other words if the virtual table is actually being
101809  ** created now instead of just being read out of sqlite_master) then
101810  ** do additional initialization work and store the statement text
101811  ** in the sqlite_master table.
101812  */
101813  if( !db->init.busy ){
101814    char *zStmt;
101815    char *zWhere;
101816    int iDb;
101817    Vdbe *v;
101818
101819    /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
101820    if( pEnd ){
101821      pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
101822    }
101823    zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
101824
101825    /* A slot for the record has already been allocated in the
101826    ** SQLITE_MASTER table.  We just need to update that slot with all
101827    ** the information we've collected.
101828    **
101829    ** The VM register number pParse->regRowid holds the rowid of an
101830    ** entry in the sqlite_master table tht was created for this vtab
101831    ** by sqlite3StartTable().
101832    */
101833    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101834    sqlite3NestedParse(pParse,
101835      "UPDATE %Q.%s "
101836         "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
101837       "WHERE rowid=#%d",
101838      db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
101839      pTab->zName,
101840      pTab->zName,
101841      zStmt,
101842      pParse->regRowid
101843    );
101844    sqlite3DbFree(db, zStmt);
101845    v = sqlite3GetVdbe(pParse);
101846    sqlite3ChangeCookie(pParse, iDb);
101847
101848    sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
101849    zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
101850    sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
101851    sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
101852                         pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
101853  }
101854
101855  /* If we are rereading the sqlite_master table create the in-memory
101856  ** record of the table. The xConnect() method is not called until
101857  ** the first time the virtual table is used in an SQL statement. This
101858  ** allows a schema that contains virtual tables to be loaded before
101859  ** the required virtual table implementations are registered.  */
101860  else {
101861    Table *pOld;
101862    Schema *pSchema = pTab->pSchema;
101863    const char *zName = pTab->zName;
101864    int nName = sqlite3Strlen30(zName);
101865    assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
101866    pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
101867    if( pOld ){
101868      db->mallocFailed = 1;
101869      assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
101870      return;
101871    }
101872    pParse->pNewTable = 0;
101873  }
101874}
101875
101876/*
101877** The parser calls this routine when it sees the first token
101878** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
101879*/
101880SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
101881  addArgumentToVtab(pParse);
101882  pParse->sArg.z = 0;
101883  pParse->sArg.n = 0;
101884}
101885
101886/*
101887** The parser calls this routine for each token after the first token
101888** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
101889*/
101890SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
101891  Token *pArg = &pParse->sArg;
101892  if( pArg->z==0 ){
101893    pArg->z = p->z;
101894    pArg->n = p->n;
101895  }else{
101896    assert(pArg->z < p->z);
101897    pArg->n = (int)(&p->z[p->n] - pArg->z);
101898  }
101899}
101900
101901/*
101902** Invoke a virtual table constructor (either xCreate or xConnect). The
101903** pointer to the function to invoke is passed as the fourth parameter
101904** to this procedure.
101905*/
101906static int vtabCallConstructor(
101907  sqlite3 *db,
101908  Table *pTab,
101909  Module *pMod,
101910  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
101911  char **pzErr
101912){
101913  VtabCtx sCtx;
101914  VTable *pVTable;
101915  int rc;
101916  const char *const*azArg = (const char *const*)pTab->azModuleArg;
101917  int nArg = pTab->nModuleArg;
101918  char *zErr = 0;
101919  char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
101920
101921  if( !zModuleName ){
101922    return SQLITE_NOMEM;
101923  }
101924
101925  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
101926  if( !pVTable ){
101927    sqlite3DbFree(db, zModuleName);
101928    return SQLITE_NOMEM;
101929  }
101930  pVTable->db = db;
101931  pVTable->pMod = pMod;
101932
101933  /* Invoke the virtual table constructor */
101934  assert( &db->pVtabCtx );
101935  assert( xConstruct );
101936  sCtx.pTab = pTab;
101937  sCtx.pVTable = pVTable;
101938  db->pVtabCtx = &sCtx;
101939  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
101940  db->pVtabCtx = 0;
101941  if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
101942
101943  if( SQLITE_OK!=rc ){
101944    if( zErr==0 ){
101945      *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
101946    }else {
101947      *pzErr = sqlite3MPrintf(db, "%s", zErr);
101948      sqlite3_free(zErr);
101949    }
101950    sqlite3DbFree(db, pVTable);
101951  }else if( ALWAYS(pVTable->pVtab) ){
101952    /* Justification of ALWAYS():  A correct vtab constructor must allocate
101953    ** the sqlite3_vtab object if successful.  */
101954    pVTable->pVtab->pModule = pMod->pModule;
101955    pVTable->nRef = 1;
101956    if( sCtx.pTab ){
101957      const char *zFormat = "vtable constructor did not declare schema: %s";
101958      *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
101959      sqlite3VtabUnlock(pVTable);
101960      rc = SQLITE_ERROR;
101961    }else{
101962      int iCol;
101963      /* If everything went according to plan, link the new VTable structure
101964      ** into the linked list headed by pTab->pVTable. Then loop through the
101965      ** columns of the table to see if any of them contain the token "hidden".
101966      ** If so, set the Column.isHidden flag and remove the token from
101967      ** the type string.  */
101968      pVTable->pNext = pTab->pVTable;
101969      pTab->pVTable = pVTable;
101970
101971      for(iCol=0; iCol<pTab->nCol; iCol++){
101972        char *zType = pTab->aCol[iCol].zType;
101973        int nType;
101974        int i = 0;
101975        if( !zType ) continue;
101976        nType = sqlite3Strlen30(zType);
101977        if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
101978          for(i=0; i<nType; i++){
101979            if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
101980             && (zType[i+7]=='\0' || zType[i+7]==' ')
101981            ){
101982              i++;
101983              break;
101984            }
101985          }
101986        }
101987        if( i<nType ){
101988          int j;
101989          int nDel = 6 + (zType[i+6] ? 1 : 0);
101990          for(j=i; (j+nDel)<=nType; j++){
101991            zType[j] = zType[j+nDel];
101992          }
101993          if( zType[i]=='\0' && i>0 ){
101994            assert(zType[i-1]==' ');
101995            zType[i-1] = '\0';
101996          }
101997          pTab->aCol[iCol].isHidden = 1;
101998        }
101999      }
102000    }
102001  }
102002
102003  sqlite3DbFree(db, zModuleName);
102004  return rc;
102005}
102006
102007/*
102008** This function is invoked by the parser to call the xConnect() method
102009** of the virtual table pTab. If an error occurs, an error code is returned
102010** and an error left in pParse.
102011**
102012** This call is a no-op if table pTab is not a virtual table.
102013*/
102014SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
102015  sqlite3 *db = pParse->db;
102016  const char *zMod;
102017  Module *pMod;
102018  int rc;
102019
102020  assert( pTab );
102021  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
102022    return SQLITE_OK;
102023  }
102024
102025  /* Locate the required virtual table module */
102026  zMod = pTab->azModuleArg[0];
102027  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
102028
102029  if( !pMod ){
102030    const char *zModule = pTab->azModuleArg[0];
102031    sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
102032    rc = SQLITE_ERROR;
102033  }else{
102034    char *zErr = 0;
102035    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
102036    if( rc!=SQLITE_OK ){
102037      sqlite3ErrorMsg(pParse, "%s", zErr);
102038    }
102039    sqlite3DbFree(db, zErr);
102040  }
102041
102042  return rc;
102043}
102044/*
102045** Grow the db->aVTrans[] array so that there is room for at least one
102046** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
102047*/
102048static int growVTrans(sqlite3 *db){
102049  const int ARRAY_INCR = 5;
102050
102051  /* Grow the sqlite3.aVTrans array if required */
102052  if( (db->nVTrans%ARRAY_INCR)==0 ){
102053    VTable **aVTrans;
102054    int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
102055    aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
102056    if( !aVTrans ){
102057      return SQLITE_NOMEM;
102058    }
102059    memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
102060    db->aVTrans = aVTrans;
102061  }
102062
102063  return SQLITE_OK;
102064}
102065
102066/*
102067** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
102068** have already been reserved using growVTrans().
102069*/
102070static void addToVTrans(sqlite3 *db, VTable *pVTab){
102071  /* Add pVtab to the end of sqlite3.aVTrans */
102072  db->aVTrans[db->nVTrans++] = pVTab;
102073  sqlite3VtabLock(pVTab);
102074}
102075
102076/*
102077** This function is invoked by the vdbe to call the xCreate method
102078** of the virtual table named zTab in database iDb.
102079**
102080** If an error occurs, *pzErr is set to point an an English language
102081** description of the error and an SQLITE_XXX error code is returned.
102082** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
102083*/
102084SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
102085  int rc = SQLITE_OK;
102086  Table *pTab;
102087  Module *pMod;
102088  const char *zMod;
102089
102090  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102091  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
102092
102093  /* Locate the required virtual table module */
102094  zMod = pTab->azModuleArg[0];
102095  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
102096
102097  /* If the module has been registered and includes a Create method,
102098  ** invoke it now. If the module has not been registered, return an
102099  ** error. Otherwise, do nothing.
102100  */
102101  if( !pMod ){
102102    *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
102103    rc = SQLITE_ERROR;
102104  }else{
102105    rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
102106  }
102107
102108  /* Justification of ALWAYS():  The xConstructor method is required to
102109  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
102110  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
102111    rc = growVTrans(db);
102112    if( rc==SQLITE_OK ){
102113      addToVTrans(db, sqlite3GetVTable(db, pTab));
102114    }
102115  }
102116
102117  return rc;
102118}
102119
102120/*
102121** This function is used to set the schema of a virtual table.  It is only
102122** valid to call this function from within the xCreate() or xConnect() of a
102123** virtual table module.
102124*/
102125SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
102126  Parse *pParse;
102127
102128  int rc = SQLITE_OK;
102129  Table *pTab;
102130  char *zErr = 0;
102131
102132  sqlite3_mutex_enter(db->mutex);
102133  if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
102134    sqlite3Error(db, SQLITE_MISUSE, 0);
102135    sqlite3_mutex_leave(db->mutex);
102136    return SQLITE_MISUSE_BKPT;
102137  }
102138  assert( (pTab->tabFlags & TF_Virtual)!=0 );
102139
102140  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
102141  if( pParse==0 ){
102142    rc = SQLITE_NOMEM;
102143  }else{
102144    pParse->declareVtab = 1;
102145    pParse->db = db;
102146    pParse->nQueryLoop = 1;
102147
102148    if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
102149     && pParse->pNewTable
102150     && !db->mallocFailed
102151     && !pParse->pNewTable->pSelect
102152     && (pParse->pNewTable->tabFlags & TF_Virtual)==0
102153    ){
102154      if( !pTab->aCol ){
102155        pTab->aCol = pParse->pNewTable->aCol;
102156        pTab->nCol = pParse->pNewTable->nCol;
102157        pParse->pNewTable->nCol = 0;
102158        pParse->pNewTable->aCol = 0;
102159      }
102160      db->pVtabCtx->pTab = 0;
102161    }else{
102162      sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
102163      sqlite3DbFree(db, zErr);
102164      rc = SQLITE_ERROR;
102165    }
102166    pParse->declareVtab = 0;
102167
102168    if( pParse->pVdbe ){
102169      sqlite3VdbeFinalize(pParse->pVdbe);
102170    }
102171    sqlite3DeleteTable(db, pParse->pNewTable);
102172    sqlite3StackFree(db, pParse);
102173  }
102174
102175  assert( (rc&0xff)==rc );
102176  rc = sqlite3ApiExit(db, rc);
102177  sqlite3_mutex_leave(db->mutex);
102178  return rc;
102179}
102180
102181/*
102182** This function is invoked by the vdbe to call the xDestroy method
102183** of the virtual table named zTab in database iDb. This occurs
102184** when a DROP TABLE is mentioned.
102185**
102186** This call is a no-op if zTab is not a virtual table.
102187*/
102188SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
102189  int rc = SQLITE_OK;
102190  Table *pTab;
102191
102192  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
102193  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
102194    VTable *p = vtabDisconnectAll(db, pTab);
102195
102196    assert( rc==SQLITE_OK );
102197    rc = p->pMod->pModule->xDestroy(p->pVtab);
102198
102199    /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
102200    if( rc==SQLITE_OK ){
102201      assert( pTab->pVTable==p && p->pNext==0 );
102202      p->pVtab = 0;
102203      pTab->pVTable = 0;
102204      sqlite3VtabUnlock(p);
102205    }
102206  }
102207
102208  return rc;
102209}
102210
102211/*
102212** This function invokes either the xRollback or xCommit method
102213** of each of the virtual tables in the sqlite3.aVTrans array. The method
102214** called is identified by the second argument, "offset", which is
102215** the offset of the method to call in the sqlite3_module structure.
102216**
102217** The array is cleared after invoking the callbacks.
102218*/
102219static void callFinaliser(sqlite3 *db, int offset){
102220  int i;
102221  if( db->aVTrans ){
102222    for(i=0; i<db->nVTrans; i++){
102223      VTable *pVTab = db->aVTrans[i];
102224      sqlite3_vtab *p = pVTab->pVtab;
102225      if( p ){
102226        int (*x)(sqlite3_vtab *);
102227        x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
102228        if( x ) x(p);
102229      }
102230      pVTab->iSavepoint = 0;
102231      sqlite3VtabUnlock(pVTab);
102232    }
102233    sqlite3DbFree(db, db->aVTrans);
102234    db->nVTrans = 0;
102235    db->aVTrans = 0;
102236  }
102237}
102238
102239/*
102240** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
102241** array. Return the error code for the first error that occurs, or
102242** SQLITE_OK if all xSync operations are successful.
102243**
102244** Set *pzErrmsg to point to a buffer that should be released using
102245** sqlite3DbFree() containing an error message, if one is available.
102246*/
102247SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
102248  int i;
102249  int rc = SQLITE_OK;
102250  VTable **aVTrans = db->aVTrans;
102251
102252  db->aVTrans = 0;
102253  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102254    int (*x)(sqlite3_vtab *);
102255    sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
102256    if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
102257      rc = x(pVtab);
102258      sqlite3DbFree(db, *pzErrmsg);
102259      *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
102260      sqlite3_free(pVtab->zErrMsg);
102261    }
102262  }
102263  db->aVTrans = aVTrans;
102264  return rc;
102265}
102266
102267/*
102268** Invoke the xRollback method of all virtual tables in the
102269** sqlite3.aVTrans array. Then clear the array itself.
102270*/
102271SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
102272  callFinaliser(db, offsetof(sqlite3_module,xRollback));
102273  return SQLITE_OK;
102274}
102275
102276/*
102277** Invoke the xCommit method of all virtual tables in the
102278** sqlite3.aVTrans array. Then clear the array itself.
102279*/
102280SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
102281  callFinaliser(db, offsetof(sqlite3_module,xCommit));
102282  return SQLITE_OK;
102283}
102284
102285/*
102286** If the virtual table pVtab supports the transaction interface
102287** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
102288** not currently open, invoke the xBegin method now.
102289**
102290** If the xBegin call is successful, place the sqlite3_vtab pointer
102291** in the sqlite3.aVTrans array.
102292*/
102293SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
102294  int rc = SQLITE_OK;
102295  const sqlite3_module *pModule;
102296
102297  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
102298  ** than zero, then this function is being called from within a
102299  ** virtual module xSync() callback. It is illegal to write to
102300  ** virtual module tables in this case, so return SQLITE_LOCKED.
102301  */
102302  if( sqlite3VtabInSync(db) ){
102303    return SQLITE_LOCKED;
102304  }
102305  if( !pVTab ){
102306    return SQLITE_OK;
102307  }
102308  pModule = pVTab->pVtab->pModule;
102309
102310  if( pModule->xBegin ){
102311    int i;
102312
102313    /* If pVtab is already in the aVTrans array, return early */
102314    for(i=0; i<db->nVTrans; i++){
102315      if( db->aVTrans[i]==pVTab ){
102316        return SQLITE_OK;
102317      }
102318    }
102319
102320    /* Invoke the xBegin method. If successful, add the vtab to the
102321    ** sqlite3.aVTrans[] array. */
102322    rc = growVTrans(db);
102323    if( rc==SQLITE_OK ){
102324      rc = pModule->xBegin(pVTab->pVtab);
102325      if( rc==SQLITE_OK ){
102326        addToVTrans(db, pVTab);
102327      }
102328    }
102329  }
102330  return rc;
102331}
102332
102333/*
102334** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
102335** virtual tables that currently have an open transaction. Pass iSavepoint
102336** as the second argument to the virtual table method invoked.
102337**
102338** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
102339** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
102340** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
102341** an open transaction is invoked.
102342**
102343** If any virtual table method returns an error code other than SQLITE_OK,
102344** processing is abandoned and the error returned to the caller of this
102345** function immediately. If all calls to virtual table methods are successful,
102346** SQLITE_OK is returned.
102347*/
102348SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
102349  int rc = SQLITE_OK;
102350
102351  assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
102352  assert( iSavepoint>=0 );
102353  if( db->aVTrans ){
102354    int i;
102355    for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
102356      VTable *pVTab = db->aVTrans[i];
102357      const sqlite3_module *pMod = pVTab->pMod->pModule;
102358      if( pVTab->pVtab && pMod->iVersion>=2 ){
102359        int (*xMethod)(sqlite3_vtab *, int);
102360        switch( op ){
102361          case SAVEPOINT_BEGIN:
102362            xMethod = pMod->xSavepoint;
102363            pVTab->iSavepoint = iSavepoint+1;
102364            break;
102365          case SAVEPOINT_ROLLBACK:
102366            xMethod = pMod->xRollbackTo;
102367            break;
102368          default:
102369            xMethod = pMod->xRelease;
102370            break;
102371        }
102372        if( xMethod && pVTab->iSavepoint>iSavepoint ){
102373          rc = xMethod(pVTab->pVtab, iSavepoint);
102374        }
102375      }
102376    }
102377  }
102378  return rc;
102379}
102380
102381/*
102382** The first parameter (pDef) is a function implementation.  The
102383** second parameter (pExpr) is the first argument to this function.
102384** If pExpr is a column in a virtual table, then let the virtual
102385** table implementation have an opportunity to overload the function.
102386**
102387** This routine is used to allow virtual table implementations to
102388** overload MATCH, LIKE, GLOB, and REGEXP operators.
102389**
102390** Return either the pDef argument (indicating no change) or a
102391** new FuncDef structure that is marked as ephemeral using the
102392** SQLITE_FUNC_EPHEM flag.
102393*/
102394SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
102395  sqlite3 *db,    /* Database connection for reporting malloc problems */
102396  FuncDef *pDef,  /* Function to possibly overload */
102397  int nArg,       /* Number of arguments to the function */
102398  Expr *pExpr     /* First argument to the function */
102399){
102400  Table *pTab;
102401  sqlite3_vtab *pVtab;
102402  sqlite3_module *pMod;
102403  void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
102404  void *pArg = 0;
102405  FuncDef *pNew;
102406  int rc = 0;
102407  char *zLowerName;
102408  unsigned char *z;
102409
102410
102411  /* Check to see the left operand is a column in a virtual table */
102412  if( NEVER(pExpr==0) ) return pDef;
102413  if( pExpr->op!=TK_COLUMN ) return pDef;
102414  pTab = pExpr->pTab;
102415  if( NEVER(pTab==0) ) return pDef;
102416  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
102417  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
102418  assert( pVtab!=0 );
102419  assert( pVtab->pModule!=0 );
102420  pMod = (sqlite3_module *)pVtab->pModule;
102421  if( pMod->xFindFunction==0 ) return pDef;
102422
102423  /* Call the xFindFunction method on the virtual table implementation
102424  ** to see if the implementation wants to overload this function
102425  */
102426  zLowerName = sqlite3DbStrDup(db, pDef->zName);
102427  if( zLowerName ){
102428    for(z=(unsigned char*)zLowerName; *z; z++){
102429      *z = sqlite3UpperToLower[*z];
102430    }
102431    rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
102432    sqlite3DbFree(db, zLowerName);
102433  }
102434  if( rc==0 ){
102435    return pDef;
102436  }
102437
102438  /* Create a new ephemeral function definition for the overloaded
102439  ** function */
102440  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
102441                             + sqlite3Strlen30(pDef->zName) + 1);
102442  if( pNew==0 ){
102443    return pDef;
102444  }
102445  *pNew = *pDef;
102446  pNew->zName = (char *)&pNew[1];
102447  memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
102448  pNew->xFunc = xFunc;
102449  pNew->pUserData = pArg;
102450  pNew->flags |= SQLITE_FUNC_EPHEM;
102451  return pNew;
102452}
102453
102454/*
102455** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
102456** array so that an OP_VBegin will get generated for it.  Add pTab to the
102457** array if it is missing.  If pTab is already in the array, this routine
102458** is a no-op.
102459*/
102460SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
102461  Parse *pToplevel = sqlite3ParseToplevel(pParse);
102462  int i, n;
102463  Table **apVtabLock;
102464
102465  assert( IsVirtual(pTab) );
102466  for(i=0; i<pToplevel->nVtabLock; i++){
102467    if( pTab==pToplevel->apVtabLock[i] ) return;
102468  }
102469  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
102470  apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
102471  if( apVtabLock ){
102472    pToplevel->apVtabLock = apVtabLock;
102473    pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
102474  }else{
102475    pToplevel->db->mallocFailed = 1;
102476  }
102477}
102478
102479/*
102480** Return the ON CONFLICT resolution mode in effect for the virtual
102481** table update operation currently in progress.
102482**
102483** The results of this routine are undefined unless it is called from
102484** within an xUpdate method.
102485*/
102486SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
102487  static const unsigned char aMap[] = {
102488    SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
102489  };
102490  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
102491  assert( OE_Ignore==4 && OE_Replace==5 );
102492  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
102493  return (int)aMap[db->vtabOnConflict-1];
102494}
102495
102496/*
102497** Call from within the xCreate() or xConnect() methods to provide
102498** the SQLite core with additional information about the behavior
102499** of the virtual table being implemented.
102500*/
102501SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
102502  va_list ap;
102503  int rc = SQLITE_OK;
102504
102505  sqlite3_mutex_enter(db->mutex);
102506
102507  va_start(ap, op);
102508  switch( op ){
102509    case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
102510      VtabCtx *p = db->pVtabCtx;
102511      if( !p ){
102512        rc = SQLITE_MISUSE_BKPT;
102513      }else{
102514        assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
102515        p->pVTable->bConstraint = (u8)va_arg(ap, int);
102516      }
102517      break;
102518    }
102519    default:
102520      rc = SQLITE_MISUSE_BKPT;
102521      break;
102522  }
102523  va_end(ap);
102524
102525  if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
102526  sqlite3_mutex_leave(db->mutex);
102527  return rc;
102528}
102529
102530#endif /* SQLITE_OMIT_VIRTUALTABLE */
102531
102532/************** End of vtab.c ************************************************/
102533/************** Begin file where.c *******************************************/
102534/*
102535** 2001 September 15
102536**
102537** The author disclaims copyright to this source code.  In place of
102538** a legal notice, here is a blessing:
102539**
102540**    May you do good and not evil.
102541**    May you find forgiveness for yourself and forgive others.
102542**    May you share freely, never taking more than you give.
102543**
102544*************************************************************************
102545** This module contains C code that generates VDBE code used to process
102546** the WHERE clause of SQL statements.  This module is responsible for
102547** generating the code that loops through a table looking for applicable
102548** rows.  Indices are selected and used to speed the search when doing
102549** so is applicable.  Because this module is responsible for selecting
102550** indices, you might also think of this module as the "query optimizer".
102551*/
102552
102553
102554/*
102555** Trace output macros
102556*/
102557#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
102558SQLITE_PRIVATE int sqlite3WhereTrace = 0;
102559#endif
102560#if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
102561# define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
102562#else
102563# define WHERETRACE(X)
102564#endif
102565
102566/* Forward reference
102567*/
102568typedef struct WhereClause WhereClause;
102569typedef struct WhereMaskSet WhereMaskSet;
102570typedef struct WhereOrInfo WhereOrInfo;
102571typedef struct WhereAndInfo WhereAndInfo;
102572typedef struct WhereCost WhereCost;
102573
102574/*
102575** The query generator uses an array of instances of this structure to
102576** help it analyze the subexpressions of the WHERE clause.  Each WHERE
102577** clause subexpression is separated from the others by AND operators,
102578** usually, or sometimes subexpressions separated by OR.
102579**
102580** All WhereTerms are collected into a single WhereClause structure.
102581** The following identity holds:
102582**
102583**        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
102584**
102585** When a term is of the form:
102586**
102587**              X <op> <expr>
102588**
102589** where X is a column name and <op> is one of certain operators,
102590** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
102591** cursor number and column number for X.  WhereTerm.eOperator records
102592** the <op> using a bitmask encoding defined by WO_xxx below.  The
102593** use of a bitmask encoding for the operator allows us to search
102594** quickly for terms that match any of several different operators.
102595**
102596** A WhereTerm might also be two or more subterms connected by OR:
102597**
102598**         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
102599**
102600** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
102601** and the WhereTerm.u.pOrInfo field points to auxiliary information that
102602** is collected about the
102603**
102604** If a term in the WHERE clause does not match either of the two previous
102605** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
102606** to the original subexpression content and wtFlags is set up appropriately
102607** but no other fields in the WhereTerm object are meaningful.
102608**
102609** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
102610** but they do so indirectly.  A single WhereMaskSet structure translates
102611** cursor number into bits and the translated bit is stored in the prereq
102612** fields.  The translation is used in order to maximize the number of
102613** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
102614** spread out over the non-negative integers.  For example, the cursor
102615** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
102616** translates these sparse cursor numbers into consecutive integers
102617** beginning with 0 in order to make the best possible use of the available
102618** bits in the Bitmask.  So, in the example above, the cursor numbers
102619** would be mapped into integers 0 through 7.
102620**
102621** The number of terms in a join is limited by the number of bits
102622** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
102623** is only able to process joins with 64 or fewer tables.
102624*/
102625typedef struct WhereTerm WhereTerm;
102626struct WhereTerm {
102627  Expr *pExpr;            /* Pointer to the subexpression that is this term */
102628  int iParent;            /* Disable pWC->a[iParent] when this term disabled */
102629  int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
102630  union {
102631    int leftColumn;         /* Column number of X in "X <op> <expr>" */
102632    WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
102633    WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
102634  } u;
102635  u16 eOperator;          /* A WO_xx value describing <op> */
102636  u8 wtFlags;             /* TERM_xxx bit flags.  See below */
102637  u8 nChild;              /* Number of children that must disable us */
102638  WhereClause *pWC;       /* The clause this term is part of */
102639  Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
102640  Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
102641};
102642
102643/*
102644** Allowed values of WhereTerm.wtFlags
102645*/
102646#define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
102647#define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
102648#define TERM_CODED      0x04   /* This term is already coded */
102649#define TERM_COPIED     0x08   /* Has a child */
102650#define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
102651#define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
102652#define TERM_OR_OK      0x40   /* Used during OR-clause processing */
102653#ifdef SQLITE_ENABLE_STAT3
102654#  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
102655#else
102656#  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
102657#endif
102658
102659/*
102660** An instance of the following structure holds all information about a
102661** WHERE clause.  Mostly this is a container for one or more WhereTerms.
102662**
102663** Explanation of pOuter:  For a WHERE clause of the form
102664**
102665**           a AND ((b AND c) OR (d AND e)) AND f
102666**
102667** There are separate WhereClause objects for the whole clause and for
102668** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
102669** subclauses points to the WhereClause object for the whole clause.
102670*/
102671struct WhereClause {
102672  Parse *pParse;           /* The parser context */
102673  WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
102674  Bitmask vmask;           /* Bitmask identifying virtual table cursors */
102675  WhereClause *pOuter;     /* Outer conjunction */
102676  u8 op;                   /* Split operator.  TK_AND or TK_OR */
102677  u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
102678  int nTerm;               /* Number of terms */
102679  int nSlot;               /* Number of entries in a[] */
102680  WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
102681#if defined(SQLITE_SMALL_STACK)
102682  WhereTerm aStatic[1];    /* Initial static space for a[] */
102683#else
102684  WhereTerm aStatic[8];    /* Initial static space for a[] */
102685#endif
102686};
102687
102688/*
102689** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
102690** a dynamically allocated instance of the following structure.
102691*/
102692struct WhereOrInfo {
102693  WhereClause wc;          /* Decomposition into subterms */
102694  Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
102695};
102696
102697/*
102698** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
102699** a dynamically allocated instance of the following structure.
102700*/
102701struct WhereAndInfo {
102702  WhereClause wc;          /* The subexpression broken out */
102703};
102704
102705/*
102706** An instance of the following structure keeps track of a mapping
102707** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
102708**
102709** The VDBE cursor numbers are small integers contained in
102710** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE
102711** clause, the cursor numbers might not begin with 0 and they might
102712** contain gaps in the numbering sequence.  But we want to make maximum
102713** use of the bits in our bitmasks.  This structure provides a mapping
102714** from the sparse cursor numbers into consecutive integers beginning
102715** with 0.
102716**
102717** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
102718** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
102719**
102720** For example, if the WHERE clause expression used these VDBE
102721** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
102722** would map those cursor numbers into bits 0 through 5.
102723**
102724** Note that the mapping is not necessarily ordered.  In the example
102725** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
102726** 57->5, 73->4.  Or one of 719 other combinations might be used. It
102727** does not really matter.  What is important is that sparse cursor
102728** numbers all get mapped into bit numbers that begin with 0 and contain
102729** no gaps.
102730*/
102731struct WhereMaskSet {
102732  int n;                        /* Number of assigned cursor values */
102733  int ix[BMS];                  /* Cursor assigned to each bit */
102734};
102735
102736/*
102737** A WhereCost object records a lookup strategy and the estimated
102738** cost of pursuing that strategy.
102739*/
102740struct WhereCost {
102741  WherePlan plan;    /* The lookup strategy */
102742  double rCost;      /* Overall cost of pursuing this search strategy */
102743  Bitmask used;      /* Bitmask of cursors used by this plan */
102744};
102745
102746/*
102747** Bitmasks for the operators that indices are able to exploit.  An
102748** OR-ed combination of these values can be used when searching for
102749** terms in the where clause.
102750*/
102751#define WO_IN     0x001
102752#define WO_EQ     0x002
102753#define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
102754#define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
102755#define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
102756#define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
102757#define WO_MATCH  0x040
102758#define WO_ISNULL 0x080
102759#define WO_OR     0x100       /* Two or more OR-connected terms */
102760#define WO_AND    0x200       /* Two or more AND-connected terms */
102761#define WO_NOOP   0x800       /* This term does not restrict search space */
102762
102763#define WO_ALL    0xfff       /* Mask of all possible WO_* values */
102764#define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
102765
102766/*
102767** Value for wsFlags returned by bestIndex() and stored in
102768** WhereLevel.wsFlags.  These flags determine which search
102769** strategies are appropriate.
102770**
102771** The least significant 12 bits is reserved as a mask for WO_ values above.
102772** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
102773** But if the table is the right table of a left join, WhereLevel.wsFlags
102774** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
102775** the "op" parameter to findTerm when we are resolving equality constraints.
102776** ISNULL constraints will then not be used on the right table of a left
102777** join.  Tickets #2177 and #2189.
102778*/
102779#define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
102780#define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
102781#define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
102782#define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
102783#define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
102784#define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
102785#define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
102786#define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
102787#define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
102788#define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
102789#define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
102790#define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
102791#define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
102792#define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
102793#define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
102794#define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
102795#define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
102796#define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
102797#define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
102798#define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
102799
102800/*
102801** Initialize a preallocated WhereClause structure.
102802*/
102803static void whereClauseInit(
102804  WhereClause *pWC,        /* The WhereClause to be initialized */
102805  Parse *pParse,           /* The parsing context */
102806  WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
102807  u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
102808){
102809  pWC->pParse = pParse;
102810  pWC->pMaskSet = pMaskSet;
102811  pWC->pOuter = 0;
102812  pWC->nTerm = 0;
102813  pWC->nSlot = ArraySize(pWC->aStatic);
102814  pWC->a = pWC->aStatic;
102815  pWC->vmask = 0;
102816  pWC->wctrlFlags = wctrlFlags;
102817}
102818
102819/* Forward reference */
102820static void whereClauseClear(WhereClause*);
102821
102822/*
102823** Deallocate all memory associated with a WhereOrInfo object.
102824*/
102825static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
102826  whereClauseClear(&p->wc);
102827  sqlite3DbFree(db, p);
102828}
102829
102830/*
102831** Deallocate all memory associated with a WhereAndInfo object.
102832*/
102833static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
102834  whereClauseClear(&p->wc);
102835  sqlite3DbFree(db, p);
102836}
102837
102838/*
102839** Deallocate a WhereClause structure.  The WhereClause structure
102840** itself is not freed.  This routine is the inverse of whereClauseInit().
102841*/
102842static void whereClauseClear(WhereClause *pWC){
102843  int i;
102844  WhereTerm *a;
102845  sqlite3 *db = pWC->pParse->db;
102846  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
102847    if( a->wtFlags & TERM_DYNAMIC ){
102848      sqlite3ExprDelete(db, a->pExpr);
102849    }
102850    if( a->wtFlags & TERM_ORINFO ){
102851      whereOrInfoDelete(db, a->u.pOrInfo);
102852    }else if( a->wtFlags & TERM_ANDINFO ){
102853      whereAndInfoDelete(db, a->u.pAndInfo);
102854    }
102855  }
102856  if( pWC->a!=pWC->aStatic ){
102857    sqlite3DbFree(db, pWC->a);
102858  }
102859}
102860
102861/*
102862** Add a single new WhereTerm entry to the WhereClause object pWC.
102863** The new WhereTerm object is constructed from Expr p and with wtFlags.
102864** The index in pWC->a[] of the new WhereTerm is returned on success.
102865** 0 is returned if the new WhereTerm could not be added due to a memory
102866** allocation error.  The memory allocation failure will be recorded in
102867** the db->mallocFailed flag so that higher-level functions can detect it.
102868**
102869** This routine will increase the size of the pWC->a[] array as necessary.
102870**
102871** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
102872** for freeing the expression p is assumed by the WhereClause object pWC.
102873** This is true even if this routine fails to allocate a new WhereTerm.
102874**
102875** WARNING:  This routine might reallocate the space used to store
102876** WhereTerms.  All pointers to WhereTerms should be invalidated after
102877** calling this routine.  Such pointers may be reinitialized by referencing
102878** the pWC->a[] array.
102879*/
102880static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
102881  WhereTerm *pTerm;
102882  int idx;
102883  testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
102884  if( pWC->nTerm>=pWC->nSlot ){
102885    WhereTerm *pOld = pWC->a;
102886    sqlite3 *db = pWC->pParse->db;
102887    pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
102888    if( pWC->a==0 ){
102889      if( wtFlags & TERM_DYNAMIC ){
102890        sqlite3ExprDelete(db, p);
102891      }
102892      pWC->a = pOld;
102893      return 0;
102894    }
102895    memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
102896    if( pOld!=pWC->aStatic ){
102897      sqlite3DbFree(db, pOld);
102898    }
102899    pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
102900  }
102901  pTerm = &pWC->a[idx = pWC->nTerm++];
102902  pTerm->pExpr = p;
102903  pTerm->wtFlags = wtFlags;
102904  pTerm->pWC = pWC;
102905  pTerm->iParent = -1;
102906  return idx;
102907}
102908
102909/*
102910** This routine identifies subexpressions in the WHERE clause where
102911** each subexpression is separated by the AND operator or some other
102912** operator specified in the op parameter.  The WhereClause structure
102913** is filled with pointers to subexpressions.  For example:
102914**
102915**    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
102916**           \________/     \_______________/     \________________/
102917**            slot[0]            slot[1]               slot[2]
102918**
102919** The original WHERE clause in pExpr is unaltered.  All this routine
102920** does is make slot[] entries point to substructure within pExpr.
102921**
102922** In the previous sentence and in the diagram, "slot[]" refers to
102923** the WhereClause.a[] array.  The slot[] array grows as needed to contain
102924** all terms of the WHERE clause.
102925*/
102926static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
102927  pWC->op = (u8)op;
102928  if( pExpr==0 ) return;
102929  if( pExpr->op!=op ){
102930    whereClauseInsert(pWC, pExpr, 0);
102931  }else{
102932    whereSplit(pWC, pExpr->pLeft, op);
102933    whereSplit(pWC, pExpr->pRight, op);
102934  }
102935}
102936
102937/*
102938** Initialize an expression mask set (a WhereMaskSet object)
102939*/
102940#define initMaskSet(P)  memset(P, 0, sizeof(*P))
102941
102942/*
102943** Return the bitmask for the given cursor number.  Return 0 if
102944** iCursor is not in the set.
102945*/
102946static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
102947  int i;
102948  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
102949  for(i=0; i<pMaskSet->n; i++){
102950    if( pMaskSet->ix[i]==iCursor ){
102951      return ((Bitmask)1)<<i;
102952    }
102953  }
102954  return 0;
102955}
102956
102957/*
102958** Create a new mask for cursor iCursor.
102959**
102960** There is one cursor per table in the FROM clause.  The number of
102961** tables in the FROM clause is limited by a test early in the
102962** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
102963** array will never overflow.
102964*/
102965static void createMask(WhereMaskSet *pMaskSet, int iCursor){
102966  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
102967  pMaskSet->ix[pMaskSet->n++] = iCursor;
102968}
102969
102970/*
102971** This routine walks (recursively) an expression tree and generates
102972** a bitmask indicating which tables are used in that expression
102973** tree.
102974**
102975** In order for this routine to work, the calling function must have
102976** previously invoked sqlite3ResolveExprNames() on the expression.  See
102977** the header comment on that routine for additional information.
102978** The sqlite3ResolveExprNames() routines looks for column names and
102979** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
102980** the VDBE cursor number of the table.  This routine just has to
102981** translate the cursor numbers into bitmask values and OR all
102982** the bitmasks together.
102983*/
102984static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
102985static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
102986static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
102987  Bitmask mask = 0;
102988  if( p==0 ) return 0;
102989  if( p->op==TK_COLUMN ){
102990    mask = getMask(pMaskSet, p->iTable);
102991    return mask;
102992  }
102993  mask = exprTableUsage(pMaskSet, p->pRight);
102994  mask |= exprTableUsage(pMaskSet, p->pLeft);
102995  if( ExprHasProperty(p, EP_xIsSelect) ){
102996    mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
102997  }else{
102998    mask |= exprListTableUsage(pMaskSet, p->x.pList);
102999  }
103000  return mask;
103001}
103002static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
103003  int i;
103004  Bitmask mask = 0;
103005  if( pList ){
103006    for(i=0; i<pList->nExpr; i++){
103007      mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
103008    }
103009  }
103010  return mask;
103011}
103012static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
103013  Bitmask mask = 0;
103014  while( pS ){
103015    SrcList *pSrc = pS->pSrc;
103016    mask |= exprListTableUsage(pMaskSet, pS->pEList);
103017    mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
103018    mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
103019    mask |= exprTableUsage(pMaskSet, pS->pWhere);
103020    mask |= exprTableUsage(pMaskSet, pS->pHaving);
103021    if( ALWAYS(pSrc!=0) ){
103022      int i;
103023      for(i=0; i<pSrc->nSrc; i++){
103024        mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
103025        mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
103026      }
103027    }
103028    pS = pS->pPrior;
103029  }
103030  return mask;
103031}
103032
103033/*
103034** Return TRUE if the given operator is one of the operators that is
103035** allowed for an indexable WHERE clause term.  The allowed operators are
103036** "=", "<", ">", "<=", ">=", and "IN".
103037**
103038** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
103039** of one of the following forms: column = expression column > expression
103040** column >= expression column < expression column <= expression
103041** expression = column expression > column expression >= column
103042** expression < column expression <= column column IN
103043** (expression-list) column IN (subquery) column IS NULL
103044*/
103045static int allowedOp(int op){
103046  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
103047  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
103048  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
103049  assert( TK_GE==TK_EQ+4 );
103050  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
103051}
103052
103053/*
103054** Swap two objects of type TYPE.
103055*/
103056#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
103057
103058/*
103059** Commute a comparison operator.  Expressions of the form "X op Y"
103060** are converted into "Y op X".
103061**
103062** If a collation sequence is associated with either the left or right
103063** side of the comparison, it remains associated with the same side after
103064** the commutation. So "Y collate NOCASE op X" becomes
103065** "X collate NOCASE op Y". This is because any collation sequence on
103066** the left hand side of a comparison overrides any collation sequence
103067** attached to the right. For the same reason the EP_ExpCollate flag
103068** is not commuted.
103069*/
103070static void exprCommute(Parse *pParse, Expr *pExpr){
103071  u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
103072  u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
103073  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
103074  pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
103075  pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
103076  SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
103077  pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
103078  pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
103079  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
103080  if( pExpr->op>=TK_GT ){
103081    assert( TK_LT==TK_GT+2 );
103082    assert( TK_GE==TK_LE+2 );
103083    assert( TK_GT>TK_EQ );
103084    assert( TK_GT<TK_LE );
103085    assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
103086    pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
103087  }
103088}
103089
103090/*
103091** Translate from TK_xx operator to WO_xx bitmask.
103092*/
103093static u16 operatorMask(int op){
103094  u16 c;
103095  assert( allowedOp(op) );
103096  if( op==TK_IN ){
103097    c = WO_IN;
103098  }else if( op==TK_ISNULL ){
103099    c = WO_ISNULL;
103100  }else{
103101    assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
103102    c = (u16)(WO_EQ<<(op-TK_EQ));
103103  }
103104  assert( op!=TK_ISNULL || c==WO_ISNULL );
103105  assert( op!=TK_IN || c==WO_IN );
103106  assert( op!=TK_EQ || c==WO_EQ );
103107  assert( op!=TK_LT || c==WO_LT );
103108  assert( op!=TK_LE || c==WO_LE );
103109  assert( op!=TK_GT || c==WO_GT );
103110  assert( op!=TK_GE || c==WO_GE );
103111  return c;
103112}
103113
103114/*
103115** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
103116** where X is a reference to the iColumn of table iCur and <op> is one of
103117** the WO_xx operator codes specified by the op parameter.
103118** Return a pointer to the term.  Return 0 if not found.
103119*/
103120static WhereTerm *findTerm(
103121  WhereClause *pWC,     /* The WHERE clause to be searched */
103122  int iCur,             /* Cursor number of LHS */
103123  int iColumn,          /* Column number of LHS */
103124  Bitmask notReady,     /* RHS must not overlap with this mask */
103125  u32 op,               /* Mask of WO_xx values describing operator */
103126  Index *pIdx           /* Must be compatible with this index, if not NULL */
103127){
103128  WhereTerm *pTerm;
103129  int k;
103130  assert( iCur>=0 );
103131  op &= WO_ALL;
103132  for(; pWC; pWC=pWC->pOuter){
103133    for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
103134      if( pTerm->leftCursor==iCur
103135         && (pTerm->prereqRight & notReady)==0
103136         && pTerm->u.leftColumn==iColumn
103137         && (pTerm->eOperator & op)!=0
103138      ){
103139        if( iColumn>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){
103140          Expr *pX = pTerm->pExpr;
103141          CollSeq *pColl;
103142          char idxaff;
103143          int j;
103144          Parse *pParse = pWC->pParse;
103145
103146          idxaff = pIdx->pTable->aCol[iColumn].affinity;
103147          if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
103148
103149          /* Figure out the collation sequence required from an index for
103150          ** it to be useful for optimising expression pX. Store this
103151          ** value in variable pColl.
103152          */
103153          assert(pX->pLeft);
103154          pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
103155          assert(pColl || pParse->nErr);
103156
103157          for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
103158            if( NEVER(j>=pIdx->nColumn) ) return 0;
103159          }
103160          if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
103161        }
103162        return pTerm;
103163      }
103164    }
103165  }
103166  return 0;
103167}
103168
103169/* Forward reference */
103170static void exprAnalyze(SrcList*, WhereClause*, int);
103171
103172/*
103173** Call exprAnalyze on all terms in a WHERE clause.
103174**
103175**
103176*/
103177static void exprAnalyzeAll(
103178  SrcList *pTabList,       /* the FROM clause */
103179  WhereClause *pWC         /* the WHERE clause to be analyzed */
103180){
103181  int i;
103182  for(i=pWC->nTerm-1; i>=0; i--){
103183    exprAnalyze(pTabList, pWC, i);
103184  }
103185}
103186
103187#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
103188/*
103189** Check to see if the given expression is a LIKE or GLOB operator that
103190** can be optimized using inequality constraints.  Return TRUE if it is
103191** so and false if not.
103192**
103193** In order for the operator to be optimizible, the RHS must be a string
103194** literal that does not begin with a wildcard.
103195*/
103196static int isLikeOrGlob(
103197  Parse *pParse,    /* Parsing and code generating context */
103198  Expr *pExpr,      /* Test this expression */
103199  Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
103200  int *pisComplete, /* True if the only wildcard is % in the last character */
103201  int *pnoCase      /* True if uppercase is equivalent to lowercase */
103202){
103203  const char *z = 0;         /* String on RHS of LIKE operator */
103204  Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
103205  ExprList *pList;           /* List of operands to the LIKE operator */
103206  int c;                     /* One character in z[] */
103207  int cnt;                   /* Number of non-wildcard prefix characters */
103208  char wc[3];                /* Wildcard characters */
103209  sqlite3 *db = pParse->db;  /* Database connection */
103210  sqlite3_value *pVal = 0;
103211  int op;                    /* Opcode of pRight */
103212
103213  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
103214    return 0;
103215  }
103216#ifdef SQLITE_EBCDIC
103217  if( *pnoCase ) return 0;
103218#endif
103219  pList = pExpr->x.pList;
103220  pLeft = pList->a[1].pExpr;
103221  if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
103222    /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
103223    ** be the name of an indexed column with TEXT affinity. */
103224    return 0;
103225  }
103226  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
103227
103228  pRight = pList->a[0].pExpr;
103229  op = pRight->op;
103230  if( op==TK_REGISTER ){
103231    op = pRight->op2;
103232  }
103233  if( op==TK_VARIABLE ){
103234    Vdbe *pReprepare = pParse->pReprepare;
103235    int iCol = pRight->iColumn;
103236    pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
103237    if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
103238      z = (char *)sqlite3_value_text(pVal);
103239    }
103240    sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
103241    assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
103242  }else if( op==TK_STRING ){
103243    z = pRight->u.zToken;
103244  }
103245  if( z ){
103246    cnt = 0;
103247    while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
103248      cnt++;
103249    }
103250    if( cnt!=0 && 255!=(u8)z[cnt-1] ){
103251      Expr *pPrefix;
103252      *pisComplete = c==wc[0] && z[cnt+1]==0;
103253      pPrefix = sqlite3Expr(db, TK_STRING, z);
103254      if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
103255      *ppPrefix = pPrefix;
103256      if( op==TK_VARIABLE ){
103257        Vdbe *v = pParse->pVdbe;
103258        sqlite3VdbeSetVarmask(v, pRight->iColumn);
103259        if( *pisComplete && pRight->u.zToken[1] ){
103260          /* If the rhs of the LIKE expression is a variable, and the current
103261          ** value of the variable means there is no need to invoke the LIKE
103262          ** function, then no OP_Variable will be added to the program.
103263          ** This causes problems for the sqlite3_bind_parameter_name()
103264          ** API. To workaround them, add a dummy OP_Variable here.
103265          */
103266          int r1 = sqlite3GetTempReg(pParse);
103267          sqlite3ExprCodeTarget(pParse, pRight, r1);
103268          sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
103269          sqlite3ReleaseTempReg(pParse, r1);
103270        }
103271      }
103272    }else{
103273      z = 0;
103274    }
103275  }
103276
103277  sqlite3ValueFree(pVal);
103278  return (z!=0);
103279}
103280#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
103281
103282
103283#ifndef SQLITE_OMIT_VIRTUALTABLE
103284/*
103285** Check to see if the given expression is of the form
103286**
103287**         column MATCH expr
103288**
103289** If it is then return TRUE.  If not, return FALSE.
103290*/
103291static int isMatchOfColumn(
103292  Expr *pExpr      /* Test this expression */
103293){
103294  ExprList *pList;
103295
103296  if( pExpr->op!=TK_FUNCTION ){
103297    return 0;
103298  }
103299  if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
103300    return 0;
103301  }
103302  pList = pExpr->x.pList;
103303  if( pList->nExpr!=2 ){
103304    return 0;
103305  }
103306  if( pList->a[1].pExpr->op != TK_COLUMN ){
103307    return 0;
103308  }
103309  return 1;
103310}
103311#endif /* SQLITE_OMIT_VIRTUALTABLE */
103312
103313/*
103314** If the pBase expression originated in the ON or USING clause of
103315** a join, then transfer the appropriate markings over to derived.
103316*/
103317static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
103318  pDerived->flags |= pBase->flags & EP_FromJoin;
103319  pDerived->iRightJoinTable = pBase->iRightJoinTable;
103320}
103321
103322#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
103323/*
103324** Analyze a term that consists of two or more OR-connected
103325** subterms.  So in:
103326**
103327**     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
103328**                          ^^^^^^^^^^^^^^^^^^^^
103329**
103330** This routine analyzes terms such as the middle term in the above example.
103331** A WhereOrTerm object is computed and attached to the term under
103332** analysis, regardless of the outcome of the analysis.  Hence:
103333**
103334**     WhereTerm.wtFlags   |=  TERM_ORINFO
103335**     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
103336**
103337** The term being analyzed must have two or more of OR-connected subterms.
103338** A single subterm might be a set of AND-connected sub-subterms.
103339** Examples of terms under analysis:
103340**
103341**     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
103342**     (B)     x=expr1 OR expr2=x OR x=expr3
103343**     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
103344**     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
103345**     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
103346**
103347** CASE 1:
103348**
103349** If all subterms are of the form T.C=expr for some single column of C
103350** a single table T (as shown in example B above) then create a new virtual
103351** term that is an equivalent IN expression.  In other words, if the term
103352** being analyzed is:
103353**
103354**      x = expr1  OR  expr2 = x  OR  x = expr3
103355**
103356** then create a new virtual term like this:
103357**
103358**      x IN (expr1,expr2,expr3)
103359**
103360** CASE 2:
103361**
103362** If all subterms are indexable by a single table T, then set
103363**
103364**     WhereTerm.eOperator              =  WO_OR
103365**     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
103366**
103367** A subterm is "indexable" if it is of the form
103368** "T.C <op> <expr>" where C is any column of table T and
103369** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
103370** A subterm is also indexable if it is an AND of two or more
103371** subsubterms at least one of which is indexable.  Indexable AND
103372** subterms have their eOperator set to WO_AND and they have
103373** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
103374**
103375** From another point of view, "indexable" means that the subterm could
103376** potentially be used with an index if an appropriate index exists.
103377** This analysis does not consider whether or not the index exists; that
103378** is something the bestIndex() routine will determine.  This analysis
103379** only looks at whether subterms appropriate for indexing exist.
103380**
103381** All examples A through E above all satisfy case 2.  But if a term
103382** also statisfies case 1 (such as B) we know that the optimizer will
103383** always prefer case 1, so in that case we pretend that case 2 is not
103384** satisfied.
103385**
103386** It might be the case that multiple tables are indexable.  For example,
103387** (E) above is indexable on tables P, Q, and R.
103388**
103389** Terms that satisfy case 2 are candidates for lookup by using
103390** separate indices to find rowids for each subterm and composing
103391** the union of all rowids using a RowSet object.  This is similar
103392** to "bitmap indices" in other database engines.
103393**
103394** OTHERWISE:
103395**
103396** If neither case 1 nor case 2 apply, then leave the eOperator set to
103397** zero.  This term is not useful for search.
103398*/
103399static void exprAnalyzeOrTerm(
103400  SrcList *pSrc,            /* the FROM clause */
103401  WhereClause *pWC,         /* the complete WHERE clause */
103402  int idxTerm               /* Index of the OR-term to be analyzed */
103403){
103404  Parse *pParse = pWC->pParse;            /* Parser context */
103405  sqlite3 *db = pParse->db;               /* Database connection */
103406  WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
103407  Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
103408  WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
103409  int i;                                  /* Loop counters */
103410  WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
103411  WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
103412  WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
103413  Bitmask chngToIN;         /* Tables that might satisfy case 1 */
103414  Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
103415
103416  /*
103417  ** Break the OR clause into its separate subterms.  The subterms are
103418  ** stored in a WhereClause structure containing within the WhereOrInfo
103419  ** object that is attached to the original OR clause term.
103420  */
103421  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
103422  assert( pExpr->op==TK_OR );
103423  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
103424  if( pOrInfo==0 ) return;
103425  pTerm->wtFlags |= TERM_ORINFO;
103426  pOrWc = &pOrInfo->wc;
103427  whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103428  whereSplit(pOrWc, pExpr, TK_OR);
103429  exprAnalyzeAll(pSrc, pOrWc);
103430  if( db->mallocFailed ) return;
103431  assert( pOrWc->nTerm>=2 );
103432
103433  /*
103434  ** Compute the set of tables that might satisfy cases 1 or 2.
103435  */
103436  indexable = ~(Bitmask)0;
103437  chngToIN = ~(pWC->vmask);
103438  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
103439    if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
103440      WhereAndInfo *pAndInfo;
103441      assert( pOrTerm->eOperator==0 );
103442      assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
103443      chngToIN = 0;
103444      pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
103445      if( pAndInfo ){
103446        WhereClause *pAndWC;
103447        WhereTerm *pAndTerm;
103448        int j;
103449        Bitmask b = 0;
103450        pOrTerm->u.pAndInfo = pAndInfo;
103451        pOrTerm->wtFlags |= TERM_ANDINFO;
103452        pOrTerm->eOperator = WO_AND;
103453        pAndWC = &pAndInfo->wc;
103454        whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
103455        whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
103456        exprAnalyzeAll(pSrc, pAndWC);
103457        pAndWC->pOuter = pWC;
103458        testcase( db->mallocFailed );
103459        if( !db->mallocFailed ){
103460          for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
103461            assert( pAndTerm->pExpr );
103462            if( allowedOp(pAndTerm->pExpr->op) ){
103463              b |= getMask(pMaskSet, pAndTerm->leftCursor);
103464            }
103465          }
103466        }
103467        indexable &= b;
103468      }
103469    }else if( pOrTerm->wtFlags & TERM_COPIED ){
103470      /* Skip this term for now.  We revisit it when we process the
103471      ** corresponding TERM_VIRTUAL term */
103472    }else{
103473      Bitmask b;
103474      b = getMask(pMaskSet, pOrTerm->leftCursor);
103475      if( pOrTerm->wtFlags & TERM_VIRTUAL ){
103476        WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
103477        b |= getMask(pMaskSet, pOther->leftCursor);
103478      }
103479      indexable &= b;
103480      if( pOrTerm->eOperator!=WO_EQ ){
103481        chngToIN = 0;
103482      }else{
103483        chngToIN &= b;
103484      }
103485    }
103486  }
103487
103488  /*
103489  ** Record the set of tables that satisfy case 2.  The set might be
103490  ** empty.
103491  */
103492  pOrInfo->indexable = indexable;
103493  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
103494
103495  /*
103496  ** chngToIN holds a set of tables that *might* satisfy case 1.  But
103497  ** we have to do some additional checking to see if case 1 really
103498  ** is satisfied.
103499  **
103500  ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
103501  ** that there is no possibility of transforming the OR clause into an
103502  ** IN operator because one or more terms in the OR clause contain
103503  ** something other than == on a column in the single table.  The 1-bit
103504  ** case means that every term of the OR clause is of the form
103505  ** "table.column=expr" for some single table.  The one bit that is set
103506  ** will correspond to the common table.  We still need to check to make
103507  ** sure the same column is used on all terms.  The 2-bit case is when
103508  ** the all terms are of the form "table1.column=table2.column".  It
103509  ** might be possible to form an IN operator with either table1.column
103510  ** or table2.column as the LHS if either is common to every term of
103511  ** the OR clause.
103512  **
103513  ** Note that terms of the form "table.column1=table.column2" (the
103514  ** same table on both sizes of the ==) cannot be optimized.
103515  */
103516  if( chngToIN ){
103517    int okToChngToIN = 0;     /* True if the conversion to IN is valid */
103518    int iColumn = -1;         /* Column index on lhs of IN operator */
103519    int iCursor = -1;         /* Table cursor common to all terms */
103520    int j = 0;                /* Loop counter */
103521
103522    /* Search for a table and column that appears on one side or the
103523    ** other of the == operator in every subterm.  That table and column
103524    ** will be recorded in iCursor and iColumn.  There might not be any
103525    ** such table and column.  Set okToChngToIN if an appropriate table
103526    ** and column is found but leave okToChngToIN false if not found.
103527    */
103528    for(j=0; j<2 && !okToChngToIN; j++){
103529      pOrTerm = pOrWc->a;
103530      for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
103531        assert( pOrTerm->eOperator==WO_EQ );
103532        pOrTerm->wtFlags &= ~TERM_OR_OK;
103533        if( pOrTerm->leftCursor==iCursor ){
103534          /* This is the 2-bit case and we are on the second iteration and
103535          ** current term is from the first iteration.  So skip this term. */
103536          assert( j==1 );
103537          continue;
103538        }
103539        if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
103540          /* This term must be of the form t1.a==t2.b where t2 is in the
103541          ** chngToIN set but t1 is not.  This term will be either preceeded
103542          ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term
103543          ** and use its inversion. */
103544          testcase( pOrTerm->wtFlags & TERM_COPIED );
103545          testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
103546          assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
103547          continue;
103548        }
103549        iColumn = pOrTerm->u.leftColumn;
103550        iCursor = pOrTerm->leftCursor;
103551        break;
103552      }
103553      if( i<0 ){
103554        /* No candidate table+column was found.  This can only occur
103555        ** on the second iteration */
103556        assert( j==1 );
103557        assert( (chngToIN&(chngToIN-1))==0 );
103558        assert( chngToIN==getMask(pMaskSet, iCursor) );
103559        break;
103560      }
103561      testcase( j==1 );
103562
103563      /* We have found a candidate table and column.  Check to see if that
103564      ** table and column is common to every term in the OR clause */
103565      okToChngToIN = 1;
103566      for(; i>=0 && okToChngToIN; i--, pOrTerm++){
103567        assert( pOrTerm->eOperator==WO_EQ );
103568        if( pOrTerm->leftCursor!=iCursor ){
103569          pOrTerm->wtFlags &= ~TERM_OR_OK;
103570        }else if( pOrTerm->u.leftColumn!=iColumn ){
103571          okToChngToIN = 0;
103572        }else{
103573          int affLeft, affRight;
103574          /* If the right-hand side is also a column, then the affinities
103575          ** of both right and left sides must be such that no type
103576          ** conversions are required on the right.  (Ticket #2249)
103577          */
103578          affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
103579          affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
103580          if( affRight!=0 && affRight!=affLeft ){
103581            okToChngToIN = 0;
103582          }else{
103583            pOrTerm->wtFlags |= TERM_OR_OK;
103584          }
103585        }
103586      }
103587    }
103588
103589    /* At this point, okToChngToIN is true if original pTerm satisfies
103590    ** case 1.  In that case, construct a new virtual term that is
103591    ** pTerm converted into an IN operator.
103592    **
103593    ** EV: R-00211-15100
103594    */
103595    if( okToChngToIN ){
103596      Expr *pDup;            /* A transient duplicate expression */
103597      ExprList *pList = 0;   /* The RHS of the IN operator */
103598      Expr *pLeft = 0;       /* The LHS of the IN operator */
103599      Expr *pNew;            /* The complete IN operator */
103600
103601      for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
103602        if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
103603        assert( pOrTerm->eOperator==WO_EQ );
103604        assert( pOrTerm->leftCursor==iCursor );
103605        assert( pOrTerm->u.leftColumn==iColumn );
103606        pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
103607        pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
103608        pLeft = pOrTerm->pExpr->pLeft;
103609      }
103610      assert( pLeft!=0 );
103611      pDup = sqlite3ExprDup(db, pLeft, 0);
103612      pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
103613      if( pNew ){
103614        int idxNew;
103615        transferJoinMarkings(pNew, pExpr);
103616        assert( !ExprHasProperty(pNew, EP_xIsSelect) );
103617        pNew->x.pList = pList;
103618        idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
103619        testcase( idxNew==0 );
103620        exprAnalyze(pSrc, pWC, idxNew);
103621        pTerm = &pWC->a[idxTerm];
103622        pWC->a[idxNew].iParent = idxTerm;
103623        pTerm->nChild = 1;
103624      }else{
103625        sqlite3ExprListDelete(db, pList);
103626      }
103627      pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
103628    }
103629  }
103630}
103631#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
103632
103633
103634/*
103635** The input to this routine is an WhereTerm structure with only the
103636** "pExpr" field filled in.  The job of this routine is to analyze the
103637** subexpression and populate all the other fields of the WhereTerm
103638** structure.
103639**
103640** If the expression is of the form "<expr> <op> X" it gets commuted
103641** to the standard form of "X <op> <expr>".
103642**
103643** If the expression is of the form "X <op> Y" where both X and Y are
103644** columns, then the original expression is unchanged and a new virtual
103645** term of the form "Y <op> X" is added to the WHERE clause and
103646** analyzed separately.  The original term is marked with TERM_COPIED
103647** and the new term is marked with TERM_DYNAMIC (because it's pExpr
103648** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
103649** is a commuted copy of a prior term.)  The original term has nChild=1
103650** and the copy has idxParent set to the index of the original term.
103651*/
103652static void exprAnalyze(
103653  SrcList *pSrc,            /* the FROM clause */
103654  WhereClause *pWC,         /* the WHERE clause */
103655  int idxTerm               /* Index of the term to be analyzed */
103656){
103657  WhereTerm *pTerm;                /* The term to be analyzed */
103658  WhereMaskSet *pMaskSet;          /* Set of table index masks */
103659  Expr *pExpr;                     /* The expression to be analyzed */
103660  Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
103661  Bitmask prereqAll;               /* Prerequesites of pExpr */
103662  Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
103663  Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
103664  int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
103665  int noCase = 0;                  /* LIKE/GLOB distinguishes case */
103666  int op;                          /* Top-level operator.  pExpr->op */
103667  Parse *pParse = pWC->pParse;     /* Parsing context */
103668  sqlite3 *db = pParse->db;        /* Database connection */
103669
103670  if( db->mallocFailed ){
103671    return;
103672  }
103673  pTerm = &pWC->a[idxTerm];
103674  pMaskSet = pWC->pMaskSet;
103675  pExpr = pTerm->pExpr;
103676  prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
103677  op = pExpr->op;
103678  if( op==TK_IN ){
103679    assert( pExpr->pRight==0 );
103680    if( ExprHasProperty(pExpr, EP_xIsSelect) ){
103681      pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
103682    }else{
103683      pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
103684    }
103685  }else if( op==TK_ISNULL ){
103686    pTerm->prereqRight = 0;
103687  }else{
103688    pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
103689  }
103690  prereqAll = exprTableUsage(pMaskSet, pExpr);
103691  if( ExprHasProperty(pExpr, EP_FromJoin) ){
103692    Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
103693    prereqAll |= x;
103694    extraRight = x-1;  /* ON clause terms may not be used with an index
103695                       ** on left table of a LEFT JOIN.  Ticket #3015 */
103696  }
103697  pTerm->prereqAll = prereqAll;
103698  pTerm->leftCursor = -1;
103699  pTerm->iParent = -1;
103700  pTerm->eOperator = 0;
103701  if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
103702    Expr *pLeft = pExpr->pLeft;
103703    Expr *pRight = pExpr->pRight;
103704    if( pLeft->op==TK_COLUMN ){
103705      pTerm->leftCursor = pLeft->iTable;
103706      pTerm->u.leftColumn = pLeft->iColumn;
103707      pTerm->eOperator = operatorMask(op);
103708    }
103709    if( pRight && pRight->op==TK_COLUMN ){
103710      WhereTerm *pNew;
103711      Expr *pDup;
103712      if( pTerm->leftCursor>=0 ){
103713        int idxNew;
103714        pDup = sqlite3ExprDup(db, pExpr, 0);
103715        if( db->mallocFailed ){
103716          sqlite3ExprDelete(db, pDup);
103717          return;
103718        }
103719        idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
103720        if( idxNew==0 ) return;
103721        pNew = &pWC->a[idxNew];
103722        pNew->iParent = idxTerm;
103723        pTerm = &pWC->a[idxTerm];
103724        pTerm->nChild = 1;
103725        pTerm->wtFlags |= TERM_COPIED;
103726      }else{
103727        pDup = pExpr;
103728        pNew = pTerm;
103729      }
103730      exprCommute(pParse, pDup);
103731      pLeft = pDup->pLeft;
103732      pNew->leftCursor = pLeft->iTable;
103733      pNew->u.leftColumn = pLeft->iColumn;
103734      testcase( (prereqLeft | extraRight) != prereqLeft );
103735      pNew->prereqRight = prereqLeft | extraRight;
103736      pNew->prereqAll = prereqAll;
103737      pNew->eOperator = operatorMask(pDup->op);
103738    }
103739  }
103740
103741#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
103742  /* If a term is the BETWEEN operator, create two new virtual terms
103743  ** that define the range that the BETWEEN implements.  For example:
103744  **
103745  **      a BETWEEN b AND c
103746  **
103747  ** is converted into:
103748  **
103749  **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
103750  **
103751  ** The two new terms are added onto the end of the WhereClause object.
103752  ** The new terms are "dynamic" and are children of the original BETWEEN
103753  ** term.  That means that if the BETWEEN term is coded, the children are
103754  ** skipped.  Or, if the children are satisfied by an index, the original
103755  ** BETWEEN term is skipped.
103756  */
103757  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
103758    ExprList *pList = pExpr->x.pList;
103759    int i;
103760    static const u8 ops[] = {TK_GE, TK_LE};
103761    assert( pList!=0 );
103762    assert( pList->nExpr==2 );
103763    for(i=0; i<2; i++){
103764      Expr *pNewExpr;
103765      int idxNew;
103766      pNewExpr = sqlite3PExpr(pParse, ops[i],
103767                             sqlite3ExprDup(db, pExpr->pLeft, 0),
103768                             sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
103769      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103770      testcase( idxNew==0 );
103771      exprAnalyze(pSrc, pWC, idxNew);
103772      pTerm = &pWC->a[idxTerm];
103773      pWC->a[idxNew].iParent = idxTerm;
103774    }
103775    pTerm->nChild = 2;
103776  }
103777#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
103778
103779#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
103780  /* Analyze a term that is composed of two or more subterms connected by
103781  ** an OR operator.
103782  */
103783  else if( pExpr->op==TK_OR ){
103784    assert( pWC->op==TK_AND );
103785    exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
103786    pTerm = &pWC->a[idxTerm];
103787  }
103788#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
103789
103790#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
103791  /* Add constraints to reduce the search space on a LIKE or GLOB
103792  ** operator.
103793  **
103794  ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
103795  **
103796  **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
103797  **
103798  ** The last character of the prefix "abc" is incremented to form the
103799  ** termination condition "abd".
103800  */
103801  if( pWC->op==TK_AND
103802   && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
103803  ){
103804    Expr *pLeft;       /* LHS of LIKE/GLOB operator */
103805    Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
103806    Expr *pNewExpr1;
103807    Expr *pNewExpr2;
103808    int idxNew1;
103809    int idxNew2;
103810    CollSeq *pColl;    /* Collating sequence to use */
103811
103812    pLeft = pExpr->x.pList->a[1].pExpr;
103813    pStr2 = sqlite3ExprDup(db, pStr1, 0);
103814    if( !db->mallocFailed ){
103815      u8 c, *pC;       /* Last character before the first wildcard */
103816      pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
103817      c = *pC;
103818      if( noCase ){
103819        /* The point is to increment the last character before the first
103820        ** wildcard.  But if we increment '@', that will push it into the
103821        ** alphabetic range where case conversions will mess up the
103822        ** inequality.  To avoid this, make sure to also run the full
103823        ** LIKE on all candidate expressions by clearing the isComplete flag
103824        */
103825        if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
103826
103827
103828        c = sqlite3UpperToLower[c];
103829      }
103830      *pC = c + 1;
103831    }
103832    pColl = sqlite3FindCollSeq(db, SQLITE_UTF8, noCase ? "NOCASE" : "BINARY",0);
103833    pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
103834                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
103835                     pStr1, 0);
103836    idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
103837    testcase( idxNew1==0 );
103838    exprAnalyze(pSrc, pWC, idxNew1);
103839    pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
103840                     sqlite3ExprSetColl(sqlite3ExprDup(db,pLeft,0), pColl),
103841                     pStr2, 0);
103842    idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
103843    testcase( idxNew2==0 );
103844    exprAnalyze(pSrc, pWC, idxNew2);
103845    pTerm = &pWC->a[idxTerm];
103846    if( isComplete ){
103847      pWC->a[idxNew1].iParent = idxTerm;
103848      pWC->a[idxNew2].iParent = idxTerm;
103849      pTerm->nChild = 2;
103850    }
103851  }
103852#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
103853
103854#ifndef SQLITE_OMIT_VIRTUALTABLE
103855  /* Add a WO_MATCH auxiliary term to the constraint set if the
103856  ** current expression is of the form:  column MATCH expr.
103857  ** This information is used by the xBestIndex methods of
103858  ** virtual tables.  The native query optimizer does not attempt
103859  ** to do anything with MATCH functions.
103860  */
103861  if( isMatchOfColumn(pExpr) ){
103862    int idxNew;
103863    Expr *pRight, *pLeft;
103864    WhereTerm *pNewTerm;
103865    Bitmask prereqColumn, prereqExpr;
103866
103867    pRight = pExpr->x.pList->a[0].pExpr;
103868    pLeft = pExpr->x.pList->a[1].pExpr;
103869    prereqExpr = exprTableUsage(pMaskSet, pRight);
103870    prereqColumn = exprTableUsage(pMaskSet, pLeft);
103871    if( (prereqExpr & prereqColumn)==0 ){
103872      Expr *pNewExpr;
103873      pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
103874                              0, sqlite3ExprDup(db, pRight, 0), 0);
103875      idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
103876      testcase( idxNew==0 );
103877      pNewTerm = &pWC->a[idxNew];
103878      pNewTerm->prereqRight = prereqExpr;
103879      pNewTerm->leftCursor = pLeft->iTable;
103880      pNewTerm->u.leftColumn = pLeft->iColumn;
103881      pNewTerm->eOperator = WO_MATCH;
103882      pNewTerm->iParent = idxTerm;
103883      pTerm = &pWC->a[idxTerm];
103884      pTerm->nChild = 1;
103885      pTerm->wtFlags |= TERM_COPIED;
103886      pNewTerm->prereqAll = pTerm->prereqAll;
103887    }
103888  }
103889#endif /* SQLITE_OMIT_VIRTUALTABLE */
103890
103891#ifdef SQLITE_ENABLE_STAT3
103892  /* When sqlite_stat3 histogram data is available an operator of the
103893  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
103894  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
103895  ** virtual term of that form.
103896  **
103897  ** Note that the virtual term must be tagged with TERM_VNULL.  This
103898  ** TERM_VNULL tag will suppress the not-null check at the beginning
103899  ** of the loop.  Without the TERM_VNULL flag, the not-null check at
103900  ** the start of the loop will prevent any results from being returned.
103901  */
103902  if( pExpr->op==TK_NOTNULL
103903   && pExpr->pLeft->op==TK_COLUMN
103904   && pExpr->pLeft->iColumn>=0
103905  ){
103906    Expr *pNewExpr;
103907    Expr *pLeft = pExpr->pLeft;
103908    int idxNew;
103909    WhereTerm *pNewTerm;
103910
103911    pNewExpr = sqlite3PExpr(pParse, TK_GT,
103912                            sqlite3ExprDup(db, pLeft, 0),
103913                            sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
103914
103915    idxNew = whereClauseInsert(pWC, pNewExpr,
103916                              TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
103917    if( idxNew ){
103918      pNewTerm = &pWC->a[idxNew];
103919      pNewTerm->prereqRight = 0;
103920      pNewTerm->leftCursor = pLeft->iTable;
103921      pNewTerm->u.leftColumn = pLeft->iColumn;
103922      pNewTerm->eOperator = WO_GT;
103923      pNewTerm->iParent = idxTerm;
103924      pTerm = &pWC->a[idxTerm];
103925      pTerm->nChild = 1;
103926      pTerm->wtFlags |= TERM_COPIED;
103927      pNewTerm->prereqAll = pTerm->prereqAll;
103928    }
103929  }
103930#endif /* SQLITE_ENABLE_STAT */
103931
103932  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
103933  ** an index for tables to the left of the join.
103934  */
103935  pTerm->prereqRight |= extraRight;
103936}
103937
103938/*
103939** Return TRUE if any of the expressions in pList->a[iFirst...] contain
103940** a reference to any table other than the iBase table.
103941*/
103942static int referencesOtherTables(
103943  ExprList *pList,          /* Search expressions in ths list */
103944  WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
103945  int iFirst,               /* Be searching with the iFirst-th expression */
103946  int iBase                 /* Ignore references to this table */
103947){
103948  Bitmask allowed = ~getMask(pMaskSet, iBase);
103949  while( iFirst<pList->nExpr ){
103950    if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
103951      return 1;
103952    }
103953  }
103954  return 0;
103955}
103956
103957/*
103958** This function searches the expression list passed as the second argument
103959** for an expression of type TK_COLUMN that refers to the same column and
103960** uses the same collation sequence as the iCol'th column of index pIdx.
103961** Argument iBase is the cursor number used for the table that pIdx refers
103962** to.
103963**
103964** If such an expression is found, its index in pList->a[] is returned. If
103965** no expression is found, -1 is returned.
103966*/
103967static int findIndexCol(
103968  Parse *pParse,                  /* Parse context */
103969  ExprList *pList,                /* Expression list to search */
103970  int iBase,                      /* Cursor for table associated with pIdx */
103971  Index *pIdx,                    /* Index to match column of */
103972  int iCol                        /* Column of index to match */
103973){
103974  int i;
103975  const char *zColl = pIdx->azColl[iCol];
103976
103977  for(i=0; i<pList->nExpr; i++){
103978    Expr *p = pList->a[i].pExpr;
103979    if( p->op==TK_COLUMN
103980     && p->iColumn==pIdx->aiColumn[iCol]
103981     && p->iTable==iBase
103982    ){
103983      CollSeq *pColl = sqlite3ExprCollSeq(pParse, p);
103984      if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
103985        return i;
103986      }
103987    }
103988  }
103989
103990  return -1;
103991}
103992
103993/*
103994** This routine determines if pIdx can be used to assist in processing a
103995** DISTINCT qualifier. In other words, it tests whether or not using this
103996** index for the outer loop guarantees that rows with equal values for
103997** all expressions in the pDistinct list are delivered grouped together.
103998**
103999** For example, the query
104000**
104001**   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
104002**
104003** can benefit from any index on columns "b" and "c".
104004*/
104005static int isDistinctIndex(
104006  Parse *pParse,                  /* Parsing context */
104007  WhereClause *pWC,               /* The WHERE clause */
104008  Index *pIdx,                    /* The index being considered */
104009  int base,                       /* Cursor number for the table pIdx is on */
104010  ExprList *pDistinct,            /* The DISTINCT expressions */
104011  int nEqCol                      /* Number of index columns with == */
104012){
104013  Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
104014  int i;                          /* Iterator variable */
104015
104016  if( pIdx->zName==0 || pDistinct==0 || pDistinct->nExpr>=BMS ) return 0;
104017  testcase( pDistinct->nExpr==BMS-1 );
104018
104019  /* Loop through all the expressions in the distinct list. If any of them
104020  ** are not simple column references, return early. Otherwise, test if the
104021  ** WHERE clause contains a "col=X" clause. If it does, the expression
104022  ** can be ignored. If it does not, and the column does not belong to the
104023  ** same table as index pIdx, return early. Finally, if there is no
104024  ** matching "col=X" expression and the column is on the same table as pIdx,
104025  ** set the corresponding bit in variable mask.
104026  */
104027  for(i=0; i<pDistinct->nExpr; i++){
104028    WhereTerm *pTerm;
104029    Expr *p = pDistinct->a[i].pExpr;
104030    if( p->op!=TK_COLUMN ) return 0;
104031    pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
104032    if( pTerm ){
104033      Expr *pX = pTerm->pExpr;
104034      CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104035      CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
104036      if( p1==p2 ) continue;
104037    }
104038    if( p->iTable!=base ) return 0;
104039    mask |= (((Bitmask)1) << i);
104040  }
104041
104042  for(i=nEqCol; mask && i<pIdx->nColumn; i++){
104043    int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
104044    if( iExpr<0 ) break;
104045    mask &= ~(((Bitmask)1) << iExpr);
104046  }
104047
104048  return (mask==0);
104049}
104050
104051
104052/*
104053** Return true if the DISTINCT expression-list passed as the third argument
104054** is redundant. A DISTINCT list is redundant if the database contains a
104055** UNIQUE index that guarantees that the result of the query will be distinct
104056** anyway.
104057*/
104058static int isDistinctRedundant(
104059  Parse *pParse,
104060  SrcList *pTabList,
104061  WhereClause *pWC,
104062  ExprList *pDistinct
104063){
104064  Table *pTab;
104065  Index *pIdx;
104066  int i;
104067  int iBase;
104068
104069  /* If there is more than one table or sub-select in the FROM clause of
104070  ** this query, then it will not be possible to show that the DISTINCT
104071  ** clause is redundant. */
104072  if( pTabList->nSrc!=1 ) return 0;
104073  iBase = pTabList->a[0].iCursor;
104074  pTab = pTabList->a[0].pTab;
104075
104076  /* If any of the expressions is an IPK column on table iBase, then return
104077  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
104078  ** current SELECT is a correlated sub-query.
104079  */
104080  for(i=0; i<pDistinct->nExpr; i++){
104081    Expr *p = pDistinct->a[i].pExpr;
104082    if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
104083  }
104084
104085  /* Loop through all indices on the table, checking each to see if it makes
104086  ** the DISTINCT qualifier redundant. It does so if:
104087  **
104088  **   1. The index is itself UNIQUE, and
104089  **
104090  **   2. All of the columns in the index are either part of the pDistinct
104091  **      list, or else the WHERE clause contains a term of the form "col=X",
104092  **      where X is a constant value. The collation sequences of the
104093  **      comparison and select-list expressions must match those of the index.
104094  */
104095  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104096    if( pIdx->onError==OE_None ) continue;
104097    for(i=0; i<pIdx->nColumn; i++){
104098      int iCol = pIdx->aiColumn[i];
104099      if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx)
104100       && 0>findIndexCol(pParse, pDistinct, iBase, pIdx, i)
104101      ){
104102        break;
104103      }
104104    }
104105    if( i==pIdx->nColumn ){
104106      /* This index implies that the DISTINCT qualifier is redundant. */
104107      return 1;
104108    }
104109  }
104110
104111  return 0;
104112}
104113
104114/*
104115** This routine decides if pIdx can be used to satisfy the ORDER BY
104116** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
104117** ORDER BY clause, this routine returns 0.
104118**
104119** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
104120** left-most table in the FROM clause of that same SELECT statement and
104121** the table has a cursor number of "base".  pIdx is an index on pTab.
104122**
104123** nEqCol is the number of columns of pIdx that are used as equality
104124** constraints.  Any of these columns may be missing from the ORDER BY
104125** clause and the match can still be a success.
104126**
104127** All terms of the ORDER BY that match against the index must be either
104128** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
104129** index do not need to satisfy this constraint.)  The *pbRev value is
104130** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
104131** the ORDER BY clause is all ASC.
104132*/
104133static int isSortingIndex(
104134  Parse *pParse,          /* Parsing context */
104135  WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
104136  Index *pIdx,            /* The index we are testing */
104137  int base,               /* Cursor number for the table to be sorted */
104138  ExprList *pOrderBy,     /* The ORDER BY clause */
104139  int nEqCol,             /* Number of index columns with == constraints */
104140  int wsFlags,            /* Index usages flags */
104141  int *pbRev              /* Set to 1 if ORDER BY is DESC */
104142){
104143  int i, j;                       /* Loop counters */
104144  int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
104145  int nTerm;                      /* Number of ORDER BY terms */
104146  struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
104147  sqlite3 *db = pParse->db;
104148
104149  if( !pOrderBy ) return 0;
104150  if( wsFlags & WHERE_COLUMN_IN ) return 0;
104151  if( pIdx->bUnordered ) return 0;
104152
104153  nTerm = pOrderBy->nExpr;
104154  assert( nTerm>0 );
104155
104156  /* Argument pIdx must either point to a 'real' named index structure,
104157  ** or an index structure allocated on the stack by bestBtreeIndex() to
104158  ** represent the rowid index that is part of every table.  */
104159  assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
104160
104161  /* Match terms of the ORDER BY clause against columns of
104162  ** the index.
104163  **
104164  ** Note that indices have pIdx->nColumn regular columns plus
104165  ** one additional column containing the rowid.  The rowid column
104166  ** of the index is also allowed to match against the ORDER BY
104167  ** clause.
104168  */
104169  for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
104170    Expr *pExpr;       /* The expression of the ORDER BY pTerm */
104171    CollSeq *pColl;    /* The collating sequence of pExpr */
104172    int termSortOrder; /* Sort order for this term */
104173    int iColumn;       /* The i-th column of the index.  -1 for rowid */
104174    int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
104175    const char *zColl; /* Name of the collating sequence for i-th index term */
104176
104177    pExpr = pTerm->pExpr;
104178    if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
104179      /* Can not use an index sort on anything that is not a column in the
104180      ** left-most table of the FROM clause */
104181      break;
104182    }
104183    pColl = sqlite3ExprCollSeq(pParse, pExpr);
104184    if( !pColl ){
104185      pColl = db->pDfltColl;
104186    }
104187    if( pIdx->zName && i<pIdx->nColumn ){
104188      iColumn = pIdx->aiColumn[i];
104189      if( iColumn==pIdx->pTable->iPKey ){
104190        iColumn = -1;
104191      }
104192      iSortOrder = pIdx->aSortOrder[i];
104193      zColl = pIdx->azColl[i];
104194    }else{
104195      iColumn = -1;
104196      iSortOrder = 0;
104197      zColl = pColl->zName;
104198    }
104199    if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
104200      /* Term j of the ORDER BY clause does not match column i of the index */
104201      if( i<nEqCol ){
104202        /* If an index column that is constrained by == fails to match an
104203        ** ORDER BY term, that is OK.  Just ignore that column of the index
104204        */
104205        continue;
104206      }else if( i==pIdx->nColumn ){
104207        /* Index column i is the rowid.  All other terms match. */
104208        break;
104209      }else{
104210        /* If an index column fails to match and is not constrained by ==
104211        ** then the index cannot satisfy the ORDER BY constraint.
104212        */
104213        return 0;
104214      }
104215    }
104216    assert( pIdx->aSortOrder!=0 || iColumn==-1 );
104217    assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
104218    assert( iSortOrder==0 || iSortOrder==1 );
104219    termSortOrder = iSortOrder ^ pTerm->sortOrder;
104220    if( i>nEqCol ){
104221      if( termSortOrder!=sortOrder ){
104222        /* Indices can only be used if all ORDER BY terms past the
104223        ** equality constraints are all either DESC or ASC. */
104224        return 0;
104225      }
104226    }else{
104227      sortOrder = termSortOrder;
104228    }
104229    j++;
104230    pTerm++;
104231    if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
104232      /* If the indexed column is the primary key and everything matches
104233      ** so far and none of the ORDER BY terms to the right reference other
104234      ** tables in the join, then we are assured that the index can be used
104235      ** to sort because the primary key is unique and so none of the other
104236      ** columns will make any difference
104237      */
104238      j = nTerm;
104239    }
104240  }
104241
104242  *pbRev = sortOrder!=0;
104243  if( j>=nTerm ){
104244    /* All terms of the ORDER BY clause are covered by this index so
104245    ** this index can be used for sorting. */
104246    return 1;
104247  }
104248  if( pIdx->onError!=OE_None && i==pIdx->nColumn
104249      && (wsFlags & WHERE_COLUMN_NULL)==0
104250      && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
104251    /* All terms of this index match some prefix of the ORDER BY clause
104252    ** and the index is UNIQUE and no terms on the tail of the ORDER BY
104253    ** clause reference other tables in a join.  If this is all true then
104254    ** the order by clause is superfluous.  Not that if the matching
104255    ** condition is IS NULL then the result is not necessarily unique
104256    ** even on a UNIQUE index, so disallow those cases. */
104257    return 1;
104258  }
104259  return 0;
104260}
104261
104262/*
104263** Prepare a crude estimate of the logarithm of the input value.
104264** The results need not be exact.  This is only used for estimating
104265** the total cost of performing operations with O(logN) or O(NlogN)
104266** complexity.  Because N is just a guess, it is no great tragedy if
104267** logN is a little off.
104268*/
104269static double estLog(double N){
104270  double logN = 1;
104271  double x = 10;
104272  while( N>x ){
104273    logN += 1;
104274    x *= 10;
104275  }
104276  return logN;
104277}
104278
104279/*
104280** Two routines for printing the content of an sqlite3_index_info
104281** structure.  Used for testing and debugging only.  If neither
104282** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
104283** are no-ops.
104284*/
104285#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
104286static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
104287  int i;
104288  if( !sqlite3WhereTrace ) return;
104289  for(i=0; i<p->nConstraint; i++){
104290    sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
104291       i,
104292       p->aConstraint[i].iColumn,
104293       p->aConstraint[i].iTermOffset,
104294       p->aConstraint[i].op,
104295       p->aConstraint[i].usable);
104296  }
104297  for(i=0; i<p->nOrderBy; i++){
104298    sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
104299       i,
104300       p->aOrderBy[i].iColumn,
104301       p->aOrderBy[i].desc);
104302  }
104303}
104304static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
104305  int i;
104306  if( !sqlite3WhereTrace ) return;
104307  for(i=0; i<p->nConstraint; i++){
104308    sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
104309       i,
104310       p->aConstraintUsage[i].argvIndex,
104311       p->aConstraintUsage[i].omit);
104312  }
104313  sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
104314  sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
104315  sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
104316  sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
104317}
104318#else
104319#define TRACE_IDX_INPUTS(A)
104320#define TRACE_IDX_OUTPUTS(A)
104321#endif
104322
104323/*
104324** Required because bestIndex() is called by bestOrClauseIndex()
104325*/
104326static void bestIndex(
104327    Parse*, WhereClause*, struct SrcList_item*,
104328    Bitmask, Bitmask, ExprList*, WhereCost*);
104329
104330/*
104331** This routine attempts to find an scanning strategy that can be used
104332** to optimize an 'OR' expression that is part of a WHERE clause.
104333**
104334** The table associated with FROM clause term pSrc may be either a
104335** regular B-Tree table or a virtual table.
104336*/
104337static void bestOrClauseIndex(
104338  Parse *pParse,              /* The parsing context */
104339  WhereClause *pWC,           /* The WHERE clause */
104340  struct SrcList_item *pSrc,  /* The FROM clause term to search */
104341  Bitmask notReady,           /* Mask of cursors not available for indexing */
104342  Bitmask notValid,           /* Cursors not available for any purpose */
104343  ExprList *pOrderBy,         /* The ORDER BY clause */
104344  WhereCost *pCost            /* Lowest cost query plan */
104345){
104346#ifndef SQLITE_OMIT_OR_OPTIMIZATION
104347  const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
104348  const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
104349  WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
104350  WhereTerm *pTerm;                 /* A single term of the WHERE clause */
104351
104352  /* The OR-clause optimization is disallowed if the INDEXED BY or
104353  ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
104354  if( pSrc->notIndexed || pSrc->pIndex!=0 ){
104355    return;
104356  }
104357  if( pWC->wctrlFlags & WHERE_AND_ONLY ){
104358    return;
104359  }
104360
104361  /* Search the WHERE clause terms for a usable WO_OR term. */
104362  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104363    if( pTerm->eOperator==WO_OR
104364     && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
104365     && (pTerm->u.pOrInfo->indexable & maskSrc)!=0
104366    ){
104367      WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
104368      WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
104369      WhereTerm *pOrTerm;
104370      int flags = WHERE_MULTI_OR;
104371      double rTotal = 0;
104372      double nRow = 0;
104373      Bitmask used = 0;
104374
104375      for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
104376        WhereCost sTermCost;
104377        WHERETRACE(("... Multi-index OR testing for term %d of %d....\n",
104378          (pOrTerm - pOrWC->a), (pTerm - pWC->a)
104379        ));
104380        if( pOrTerm->eOperator==WO_AND ){
104381          WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
104382          bestIndex(pParse, pAndWC, pSrc, notReady, notValid, 0, &sTermCost);
104383        }else if( pOrTerm->leftCursor==iCur ){
104384          WhereClause tempWC;
104385          tempWC.pParse = pWC->pParse;
104386          tempWC.pMaskSet = pWC->pMaskSet;
104387          tempWC.pOuter = pWC;
104388          tempWC.op = TK_AND;
104389          tempWC.a = pOrTerm;
104390          tempWC.wctrlFlags = 0;
104391          tempWC.nTerm = 1;
104392          bestIndex(pParse, &tempWC, pSrc, notReady, notValid, 0, &sTermCost);
104393        }else{
104394          continue;
104395        }
104396        rTotal += sTermCost.rCost;
104397        nRow += sTermCost.plan.nRow;
104398        used |= sTermCost.used;
104399        if( rTotal>=pCost->rCost ) break;
104400      }
104401
104402      /* If there is an ORDER BY clause, increase the scan cost to account
104403      ** for the cost of the sort. */
104404      if( pOrderBy!=0 ){
104405        WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
104406                    rTotal, rTotal+nRow*estLog(nRow)));
104407        rTotal += nRow*estLog(nRow);
104408      }
104409
104410      /* If the cost of scanning using this OR term for optimization is
104411      ** less than the current cost stored in pCost, replace the contents
104412      ** of pCost. */
104413      WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
104414      if( rTotal<pCost->rCost ){
104415        pCost->rCost = rTotal;
104416        pCost->used = used;
104417        pCost->plan.nRow = nRow;
104418        pCost->plan.wsFlags = flags;
104419        pCost->plan.u.pTerm = pTerm;
104420      }
104421    }
104422  }
104423#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
104424}
104425
104426#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104427/*
104428** Return TRUE if the WHERE clause term pTerm is of a form where it
104429** could be used with an index to access pSrc, assuming an appropriate
104430** index existed.
104431*/
104432static int termCanDriveIndex(
104433  WhereTerm *pTerm,              /* WHERE clause term to check */
104434  struct SrcList_item *pSrc,     /* Table we are trying to access */
104435  Bitmask notReady               /* Tables in outer loops of the join */
104436){
104437  char aff;
104438  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
104439  if( pTerm->eOperator!=WO_EQ ) return 0;
104440  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
104441  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
104442  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
104443  return 1;
104444}
104445#endif
104446
104447#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104448/*
104449** If the query plan for pSrc specified in pCost is a full table scan
104450** and indexing is allows (if there is no NOT INDEXED clause) and it
104451** possible to construct a transient index that would perform better
104452** than a full table scan even when the cost of constructing the index
104453** is taken into account, then alter the query plan to use the
104454** transient index.
104455*/
104456static void bestAutomaticIndex(
104457  Parse *pParse,              /* The parsing context */
104458  WhereClause *pWC,           /* The WHERE clause */
104459  struct SrcList_item *pSrc,  /* The FROM clause term to search */
104460  Bitmask notReady,           /* Mask of cursors that are not available */
104461  WhereCost *pCost            /* Lowest cost query plan */
104462){
104463  double nTableRow;           /* Rows in the input table */
104464  double logN;                /* log(nTableRow) */
104465  double costTempIdx;         /* per-query cost of the transient index */
104466  WhereTerm *pTerm;           /* A single term of the WHERE clause */
104467  WhereTerm *pWCEnd;          /* End of pWC->a[] */
104468  Table *pTable;              /* Table tht might be indexed */
104469
104470  if( pParse->nQueryLoop<=(double)1 ){
104471    /* There is no point in building an automatic index for a single scan */
104472    return;
104473  }
104474  if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
104475    /* Automatic indices are disabled at run-time */
104476    return;
104477  }
104478  if( (pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)!=0 ){
104479    /* We already have some kind of index in use for this query. */
104480    return;
104481  }
104482  if( pSrc->notIndexed ){
104483    /* The NOT INDEXED clause appears in the SQL. */
104484    return;
104485  }
104486  if( pSrc->isCorrelated ){
104487    /* The source is a correlated sub-query. No point in indexing it. */
104488    return;
104489  }
104490
104491  assert( pParse->nQueryLoop >= (double)1 );
104492  pTable = pSrc->pTab;
104493  nTableRow = pTable->nRowEst;
104494  logN = estLog(nTableRow);
104495  costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
104496  if( costTempIdx>=pCost->rCost ){
104497    /* The cost of creating the transient table would be greater than
104498    ** doing the full table scan */
104499    return;
104500  }
104501
104502  /* Search for any equality comparison term */
104503  pWCEnd = &pWC->a[pWC->nTerm];
104504  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104505    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104506      WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
104507                    pCost->rCost, costTempIdx));
104508      pCost->rCost = costTempIdx;
104509      pCost->plan.nRow = logN + 1;
104510      pCost->plan.wsFlags = WHERE_TEMP_INDEX;
104511      pCost->used = pTerm->prereqRight;
104512      break;
104513    }
104514  }
104515}
104516#else
104517# define bestAutomaticIndex(A,B,C,D,E)  /* no-op */
104518#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
104519
104520
104521#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
104522/*
104523** Generate code to construct the Index object for an automatic index
104524** and to set up the WhereLevel object pLevel so that the code generator
104525** makes use of the automatic index.
104526*/
104527static void constructAutomaticIndex(
104528  Parse *pParse,              /* The parsing context */
104529  WhereClause *pWC,           /* The WHERE clause */
104530  struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
104531  Bitmask notReady,           /* Mask of cursors that are not available */
104532  WhereLevel *pLevel          /* Write new index here */
104533){
104534  int nColumn;                /* Number of columns in the constructed index */
104535  WhereTerm *pTerm;           /* A single term of the WHERE clause */
104536  WhereTerm *pWCEnd;          /* End of pWC->a[] */
104537  int nByte;                  /* Byte of memory needed for pIdx */
104538  Index *pIdx;                /* Object describing the transient index */
104539  Vdbe *v;                    /* Prepared statement under construction */
104540  int addrInit;               /* Address of the initialization bypass jump */
104541  Table *pTable;              /* The table being indexed */
104542  KeyInfo *pKeyinfo;          /* Key information for the index */
104543  int addrTop;                /* Top of the index fill loop */
104544  int regRecord;              /* Register holding an index record */
104545  int n;                      /* Column counter */
104546  int i;                      /* Loop counter */
104547  int mxBitCol;               /* Maximum column in pSrc->colUsed */
104548  CollSeq *pColl;             /* Collating sequence to on a column */
104549  Bitmask idxCols;            /* Bitmap of columns used for indexing */
104550  Bitmask extraCols;          /* Bitmap of additional columns */
104551
104552  /* Generate code to skip over the creation and initialization of the
104553  ** transient index on 2nd and subsequent iterations of the loop. */
104554  v = pParse->pVdbe;
104555  assert( v!=0 );
104556  addrInit = sqlite3CodeOnce(pParse);
104557
104558  /* Count the number of columns that will be added to the index
104559  ** and used to match WHERE clause constraints */
104560  nColumn = 0;
104561  pTable = pSrc->pTab;
104562  pWCEnd = &pWC->a[pWC->nTerm];
104563  idxCols = 0;
104564  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104565    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104566      int iCol = pTerm->u.leftColumn;
104567      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104568      testcase( iCol==BMS );
104569      testcase( iCol==BMS-1 );
104570      if( (idxCols & cMask)==0 ){
104571        nColumn++;
104572        idxCols |= cMask;
104573      }
104574    }
104575  }
104576  assert( nColumn>0 );
104577  pLevel->plan.nEq = nColumn;
104578
104579  /* Count the number of additional columns needed to create a
104580  ** covering index.  A "covering index" is an index that contains all
104581  ** columns that are needed by the query.  With a covering index, the
104582  ** original table never needs to be accessed.  Automatic indices must
104583  ** be a covering index because the index will not be updated if the
104584  ** original table changes and the index and table cannot both be used
104585  ** if they go out of sync.
104586  */
104587  extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
104588  mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
104589  testcase( pTable->nCol==BMS-1 );
104590  testcase( pTable->nCol==BMS-2 );
104591  for(i=0; i<mxBitCol; i++){
104592    if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
104593  }
104594  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104595    nColumn += pTable->nCol - BMS + 1;
104596  }
104597  pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
104598
104599  /* Construct the Index object to describe this index */
104600  nByte = sizeof(Index);
104601  nByte += nColumn*sizeof(int);     /* Index.aiColumn */
104602  nByte += nColumn*sizeof(char*);   /* Index.azColl */
104603  nByte += nColumn;                 /* Index.aSortOrder */
104604  pIdx = sqlite3DbMallocZero(pParse->db, nByte);
104605  if( pIdx==0 ) return;
104606  pLevel->plan.u.pIdx = pIdx;
104607  pIdx->azColl = (char**)&pIdx[1];
104608  pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
104609  pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
104610  pIdx->zName = "auto-index";
104611  pIdx->nColumn = nColumn;
104612  pIdx->pTable = pTable;
104613  n = 0;
104614  idxCols = 0;
104615  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
104616    if( termCanDriveIndex(pTerm, pSrc, notReady) ){
104617      int iCol = pTerm->u.leftColumn;
104618      Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
104619      if( (idxCols & cMask)==0 ){
104620        Expr *pX = pTerm->pExpr;
104621        idxCols |= cMask;
104622        pIdx->aiColumn[n] = pTerm->u.leftColumn;
104623        pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
104624        pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
104625        n++;
104626      }
104627    }
104628  }
104629  assert( (u32)n==pLevel->plan.nEq );
104630
104631  /* Add additional columns needed to make the automatic index into
104632  ** a covering index */
104633  for(i=0; i<mxBitCol; i++){
104634    if( extraCols & (((Bitmask)1)<<i) ){
104635      pIdx->aiColumn[n] = i;
104636      pIdx->azColl[n] = "BINARY";
104637      n++;
104638    }
104639  }
104640  if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
104641    for(i=BMS-1; i<pTable->nCol; i++){
104642      pIdx->aiColumn[n] = i;
104643      pIdx->azColl[n] = "BINARY";
104644      n++;
104645    }
104646  }
104647  assert( n==nColumn );
104648
104649  /* Create the automatic index */
104650  pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
104651  assert( pLevel->iIdxCur>=0 );
104652  sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
104653                    (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
104654  VdbeComment((v, "for %s", pTable->zName));
104655
104656  /* Fill the automatic index with content */
104657  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
104658  regRecord = sqlite3GetTempReg(pParse);
104659  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
104660  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
104661  sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
104662  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
104663  sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
104664  sqlite3VdbeJumpHere(v, addrTop);
104665  sqlite3ReleaseTempReg(pParse, regRecord);
104666
104667  /* Jump here when skipping the initialization */
104668  sqlite3VdbeJumpHere(v, addrInit);
104669}
104670#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
104671
104672#ifndef SQLITE_OMIT_VIRTUALTABLE
104673/*
104674** Allocate and populate an sqlite3_index_info structure. It is the
104675** responsibility of the caller to eventually release the structure
104676** by passing the pointer returned by this function to sqlite3_free().
104677*/
104678static sqlite3_index_info *allocateIndexInfo(
104679  Parse *pParse,
104680  WhereClause *pWC,
104681  struct SrcList_item *pSrc,
104682  ExprList *pOrderBy
104683){
104684  int i, j;
104685  int nTerm;
104686  struct sqlite3_index_constraint *pIdxCons;
104687  struct sqlite3_index_orderby *pIdxOrderBy;
104688  struct sqlite3_index_constraint_usage *pUsage;
104689  WhereTerm *pTerm;
104690  int nOrderBy;
104691  sqlite3_index_info *pIdxInfo;
104692
104693  WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
104694
104695  /* Count the number of possible WHERE clause constraints referring
104696  ** to this virtual table */
104697  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104698    if( pTerm->leftCursor != pSrc->iCursor ) continue;
104699    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104700    testcase( pTerm->eOperator==WO_IN );
104701    testcase( pTerm->eOperator==WO_ISNULL );
104702    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104703    if( pTerm->wtFlags & TERM_VNULL ) continue;
104704    nTerm++;
104705  }
104706
104707  /* If the ORDER BY clause contains only columns in the current
104708  ** virtual table then allocate space for the aOrderBy part of
104709  ** the sqlite3_index_info structure.
104710  */
104711  nOrderBy = 0;
104712  if( pOrderBy ){
104713    for(i=0; i<pOrderBy->nExpr; i++){
104714      Expr *pExpr = pOrderBy->a[i].pExpr;
104715      if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
104716    }
104717    if( i==pOrderBy->nExpr ){
104718      nOrderBy = pOrderBy->nExpr;
104719    }
104720  }
104721
104722  /* Allocate the sqlite3_index_info structure
104723  */
104724  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
104725                           + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
104726                           + sizeof(*pIdxOrderBy)*nOrderBy );
104727  if( pIdxInfo==0 ){
104728    sqlite3ErrorMsg(pParse, "out of memory");
104729    /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
104730    return 0;
104731  }
104732
104733  /* Initialize the structure.  The sqlite3_index_info structure contains
104734  ** many fields that are declared "const" to prevent xBestIndex from
104735  ** changing them.  We have to do some funky casting in order to
104736  ** initialize those fields.
104737  */
104738  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
104739  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
104740  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
104741  *(int*)&pIdxInfo->nConstraint = nTerm;
104742  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
104743  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
104744  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
104745  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
104746                                                                   pUsage;
104747
104748  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
104749    if( pTerm->leftCursor != pSrc->iCursor ) continue;
104750    assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
104751    testcase( pTerm->eOperator==WO_IN );
104752    testcase( pTerm->eOperator==WO_ISNULL );
104753    if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
104754    if( pTerm->wtFlags & TERM_VNULL ) continue;
104755    pIdxCons[j].iColumn = pTerm->u.leftColumn;
104756    pIdxCons[j].iTermOffset = i;
104757    pIdxCons[j].op = (u8)pTerm->eOperator;
104758    /* The direct assignment in the previous line is possible only because
104759    ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
104760    ** following asserts verify this fact. */
104761    assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
104762    assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
104763    assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
104764    assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
104765    assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
104766    assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
104767    assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
104768    j++;
104769  }
104770  for(i=0; i<nOrderBy; i++){
104771    Expr *pExpr = pOrderBy->a[i].pExpr;
104772    pIdxOrderBy[i].iColumn = pExpr->iColumn;
104773    pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
104774  }
104775
104776  return pIdxInfo;
104777}
104778
104779/*
104780** The table object reference passed as the second argument to this function
104781** must represent a virtual table. This function invokes the xBestIndex()
104782** method of the virtual table with the sqlite3_index_info pointer passed
104783** as the argument.
104784**
104785** If an error occurs, pParse is populated with an error message and a
104786** non-zero value is returned. Otherwise, 0 is returned and the output
104787** part of the sqlite3_index_info structure is left populated.
104788**
104789** Whether or not an error is returned, it is the responsibility of the
104790** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
104791** that this is required.
104792*/
104793static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
104794  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
104795  int i;
104796  int rc;
104797
104798  WHERETRACE(("xBestIndex for %s\n", pTab->zName));
104799  TRACE_IDX_INPUTS(p);
104800  rc = pVtab->pModule->xBestIndex(pVtab, p);
104801  TRACE_IDX_OUTPUTS(p);
104802
104803  if( rc!=SQLITE_OK ){
104804    if( rc==SQLITE_NOMEM ){
104805      pParse->db->mallocFailed = 1;
104806    }else if( !pVtab->zErrMsg ){
104807      sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
104808    }else{
104809      sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
104810    }
104811  }
104812  sqlite3_free(pVtab->zErrMsg);
104813  pVtab->zErrMsg = 0;
104814
104815  for(i=0; i<p->nConstraint; i++){
104816    if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
104817      sqlite3ErrorMsg(pParse,
104818          "table %s: xBestIndex returned an invalid plan", pTab->zName);
104819    }
104820  }
104821
104822  return pParse->nErr;
104823}
104824
104825
104826/*
104827** Compute the best index for a virtual table.
104828**
104829** The best index is computed by the xBestIndex method of the virtual
104830** table module.  This routine is really just a wrapper that sets up
104831** the sqlite3_index_info structure that is used to communicate with
104832** xBestIndex.
104833**
104834** In a join, this routine might be called multiple times for the
104835** same virtual table.  The sqlite3_index_info structure is created
104836** and initialized on the first invocation and reused on all subsequent
104837** invocations.  The sqlite3_index_info structure is also used when
104838** code is generated to access the virtual table.  The whereInfoDelete()
104839** routine takes care of freeing the sqlite3_index_info structure after
104840** everybody has finished with it.
104841*/
104842static void bestVirtualIndex(
104843  Parse *pParse,                  /* The parsing context */
104844  WhereClause *pWC,               /* The WHERE clause */
104845  struct SrcList_item *pSrc,      /* The FROM clause term to search */
104846  Bitmask notReady,               /* Mask of cursors not available for index */
104847  Bitmask notValid,               /* Cursors not valid for any purpose */
104848  ExprList *pOrderBy,             /* The order by clause */
104849  WhereCost *pCost,               /* Lowest cost query plan */
104850  sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
104851){
104852  Table *pTab = pSrc->pTab;
104853  sqlite3_index_info *pIdxInfo;
104854  struct sqlite3_index_constraint *pIdxCons;
104855  struct sqlite3_index_constraint_usage *pUsage;
104856  WhereTerm *pTerm;
104857  int i, j;
104858  int nOrderBy;
104859  double rCost;
104860
104861  /* Make sure wsFlags is initialized to some sane value. Otherwise, if the
104862  ** malloc in allocateIndexInfo() fails and this function returns leaving
104863  ** wsFlags in an uninitialized state, the caller may behave unpredictably.
104864  */
104865  memset(pCost, 0, sizeof(*pCost));
104866  pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
104867
104868  /* If the sqlite3_index_info structure has not been previously
104869  ** allocated and initialized, then allocate and initialize it now.
104870  */
104871  pIdxInfo = *ppIdxInfo;
104872  if( pIdxInfo==0 ){
104873    *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
104874  }
104875  if( pIdxInfo==0 ){
104876    return;
104877  }
104878
104879  /* At this point, the sqlite3_index_info structure that pIdxInfo points
104880  ** to will have been initialized, either during the current invocation or
104881  ** during some prior invocation.  Now we just have to customize the
104882  ** details of pIdxInfo for the current invocation and pass it to
104883  ** xBestIndex.
104884  */
104885
104886  /* The module name must be defined. Also, by this point there must
104887  ** be a pointer to an sqlite3_vtab structure. Otherwise
104888  ** sqlite3ViewGetColumnNames() would have picked up the error.
104889  */
104890  assert( pTab->azModuleArg && pTab->azModuleArg[0] );
104891  assert( sqlite3GetVTable(pParse->db, pTab) );
104892
104893  /* Set the aConstraint[].usable fields and initialize all
104894  ** output variables to zero.
104895  **
104896  ** aConstraint[].usable is true for constraints where the right-hand
104897  ** side contains only references to tables to the left of the current
104898  ** table.  In other words, if the constraint is of the form:
104899  **
104900  **           column = expr
104901  **
104902  ** and we are evaluating a join, then the constraint on column is
104903  ** only valid if all tables referenced in expr occur to the left
104904  ** of the table containing column.
104905  **
104906  ** The aConstraints[] array contains entries for all constraints
104907  ** on the current table.  That way we only have to compute it once
104908  ** even though we might try to pick the best index multiple times.
104909  ** For each attempt at picking an index, the order of tables in the
104910  ** join might be different so we have to recompute the usable flag
104911  ** each time.
104912  */
104913  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
104914  pUsage = pIdxInfo->aConstraintUsage;
104915  for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
104916    j = pIdxCons->iTermOffset;
104917    pTerm = &pWC->a[j];
104918    pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
104919  }
104920  memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
104921  if( pIdxInfo->needToFreeIdxStr ){
104922    sqlite3_free(pIdxInfo->idxStr);
104923  }
104924  pIdxInfo->idxStr = 0;
104925  pIdxInfo->idxNum = 0;
104926  pIdxInfo->needToFreeIdxStr = 0;
104927  pIdxInfo->orderByConsumed = 0;
104928  /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
104929  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
104930  nOrderBy = pIdxInfo->nOrderBy;
104931  if( !pOrderBy ){
104932    pIdxInfo->nOrderBy = 0;
104933  }
104934
104935  if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
104936    return;
104937  }
104938
104939  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
104940  for(i=0; i<pIdxInfo->nConstraint; i++){
104941    if( pUsage[i].argvIndex>0 ){
104942      pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
104943    }
104944  }
104945
104946  /* If there is an ORDER BY clause, and the selected virtual table index
104947  ** does not satisfy it, increase the cost of the scan accordingly. This
104948  ** matches the processing for non-virtual tables in bestBtreeIndex().
104949  */
104950  rCost = pIdxInfo->estimatedCost;
104951  if( pOrderBy && pIdxInfo->orderByConsumed==0 ){
104952    rCost += estLog(rCost)*rCost;
104953  }
104954
104955  /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
104956  ** inital value of lowestCost in this loop. If it is, then the
104957  ** (cost<lowestCost) test below will never be true.
104958  **
104959  ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT
104960  ** is defined.
104961  */
104962  if( (SQLITE_BIG_DBL/((double)2))<rCost ){
104963    pCost->rCost = (SQLITE_BIG_DBL/((double)2));
104964  }else{
104965    pCost->rCost = rCost;
104966  }
104967  pCost->plan.u.pVtabIdx = pIdxInfo;
104968  if( pIdxInfo->orderByConsumed ){
104969    pCost->plan.wsFlags |= WHERE_ORDERBY;
104970  }
104971  pCost->plan.nEq = 0;
104972  pIdxInfo->nOrderBy = nOrderBy;
104973
104974  /* Try to find a more efficient access pattern by using multiple indexes
104975  ** to optimize an OR expression within the WHERE clause.
104976  */
104977  bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
104978}
104979#endif /* SQLITE_OMIT_VIRTUALTABLE */
104980
104981#ifdef SQLITE_ENABLE_STAT3
104982/*
104983** Estimate the location of a particular key among all keys in an
104984** index.  Store the results in aStat as follows:
104985**
104986**    aStat[0]      Est. number of rows less than pVal
104987**    aStat[1]      Est. number of rows equal to pVal
104988**
104989** Return SQLITE_OK on success.
104990*/
104991static int whereKeyStats(
104992  Parse *pParse,              /* Database connection */
104993  Index *pIdx,                /* Index to consider domain of */
104994  sqlite3_value *pVal,        /* Value to consider */
104995  int roundUp,                /* Round up if true.  Round down if false */
104996  tRowcnt *aStat              /* OUT: stats written here */
104997){
104998  tRowcnt n;
104999  IndexSample *aSample;
105000  int i, eType;
105001  int isEq = 0;
105002  i64 v;
105003  double r, rS;
105004
105005  assert( roundUp==0 || roundUp==1 );
105006  assert( pIdx->nSample>0 );
105007  if( pVal==0 ) return SQLITE_ERROR;
105008  n = pIdx->aiRowEst[0];
105009  aSample = pIdx->aSample;
105010  eType = sqlite3_value_type(pVal);
105011
105012  if( eType==SQLITE_INTEGER ){
105013    v = sqlite3_value_int64(pVal);
105014    r = (i64)v;
105015    for(i=0; i<pIdx->nSample; i++){
105016      if( aSample[i].eType==SQLITE_NULL ) continue;
105017      if( aSample[i].eType>=SQLITE_TEXT ) break;
105018      if( aSample[i].eType==SQLITE_INTEGER ){
105019        if( aSample[i].u.i>=v ){
105020          isEq = aSample[i].u.i==v;
105021          break;
105022        }
105023      }else{
105024        assert( aSample[i].eType==SQLITE_FLOAT );
105025        if( aSample[i].u.r>=r ){
105026          isEq = aSample[i].u.r==r;
105027          break;
105028        }
105029      }
105030    }
105031  }else if( eType==SQLITE_FLOAT ){
105032    r = sqlite3_value_double(pVal);
105033    for(i=0; i<pIdx->nSample; i++){
105034      if( aSample[i].eType==SQLITE_NULL ) continue;
105035      if( aSample[i].eType>=SQLITE_TEXT ) break;
105036      if( aSample[i].eType==SQLITE_FLOAT ){
105037        rS = aSample[i].u.r;
105038      }else{
105039        rS = aSample[i].u.i;
105040      }
105041      if( rS>=r ){
105042        isEq = rS==r;
105043        break;
105044      }
105045    }
105046  }else if( eType==SQLITE_NULL ){
105047    i = 0;
105048    if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
105049  }else{
105050    assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
105051    for(i=0; i<pIdx->nSample; i++){
105052      if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
105053        break;
105054      }
105055    }
105056    if( i<pIdx->nSample ){
105057      sqlite3 *db = pParse->db;
105058      CollSeq *pColl;
105059      const u8 *z;
105060      if( eType==SQLITE_BLOB ){
105061        z = (const u8 *)sqlite3_value_blob(pVal);
105062        pColl = db->pDfltColl;
105063        assert( pColl->enc==SQLITE_UTF8 );
105064      }else{
105065        pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
105066        if( pColl==0 ){
105067          sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
105068                          *pIdx->azColl);
105069          return SQLITE_ERROR;
105070        }
105071        z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
105072        if( !z ){
105073          return SQLITE_NOMEM;
105074        }
105075        assert( z && pColl && pColl->xCmp );
105076      }
105077      n = sqlite3ValueBytes(pVal, pColl->enc);
105078
105079      for(; i<pIdx->nSample; i++){
105080        int c;
105081        int eSampletype = aSample[i].eType;
105082        if( eSampletype<eType ) continue;
105083        if( eSampletype!=eType ) break;
105084#ifndef SQLITE_OMIT_UTF16
105085        if( pColl->enc!=SQLITE_UTF8 ){
105086          int nSample;
105087          char *zSample = sqlite3Utf8to16(
105088              db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
105089          );
105090          if( !zSample ){
105091            assert( db->mallocFailed );
105092            return SQLITE_NOMEM;
105093          }
105094          c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
105095          sqlite3DbFree(db, zSample);
105096        }else
105097#endif
105098        {
105099          c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
105100        }
105101        if( c>=0 ){
105102          if( c==0 ) isEq = 1;
105103          break;
105104        }
105105      }
105106    }
105107  }
105108
105109  /* At this point, aSample[i] is the first sample that is greater than
105110  ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
105111  ** than pVal.  If aSample[i]==pVal, then isEq==1.
105112  */
105113  if( isEq ){
105114    assert( i<pIdx->nSample );
105115    aStat[0] = aSample[i].nLt;
105116    aStat[1] = aSample[i].nEq;
105117  }else{
105118    tRowcnt iLower, iUpper, iGap;
105119    if( i==0 ){
105120      iLower = 0;
105121      iUpper = aSample[0].nLt;
105122    }else{
105123      iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
105124      iLower = aSample[i-1].nEq + aSample[i-1].nLt;
105125    }
105126    aStat[1] = pIdx->avgEq;
105127    if( iLower>=iUpper ){
105128      iGap = 0;
105129    }else{
105130      iGap = iUpper - iLower;
105131    }
105132    if( roundUp ){
105133      iGap = (iGap*2)/3;
105134    }else{
105135      iGap = iGap/3;
105136    }
105137    aStat[0] = iLower + iGap;
105138  }
105139  return SQLITE_OK;
105140}
105141#endif /* SQLITE_ENABLE_STAT3 */
105142
105143/*
105144** If expression pExpr represents a literal value, set *pp to point to
105145** an sqlite3_value structure containing the same value, with affinity
105146** aff applied to it, before returning. It is the responsibility of the
105147** caller to eventually release this structure by passing it to
105148** sqlite3ValueFree().
105149**
105150** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
105151** is an SQL variable that currently has a non-NULL value bound to it,
105152** create an sqlite3_value structure containing this value, again with
105153** affinity aff applied to it, instead.
105154**
105155** If neither of the above apply, set *pp to NULL.
105156**
105157** If an error occurs, return an error code. Otherwise, SQLITE_OK.
105158*/
105159#ifdef SQLITE_ENABLE_STAT3
105160static int valueFromExpr(
105161  Parse *pParse,
105162  Expr *pExpr,
105163  u8 aff,
105164  sqlite3_value **pp
105165){
105166  if( pExpr->op==TK_VARIABLE
105167   || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
105168  ){
105169    int iVar = pExpr->iColumn;
105170    sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
105171    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
105172    return SQLITE_OK;
105173  }
105174  return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
105175}
105176#endif
105177
105178/*
105179** This function is used to estimate the number of rows that will be visited
105180** by scanning an index for a range of values. The range may have an upper
105181** bound, a lower bound, or both. The WHERE clause terms that set the upper
105182** and lower bounds are represented by pLower and pUpper respectively. For
105183** example, assuming that index p is on t1(a):
105184**
105185**   ... FROM t1 WHERE a > ? AND a < ? ...
105186**                    |_____|   |_____|
105187**                       |         |
105188**                     pLower    pUpper
105189**
105190** If either of the upper or lower bound is not present, then NULL is passed in
105191** place of the corresponding WhereTerm.
105192**
105193** The nEq parameter is passed the index of the index column subject to the
105194** range constraint. Or, equivalently, the number of equality constraints
105195** optimized by the proposed index scan. For example, assuming index p is
105196** on t1(a, b), and the SQL query is:
105197**
105198**   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
105199**
105200** then nEq should be passed the value 1 (as the range restricted column,
105201** b, is the second left-most column of the index). Or, if the query is:
105202**
105203**   ... FROM t1 WHERE a > ? AND a < ? ...
105204**
105205** then nEq should be passed 0.
105206**
105207** The returned value is an integer divisor to reduce the estimated
105208** search space.  A return value of 1 means that range constraints are
105209** no help at all.  A return value of 2 means range constraints are
105210** expected to reduce the search space by half.  And so forth...
105211**
105212** In the absence of sqlite_stat3 ANALYZE data, each range inequality
105213** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
105214** results in a return of 4 and a range constraint (x>? AND x<?) results
105215** in a return of 16.
105216*/
105217static int whereRangeScanEst(
105218  Parse *pParse,       /* Parsing & code generating context */
105219  Index *p,            /* The index containing the range-compared column; "x" */
105220  int nEq,             /* index into p->aCol[] of the range-compared column */
105221  WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
105222  WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
105223  double *pRangeDiv   /* OUT: Reduce search space by this divisor */
105224){
105225  int rc = SQLITE_OK;
105226
105227#ifdef SQLITE_ENABLE_STAT3
105228
105229  if( nEq==0 && p->nSample ){
105230    sqlite3_value *pRangeVal;
105231    tRowcnt iLower = 0;
105232    tRowcnt iUpper = p->aiRowEst[0];
105233    tRowcnt a[2];
105234    u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105235
105236    if( pLower ){
105237      Expr *pExpr = pLower->pExpr->pRight;
105238      rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105239      assert( pLower->eOperator==WO_GT || pLower->eOperator==WO_GE );
105240      if( rc==SQLITE_OK
105241       && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
105242      ){
105243        iLower = a[0];
105244        if( pLower->eOperator==WO_GT ) iLower += a[1];
105245      }
105246      sqlite3ValueFree(pRangeVal);
105247    }
105248    if( rc==SQLITE_OK && pUpper ){
105249      Expr *pExpr = pUpper->pExpr->pRight;
105250      rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
105251      assert( pUpper->eOperator==WO_LT || pUpper->eOperator==WO_LE );
105252      if( rc==SQLITE_OK
105253       && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
105254      ){
105255        iUpper = a[0];
105256        if( pUpper->eOperator==WO_LE ) iUpper += a[1];
105257      }
105258      sqlite3ValueFree(pRangeVal);
105259    }
105260    if( rc==SQLITE_OK ){
105261      if( iUpper<=iLower ){
105262        *pRangeDiv = (double)p->aiRowEst[0];
105263      }else{
105264        *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
105265      }
105266      WHERETRACE(("range scan regions: %u..%u  div=%g\n",
105267                  (u32)iLower, (u32)iUpper, *pRangeDiv));
105268      return SQLITE_OK;
105269    }
105270  }
105271#else
105272  UNUSED_PARAMETER(pParse);
105273  UNUSED_PARAMETER(p);
105274  UNUSED_PARAMETER(nEq);
105275#endif
105276  assert( pLower || pUpper );
105277  *pRangeDiv = (double)1;
105278  if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
105279  if( pUpper ) *pRangeDiv *= (double)4;
105280  return rc;
105281}
105282
105283#ifdef SQLITE_ENABLE_STAT3
105284/*
105285** Estimate the number of rows that will be returned based on
105286** an equality constraint x=VALUE and where that VALUE occurs in
105287** the histogram data.  This only works when x is the left-most
105288** column of an index and sqlite_stat3 histogram data is available
105289** for that index.  When pExpr==NULL that means the constraint is
105290** "x IS NULL" instead of "x=VALUE".
105291**
105292** Write the estimated row count into *pnRow and return SQLITE_OK.
105293** If unable to make an estimate, leave *pnRow unchanged and return
105294** non-zero.
105295**
105296** This routine can fail if it is unable to load a collating sequence
105297** required for string comparison, or if unable to allocate memory
105298** for a UTF conversion required for comparison.  The error is stored
105299** in the pParse structure.
105300*/
105301static int whereEqualScanEst(
105302  Parse *pParse,       /* Parsing & code generating context */
105303  Index *p,            /* The index whose left-most column is pTerm */
105304  Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
105305  double *pnRow        /* Write the revised row estimate here */
105306){
105307  sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
105308  u8 aff;                   /* Column affinity */
105309  int rc;                   /* Subfunction return code */
105310  tRowcnt a[2];             /* Statistics */
105311
105312  assert( p->aSample!=0 );
105313  assert( p->nSample>0 );
105314  aff = p->pTable->aCol[p->aiColumn[0]].affinity;
105315  if( pExpr ){
105316    rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
105317    if( rc ) goto whereEqualScanEst_cancel;
105318  }else{
105319    pRhs = sqlite3ValueNew(pParse->db);
105320  }
105321  if( pRhs==0 ) return SQLITE_NOTFOUND;
105322  rc = whereKeyStats(pParse, p, pRhs, 0, a);
105323  if( rc==SQLITE_OK ){
105324    WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
105325    *pnRow = a[1];
105326  }
105327whereEqualScanEst_cancel:
105328  sqlite3ValueFree(pRhs);
105329  return rc;
105330}
105331#endif /* defined(SQLITE_ENABLE_STAT3) */
105332
105333#ifdef SQLITE_ENABLE_STAT3
105334/*
105335** Estimate the number of rows that will be returned based on
105336** an IN constraint where the right-hand side of the IN operator
105337** is a list of values.  Example:
105338**
105339**        WHERE x IN (1,2,3,4)
105340**
105341** Write the estimated row count into *pnRow and return SQLITE_OK.
105342** If unable to make an estimate, leave *pnRow unchanged and return
105343** non-zero.
105344**
105345** This routine can fail if it is unable to load a collating sequence
105346** required for string comparison, or if unable to allocate memory
105347** for a UTF conversion required for comparison.  The error is stored
105348** in the pParse structure.
105349*/
105350static int whereInScanEst(
105351  Parse *pParse,       /* Parsing & code generating context */
105352  Index *p,            /* The index whose left-most column is pTerm */
105353  ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
105354  double *pnRow        /* Write the revised row estimate here */
105355){
105356  int rc = SQLITE_OK;         /* Subfunction return code */
105357  double nEst;                /* Number of rows for a single term */
105358  double nRowEst = (double)0; /* New estimate of the number of rows */
105359  int i;                      /* Loop counter */
105360
105361  assert( p->aSample!=0 );
105362  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
105363    nEst = p->aiRowEst[0];
105364    rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
105365    nRowEst += nEst;
105366  }
105367  if( rc==SQLITE_OK ){
105368    if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
105369    *pnRow = nRowEst;
105370    WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
105371  }
105372  return rc;
105373}
105374#endif /* defined(SQLITE_ENABLE_STAT3) */
105375
105376
105377/*
105378** Find the best query plan for accessing a particular table.  Write the
105379** best query plan and its cost into the WhereCost object supplied as the
105380** last parameter.
105381**
105382** The lowest cost plan wins.  The cost is an estimate of the amount of
105383** CPU and disk I/O needed to process the requested result.
105384** Factors that influence cost include:
105385**
105386**    *  The estimated number of rows that will be retrieved.  (The
105387**       fewer the better.)
105388**
105389**    *  Whether or not sorting must occur.
105390**
105391**    *  Whether or not there must be separate lookups in the
105392**       index and in the main table.
105393**
105394** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
105395** the SQL statement, then this function only considers plans using the
105396** named index. If no such plan is found, then the returned cost is
105397** SQLITE_BIG_DBL. If a plan is found that uses the named index,
105398** then the cost is calculated in the usual way.
105399**
105400** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table
105401** in the SELECT statement, then no indexes are considered. However, the
105402** selected plan may still take advantage of the built-in rowid primary key
105403** index.
105404*/
105405static void bestBtreeIndex(
105406  Parse *pParse,              /* The parsing context */
105407  WhereClause *pWC,           /* The WHERE clause */
105408  struct SrcList_item *pSrc,  /* The FROM clause term to search */
105409  Bitmask notReady,           /* Mask of cursors not available for indexing */
105410  Bitmask notValid,           /* Cursors not available for any purpose */
105411  ExprList *pOrderBy,         /* The ORDER BY clause */
105412  ExprList *pDistinct,        /* The select-list if query is DISTINCT */
105413  WhereCost *pCost            /* Lowest cost query plan */
105414){
105415  int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
105416  Index *pProbe;              /* An index we are evaluating */
105417  Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
105418  int eqTermMask;             /* Current mask of valid equality operators */
105419  int idxEqTermMask;          /* Index mask of valid equality operators */
105420  Index sPk;                  /* A fake index object for the primary key */
105421  tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
105422  int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
105423  int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
105424
105425  /* Initialize the cost to a worst-case value */
105426  memset(pCost, 0, sizeof(*pCost));
105427  pCost->rCost = SQLITE_BIG_DBL;
105428
105429  /* If the pSrc table is the right table of a LEFT JOIN then we may not
105430  ** use an index to satisfy IS NULL constraints on that table.  This is
105431  ** because columns might end up being NULL if the table does not match -
105432  ** a circumstance which the index cannot help us discover.  Ticket #2177.
105433  */
105434  if( pSrc->jointype & JT_LEFT ){
105435    idxEqTermMask = WO_EQ|WO_IN;
105436  }else{
105437    idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
105438  }
105439
105440  if( pSrc->pIndex ){
105441    /* An INDEXED BY clause specifies a particular index to use */
105442    pIdx = pProbe = pSrc->pIndex;
105443    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105444    eqTermMask = idxEqTermMask;
105445  }else{
105446    /* There is no INDEXED BY clause.  Create a fake Index object in local
105447    ** variable sPk to represent the rowid primary key index.  Make this
105448    ** fake index the first in a chain of Index objects with all of the real
105449    ** indices to follow */
105450    Index *pFirst;                  /* First of real indices on the table */
105451    memset(&sPk, 0, sizeof(Index));
105452    sPk.nColumn = 1;
105453    sPk.aiColumn = &aiColumnPk;
105454    sPk.aiRowEst = aiRowEstPk;
105455    sPk.onError = OE_Replace;
105456    sPk.pTable = pSrc->pTab;
105457    aiRowEstPk[0] = pSrc->pTab->nRowEst;
105458    aiRowEstPk[1] = 1;
105459    pFirst = pSrc->pTab->pIndex;
105460    if( pSrc->notIndexed==0 ){
105461      /* The real indices of the table are only considered if the
105462      ** NOT INDEXED qualifier is omitted from the FROM clause */
105463      sPk.pNext = pFirst;
105464    }
105465    pProbe = &sPk;
105466    wsFlagMask = ~(
105467        WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
105468    );
105469    eqTermMask = WO_EQ|WO_IN;
105470    pIdx = 0;
105471  }
105472
105473  /* Loop over all indices looking for the best one to use
105474  */
105475  for(; pProbe; pIdx=pProbe=pProbe->pNext){
105476    const tRowcnt * const aiRowEst = pProbe->aiRowEst;
105477    double cost;                /* Cost of using pProbe */
105478    double nRow;                /* Estimated number of rows in result set */
105479    double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
105480    int rev;                    /* True to scan in reverse order */
105481    int wsFlags = 0;
105482    Bitmask used = 0;
105483
105484    /* The following variables are populated based on the properties of
105485    ** index being evaluated. They are then used to determine the expected
105486    ** cost and number of rows returned.
105487    **
105488    **  nEq:
105489    **    Number of equality terms that can be implemented using the index.
105490    **    In other words, the number of initial fields in the index that
105491    **    are used in == or IN or NOT NULL constraints of the WHERE clause.
105492    **
105493    **  nInMul:
105494    **    The "in-multiplier". This is an estimate of how many seek operations
105495    **    SQLite must perform on the index in question. For example, if the
105496    **    WHERE clause is:
105497    **
105498    **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
105499    **
105500    **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is
105501    **    set to 9. Given the same schema and either of the following WHERE
105502    **    clauses:
105503    **
105504    **      WHERE a =  1
105505    **      WHERE a >= 2
105506    **
105507    **    nInMul is set to 1.
105508    **
105509    **    If there exists a WHERE term of the form "x IN (SELECT ...)", then
105510    **    the sub-select is assumed to return 25 rows for the purposes of
105511    **    determining nInMul.
105512    **
105513    **  bInEst:
105514    **    Set to true if there was at least one "x IN (SELECT ...)" term used
105515    **    in determining the value of nInMul.  Note that the RHS of the
105516    **    IN operator must be a SELECT, not a value list, for this variable
105517    **    to be true.
105518    **
105519    **  rangeDiv:
105520    **    An estimate of a divisor by which to reduce the search space due
105521    **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
105522    **    data, a single inequality reduces the search space to 1/4rd its
105523    **    original size (rangeDiv==4).  Two inequalities reduce the search
105524    **    space to 1/16th of its original size (rangeDiv==16).
105525    **
105526    **  bSort:
105527    **    Boolean. True if there is an ORDER BY clause that will require an
105528    **    external sort (i.e. scanning the index being evaluated will not
105529    **    correctly order records).
105530    **
105531    **  bLookup:
105532    **    Boolean. True if a table lookup is required for each index entry
105533    **    visited.  In other words, true if this is not a covering index.
105534    **    This is always false for the rowid primary key index of a table.
105535    **    For other indexes, it is true unless all the columns of the table
105536    **    used by the SELECT statement are present in the index (such an
105537    **    index is sometimes described as a covering index).
105538    **    For example, given the index on (a, b), the second of the following
105539    **    two queries requires table b-tree lookups in order to find the value
105540    **    of column c, but the first does not because columns a and b are
105541    **    both available in the index.
105542    **
105543    **             SELECT a, b    FROM tbl WHERE a = 1;
105544    **             SELECT a, b, c FROM tbl WHERE a = 1;
105545    */
105546    int nEq;                      /* Number of == or IN terms matching index */
105547    int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
105548    int nInMul = 1;               /* Number of distinct equalities to lookup */
105549    double rangeDiv = (double)1;  /* Estimated reduction in search space */
105550    int nBound = 0;               /* Number of range constraints seen */
105551    int bSort = !!pOrderBy;       /* True if external sort required */
105552    int bDist = !!pDistinct;      /* True if index cannot help with DISTINCT */
105553    int bLookup = 0;              /* True if not a covering index */
105554    WhereTerm *pTerm;             /* A single term of the WHERE clause */
105555#ifdef SQLITE_ENABLE_STAT3
105556    WhereTerm *pFirstTerm = 0;    /* First term matching the index */
105557#endif
105558
105559    /* Determine the values of nEq and nInMul */
105560    for(nEq=0; nEq<pProbe->nColumn; nEq++){
105561      int j = pProbe->aiColumn[nEq];
105562      pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
105563      if( pTerm==0 ) break;
105564      wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
105565      testcase( pTerm->pWC!=pWC );
105566      if( pTerm->eOperator & WO_IN ){
105567        Expr *pExpr = pTerm->pExpr;
105568        wsFlags |= WHERE_COLUMN_IN;
105569        if( ExprHasProperty(pExpr, EP_xIsSelect) ){
105570          /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
105571          nInMul *= 25;
105572          bInEst = 1;
105573        }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
105574          /* "x IN (value, value, ...)" */
105575          nInMul *= pExpr->x.pList->nExpr;
105576        }
105577      }else if( pTerm->eOperator & WO_ISNULL ){
105578        wsFlags |= WHERE_COLUMN_NULL;
105579      }
105580#ifdef SQLITE_ENABLE_STAT3
105581      if( nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
105582#endif
105583      used |= pTerm->prereqRight;
105584    }
105585
105586    /* If the index being considered is UNIQUE, and there is an equality
105587    ** constraint for all columns in the index, then this search will find
105588    ** at most a single row. In this case set the WHERE_UNIQUE flag to
105589    ** indicate this to the caller.
105590    **
105591    ** Otherwise, if the search may find more than one row, test to see if
105592    ** there is a range constraint on indexed column (nEq+1) that can be
105593    ** optimized using the index.
105594    */
105595    if( nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
105596      testcase( wsFlags & WHERE_COLUMN_IN );
105597      testcase( wsFlags & WHERE_COLUMN_NULL );
105598      if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
105599        wsFlags |= WHERE_UNIQUE;
105600      }
105601    }else if( pProbe->bUnordered==0 ){
105602      int j = (nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[nEq]);
105603      if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
105604        WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
105605        WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
105606        whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &rangeDiv);
105607        if( pTop ){
105608          nBound = 1;
105609          wsFlags |= WHERE_TOP_LIMIT;
105610          used |= pTop->prereqRight;
105611          testcase( pTop->pWC!=pWC );
105612        }
105613        if( pBtm ){
105614          nBound++;
105615          wsFlags |= WHERE_BTM_LIMIT;
105616          used |= pBtm->prereqRight;
105617          testcase( pBtm->pWC!=pWC );
105618        }
105619        wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
105620      }
105621    }
105622
105623    /* If there is an ORDER BY clause and the index being considered will
105624    ** naturally scan rows in the required order, set the appropriate flags
105625    ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
105626    ** will scan rows in a different order, set the bSort variable.  */
105627    if( isSortingIndex(
105628          pParse, pWC->pMaskSet, pProbe, iCur, pOrderBy, nEq, wsFlags, &rev)
105629    ){
105630      bSort = 0;
105631      wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
105632      wsFlags |= (rev ? WHERE_REVERSE : 0);
105633    }
105634
105635    /* If there is a DISTINCT qualifier and this index will scan rows in
105636    ** order of the DISTINCT expressions, clear bDist and set the appropriate
105637    ** flags in wsFlags. */
105638    if( isDistinctIndex(pParse, pWC, pProbe, iCur, pDistinct, nEq)
105639     && (wsFlags & WHERE_COLUMN_IN)==0
105640    ){
105641      bDist = 0;
105642      wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
105643    }
105644
105645    /* If currently calculating the cost of using an index (not the IPK
105646    ** index), determine if all required column data may be obtained without
105647    ** using the main table (i.e. if the index is a covering
105648    ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
105649    ** wsFlags. Otherwise, set the bLookup variable to true.  */
105650    if( pIdx && wsFlags ){
105651      Bitmask m = pSrc->colUsed;
105652      int j;
105653      for(j=0; j<pIdx->nColumn; j++){
105654        int x = pIdx->aiColumn[j];
105655        if( x<BMS-1 ){
105656          m &= ~(((Bitmask)1)<<x);
105657        }
105658      }
105659      if( m==0 ){
105660        wsFlags |= WHERE_IDX_ONLY;
105661      }else{
105662        bLookup = 1;
105663      }
105664    }
105665
105666    /*
105667    ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
105668    ** constraint, do not let the estimate exceed half the rows in the table.
105669    */
105670    nRow = (double)(aiRowEst[nEq] * nInMul);
105671    if( bInEst && nRow*2>aiRowEst[0] ){
105672      nRow = aiRowEst[0]/2;
105673      nInMul = (int)(nRow / aiRowEst[nEq]);
105674    }
105675
105676#ifdef SQLITE_ENABLE_STAT3
105677    /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
105678    ** and we do not think that values of x are unique and if histogram
105679    ** data is available for column x, then it might be possible
105680    ** to get a better estimate on the number of rows based on
105681    ** VALUE and how common that value is according to the histogram.
105682    */
105683    if( nRow>(double)1 && nEq==1 && pFirstTerm!=0 && aiRowEst[1]>1 ){
105684      assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
105685      if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
105686        testcase( pFirstTerm->eOperator==WO_EQ );
105687        testcase( pFirstTerm->eOperator==WO_ISNULL );
105688        whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight, &nRow);
105689      }else if( bInEst==0 ){
105690        assert( pFirstTerm->eOperator==WO_IN );
105691        whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList, &nRow);
105692      }
105693    }
105694#endif /* SQLITE_ENABLE_STAT3 */
105695
105696    /* Adjust the number of output rows and downward to reflect rows
105697    ** that are excluded by range constraints.
105698    */
105699    nRow = nRow/rangeDiv;
105700    if( nRow<1 ) nRow = 1;
105701
105702    /* Experiments run on real SQLite databases show that the time needed
105703    ** to do a binary search to locate a row in a table or index is roughly
105704    ** log10(N) times the time to move from one row to the next row within
105705    ** a table or index.  The actual times can vary, with the size of
105706    ** records being an important factor.  Both moves and searches are
105707    ** slower with larger records, presumably because fewer records fit
105708    ** on one page and hence more pages have to be fetched.
105709    **
105710    ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
105711    ** not give us data on the relative sizes of table and index records.
105712    ** So this computation assumes table records are about twice as big
105713    ** as index records
105714    */
105715    if( (wsFlags & WHERE_NOT_FULLSCAN)==0 ){
105716      /* The cost of a full table scan is a number of move operations equal
105717      ** to the number of rows in the table.
105718      **
105719      ** We add an additional 4x penalty to full table scans.  This causes
105720      ** the cost function to err on the side of choosing an index over
105721      ** choosing a full scan.  This 4x full-scan penalty is an arguable
105722      ** decision and one which we expect to revisit in the future.  But
105723      ** it seems to be working well enough at the moment.
105724      */
105725      cost = aiRowEst[0]*4;
105726    }else{
105727      log10N = estLog(aiRowEst[0]);
105728      cost = nRow;
105729      if( pIdx ){
105730        if( bLookup ){
105731          /* For an index lookup followed by a table lookup:
105732          **    nInMul index searches to find the start of each index range
105733          **  + nRow steps through the index
105734          **  + nRow table searches to lookup the table entry using the rowid
105735          */
105736          cost += (nInMul + nRow)*log10N;
105737        }else{
105738          /* For a covering index:
105739          **     nInMul index searches to find the initial entry
105740          **   + nRow steps through the index
105741          */
105742          cost += nInMul*log10N;
105743        }
105744      }else{
105745        /* For a rowid primary key lookup:
105746        **    nInMult table searches to find the initial entry for each range
105747        **  + nRow steps through the table
105748        */
105749        cost += nInMul*log10N;
105750      }
105751    }
105752
105753    /* Add in the estimated cost of sorting the result.  Actual experimental
105754    ** measurements of sorting performance in SQLite show that sorting time
105755    ** adds C*N*log10(N) to the cost, where N is the number of rows to be
105756    ** sorted and C is a factor between 1.95 and 4.3.  We will split the
105757    ** difference and select C of 3.0.
105758    */
105759    if( bSort ){
105760      cost += nRow*estLog(nRow)*3;
105761    }
105762    if( bDist ){
105763      cost += nRow*estLog(nRow)*3;
105764    }
105765
105766    /**** Cost of using this index has now been computed ****/
105767
105768    /* If there are additional constraints on this table that cannot
105769    ** be used with the current index, but which might lower the number
105770    ** of output rows, adjust the nRow value accordingly.  This only
105771    ** matters if the current index is the least costly, so do not bother
105772    ** with this step if we already know this index will not be chosen.
105773    ** Also, never reduce the output row count below 2 using this step.
105774    **
105775    ** It is critical that the notValid mask be used here instead of
105776    ** the notReady mask.  When computing an "optimal" index, the notReady
105777    ** mask will only have one bit set - the bit for the current table.
105778    ** The notValid mask, on the other hand, always has all bits set for
105779    ** tables that are not in outer loops.  If notReady is used here instead
105780    ** of notValid, then a optimal index that depends on inner joins loops
105781    ** might be selected even when there exists an optimal index that has
105782    ** no such dependency.
105783    */
105784    if( nRow>2 && cost<=pCost->rCost ){
105785      int k;                       /* Loop counter */
105786      int nSkipEq = nEq;           /* Number of == constraints to skip */
105787      int nSkipRange = nBound;     /* Number of < constraints to skip */
105788      Bitmask thisTab;             /* Bitmap for pSrc */
105789
105790      thisTab = getMask(pWC->pMaskSet, iCur);
105791      for(pTerm=pWC->a, k=pWC->nTerm; nRow>2 && k; k--, pTerm++){
105792        if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
105793        if( (pTerm->prereqAll & notValid)!=thisTab ) continue;
105794        if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
105795          if( nSkipEq ){
105796            /* Ignore the first nEq equality matches since the index
105797            ** has already accounted for these */
105798            nSkipEq--;
105799          }else{
105800            /* Assume each additional equality match reduces the result
105801            ** set size by a factor of 10 */
105802            nRow /= 10;
105803          }
105804        }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
105805          if( nSkipRange ){
105806            /* Ignore the first nSkipRange range constraints since the index
105807            ** has already accounted for these */
105808            nSkipRange--;
105809          }else{
105810            /* Assume each additional range constraint reduces the result
105811            ** set size by a factor of 3.  Indexed range constraints reduce
105812            ** the search space by a larger factor: 4.  We make indexed range
105813            ** more selective intentionally because of the subjective
105814            ** observation that indexed range constraints really are more
105815            ** selective in practice, on average. */
105816            nRow /= 3;
105817          }
105818        }else if( pTerm->eOperator!=WO_NOOP ){
105819          /* Any other expression lowers the output row count by half */
105820          nRow /= 2;
105821        }
105822      }
105823      if( nRow<2 ) nRow = 2;
105824    }
105825
105826
105827    WHERETRACE((
105828      "%s(%s): nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%x\n"
105829      "         notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f used=0x%llx\n",
105830      pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"),
105831      nEq, nInMul, (int)rangeDiv, bSort, bLookup, wsFlags,
105832      notReady, log10N, nRow, cost, used
105833    ));
105834
105835    /* If this index is the best we have seen so far, then record this
105836    ** index and its cost in the pCost structure.
105837    */
105838    if( (!pIdx || wsFlags)
105839     && (cost<pCost->rCost || (cost<=pCost->rCost && nRow<pCost->plan.nRow))
105840    ){
105841      pCost->rCost = cost;
105842      pCost->used = used;
105843      pCost->plan.nRow = nRow;
105844      pCost->plan.wsFlags = (wsFlags&wsFlagMask);
105845      pCost->plan.nEq = nEq;
105846      pCost->plan.u.pIdx = pIdx;
105847    }
105848
105849    /* If there was an INDEXED BY clause, then only that one index is
105850    ** considered. */
105851    if( pSrc->pIndex ) break;
105852
105853    /* Reset masks for the next index in the loop */
105854    wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
105855    eqTermMask = idxEqTermMask;
105856  }
105857
105858  /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
105859  ** is set, then reverse the order that the index will be scanned
105860  ** in. This is used for application testing, to help find cases
105861  ** where application behaviour depends on the (undefined) order that
105862  ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
105863  if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
105864    pCost->plan.wsFlags |= WHERE_REVERSE;
105865  }
105866
105867  assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
105868  assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
105869  assert( pSrc->pIndex==0
105870       || pCost->plan.u.pIdx==0
105871       || pCost->plan.u.pIdx==pSrc->pIndex
105872  );
105873
105874  WHERETRACE(("best index is: %s\n",
105875    ((pCost->plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ? "none" :
105876         pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
105877  ));
105878
105879  bestOrClauseIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost);
105880  bestAutomaticIndex(pParse, pWC, pSrc, notReady, pCost);
105881  pCost->plan.wsFlags |= eqTermMask;
105882}
105883
105884/*
105885** Find the query plan for accessing table pSrc->pTab. Write the
105886** best query plan and its cost into the WhereCost object supplied
105887** as the last parameter. This function may calculate the cost of
105888** both real and virtual table scans.
105889*/
105890static void bestIndex(
105891  Parse *pParse,              /* The parsing context */
105892  WhereClause *pWC,           /* The WHERE clause */
105893  struct SrcList_item *pSrc,  /* The FROM clause term to search */
105894  Bitmask notReady,           /* Mask of cursors not available for indexing */
105895  Bitmask notValid,           /* Cursors not available for any purpose */
105896  ExprList *pOrderBy,         /* The ORDER BY clause */
105897  WhereCost *pCost            /* Lowest cost query plan */
105898){
105899#ifndef SQLITE_OMIT_VIRTUALTABLE
105900  if( IsVirtual(pSrc->pTab) ){
105901    sqlite3_index_info *p = 0;
105902    bestVirtualIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, pCost,&p);
105903    if( p->needToFreeIdxStr ){
105904      sqlite3_free(p->idxStr);
105905    }
105906    sqlite3DbFree(pParse->db, p);
105907  }else
105908#endif
105909  {
105910    bestBtreeIndex(pParse, pWC, pSrc, notReady, notValid, pOrderBy, 0, pCost);
105911  }
105912}
105913
105914/*
105915** Disable a term in the WHERE clause.  Except, do not disable the term
105916** if it controls a LEFT OUTER JOIN and it did not originate in the ON
105917** or USING clause of that join.
105918**
105919** Consider the term t2.z='ok' in the following queries:
105920**
105921**   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
105922**   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
105923**   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
105924**
105925** The t2.z='ok' is disabled in the in (2) because it originates
105926** in the ON clause.  The term is disabled in (3) because it is not part
105927** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
105928**
105929** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
105930** completely satisfied by indices.
105931**
105932** Disabling a term causes that term to not be tested in the inner loop
105933** of the join.  Disabling is an optimization.  When terms are satisfied
105934** by indices, we disable them to prevent redundant tests in the inner
105935** loop.  We would get the correct results if nothing were ever disabled,
105936** but joins might run a little slower.  The trick is to disable as much
105937** as we can without disabling too much.  If we disabled in (1), we'd get
105938** the wrong answer.  See ticket #813.
105939*/
105940static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
105941  if( pTerm
105942      && (pTerm->wtFlags & TERM_CODED)==0
105943      && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
105944  ){
105945    pTerm->wtFlags |= TERM_CODED;
105946    if( pTerm->iParent>=0 ){
105947      WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
105948      if( (--pOther->nChild)==0 ){
105949        disableTerm(pLevel, pOther);
105950      }
105951    }
105952  }
105953}
105954
105955/*
105956** Code an OP_Affinity opcode to apply the column affinity string zAff
105957** to the n registers starting at base.
105958**
105959** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
105960** beginning and end of zAff are ignored.  If all entries in zAff are
105961** SQLITE_AFF_NONE, then no code gets generated.
105962**
105963** This routine makes its own copy of zAff so that the caller is free
105964** to modify zAff after this routine returns.
105965*/
105966static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
105967  Vdbe *v = pParse->pVdbe;
105968  if( zAff==0 ){
105969    assert( pParse->db->mallocFailed );
105970    return;
105971  }
105972  assert( v!=0 );
105973
105974  /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
105975  ** and end of the affinity string.
105976  */
105977  while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
105978    n--;
105979    base++;
105980    zAff++;
105981  }
105982  while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
105983    n--;
105984  }
105985
105986  /* Code the OP_Affinity opcode if there is anything left to do. */
105987  if( n>0 ){
105988    sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
105989    sqlite3VdbeChangeP4(v, -1, zAff, n);
105990    sqlite3ExprCacheAffinityChange(pParse, base, n);
105991  }
105992}
105993
105994
105995/*
105996** Generate code for a single equality term of the WHERE clause.  An equality
105997** term can be either X=expr or X IN (...).   pTerm is the term to be
105998** coded.
105999**
106000** The current value for the constraint is left in register iReg.
106001**
106002** For a constraint of the form X=expr, the expression is evaluated and its
106003** result is left on the stack.  For constraints of the form X IN (...)
106004** this routine sets up a loop that will iterate over all values of X.
106005*/
106006static int codeEqualityTerm(
106007  Parse *pParse,      /* The parsing context */
106008  WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
106009  WhereLevel *pLevel, /* When level of the FROM clause we are working on */
106010  int iTarget         /* Attempt to leave results in this register */
106011){
106012  Expr *pX = pTerm->pExpr;
106013  Vdbe *v = pParse->pVdbe;
106014  int iReg;                  /* Register holding results */
106015
106016  assert( iTarget>0 );
106017  if( pX->op==TK_EQ ){
106018    iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
106019  }else if( pX->op==TK_ISNULL ){
106020    iReg = iTarget;
106021    sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
106022#ifndef SQLITE_OMIT_SUBQUERY
106023  }else{
106024    int eType;
106025    int iTab;
106026    struct InLoop *pIn;
106027
106028    assert( pX->op==TK_IN );
106029    iReg = iTarget;
106030    eType = sqlite3FindInIndex(pParse, pX, 0);
106031    iTab = pX->iTable;
106032    sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
106033    assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
106034    if( pLevel->u.in.nIn==0 ){
106035      pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
106036    }
106037    pLevel->u.in.nIn++;
106038    pLevel->u.in.aInLoop =
106039       sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
106040                              sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
106041    pIn = pLevel->u.in.aInLoop;
106042    if( pIn ){
106043      pIn += pLevel->u.in.nIn - 1;
106044      pIn->iCur = iTab;
106045      if( eType==IN_INDEX_ROWID ){
106046        pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
106047      }else{
106048        pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
106049      }
106050      sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
106051    }else{
106052      pLevel->u.in.nIn = 0;
106053    }
106054#endif
106055  }
106056  disableTerm(pLevel, pTerm);
106057  return iReg;
106058}
106059
106060/*
106061** Generate code that will evaluate all == and IN constraints for an
106062** index.
106063**
106064** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
106065** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
106066** The index has as many as three equality constraints, but in this
106067** example, the third "c" value is an inequality.  So only two
106068** constraints are coded.  This routine will generate code to evaluate
106069** a==5 and b IN (1,2,3).  The current values for a and b will be stored
106070** in consecutive registers and the index of the first register is returned.
106071**
106072** In the example above nEq==2.  But this subroutine works for any value
106073** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
106074** The only thing it does is allocate the pLevel->iMem memory cell and
106075** compute the affinity string.
106076**
106077** This routine always allocates at least one memory cell and returns
106078** the index of that memory cell. The code that
106079** calls this routine will use that memory cell to store the termination
106080** key value of the loop.  If one or more IN operators appear, then
106081** this routine allocates an additional nEq memory cells for internal
106082** use.
106083**
106084** Before returning, *pzAff is set to point to a buffer containing a
106085** copy of the column affinity string of the index allocated using
106086** sqlite3DbMalloc(). Except, entries in the copy of the string associated
106087** with equality constraints that use NONE affinity are set to
106088** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
106089**
106090**   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
106091**   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
106092**
106093** In the example above, the index on t1(a) has TEXT affinity. But since
106094** the right hand side of the equality constraint (t2.b) has NONE affinity,
106095** no conversion should be attempted before using a t2.b value as part of
106096** a key to search the index. Hence the first byte in the returned affinity
106097** string in this example would be set to SQLITE_AFF_NONE.
106098*/
106099static int codeAllEqualityTerms(
106100  Parse *pParse,        /* Parsing context */
106101  WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
106102  WhereClause *pWC,     /* The WHERE clause */
106103  Bitmask notReady,     /* Which parts of FROM have not yet been coded */
106104  int nExtraReg,        /* Number of extra registers to allocate */
106105  char **pzAff          /* OUT: Set to point to affinity string */
106106){
106107  int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
106108  Vdbe *v = pParse->pVdbe;      /* The vm under construction */
106109  Index *pIdx;                  /* The index being used for this loop */
106110  int iCur = pLevel->iTabCur;   /* The cursor of the table */
106111  WhereTerm *pTerm;             /* A single constraint term */
106112  int j;                        /* Loop counter */
106113  int regBase;                  /* Base register */
106114  int nReg;                     /* Number of registers to allocate */
106115  char *zAff;                   /* Affinity string to return */
106116
106117  /* This module is only called on query plans that use an index. */
106118  assert( pLevel->plan.wsFlags & WHERE_INDEXED );
106119  pIdx = pLevel->plan.u.pIdx;
106120
106121  /* Figure out how many memory cells we will need then allocate them.
106122  */
106123  regBase = pParse->nMem + 1;
106124  nReg = pLevel->plan.nEq + nExtraReg;
106125  pParse->nMem += nReg;
106126
106127  zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
106128  if( !zAff ){
106129    pParse->db->mallocFailed = 1;
106130  }
106131
106132  /* Evaluate the equality constraints
106133  */
106134  assert( pIdx->nColumn>=nEq );
106135  for(j=0; j<nEq; j++){
106136    int r1;
106137    int k = pIdx->aiColumn[j];
106138    pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
106139    if( NEVER(pTerm==0) ) break;
106140    /* The following true for indices with redundant columns.
106141    ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
106142    testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
106143    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106144    r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
106145    if( r1!=regBase+j ){
106146      if( nReg==1 ){
106147        sqlite3ReleaseTempReg(pParse, regBase);
106148        regBase = r1;
106149      }else{
106150        sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
106151      }
106152    }
106153    testcase( pTerm->eOperator & WO_ISNULL );
106154    testcase( pTerm->eOperator & WO_IN );
106155    if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
106156      Expr *pRight = pTerm->pExpr->pRight;
106157      sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
106158      if( zAff ){
106159        if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
106160          zAff[j] = SQLITE_AFF_NONE;
106161        }
106162        if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
106163          zAff[j] = SQLITE_AFF_NONE;
106164        }
106165      }
106166    }
106167  }
106168  *pzAff = zAff;
106169  return regBase;
106170}
106171
106172#ifndef SQLITE_OMIT_EXPLAIN
106173/*
106174** This routine is a helper for explainIndexRange() below
106175**
106176** pStr holds the text of an expression that we are building up one term
106177** at a time.  This routine adds a new term to the end of the expression.
106178** Terms are separated by AND so add the "AND" text for second and subsequent
106179** terms only.
106180*/
106181static void explainAppendTerm(
106182  StrAccum *pStr,             /* The text expression being built */
106183  int iTerm,                  /* Index of this term.  First is zero */
106184  const char *zColumn,        /* Name of the column */
106185  const char *zOp             /* Name of the operator */
106186){
106187  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
106188  sqlite3StrAccumAppend(pStr, zColumn, -1);
106189  sqlite3StrAccumAppend(pStr, zOp, 1);
106190  sqlite3StrAccumAppend(pStr, "?", 1);
106191}
106192
106193/*
106194** Argument pLevel describes a strategy for scanning table pTab. This
106195** function returns a pointer to a string buffer containing a description
106196** of the subset of table rows scanned by the strategy in the form of an
106197** SQL expression. Or, if all rows are scanned, NULL is returned.
106198**
106199** For example, if the query:
106200**
106201**   SELECT * FROM t1 WHERE a=1 AND b>2;
106202**
106203** is run and there is an index on (a, b), then this function returns a
106204** string similar to:
106205**
106206**   "a=? AND b>?"
106207**
106208** The returned pointer points to memory obtained from sqlite3DbMalloc().
106209** It is the responsibility of the caller to free the buffer when it is
106210** no longer required.
106211*/
106212static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
106213  WherePlan *pPlan = &pLevel->plan;
106214  Index *pIndex = pPlan->u.pIdx;
106215  int nEq = pPlan->nEq;
106216  int i, j;
106217  Column *aCol = pTab->aCol;
106218  int *aiColumn = pIndex->aiColumn;
106219  StrAccum txt;
106220
106221  if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
106222    return 0;
106223  }
106224  sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
106225  txt.db = db;
106226  sqlite3StrAccumAppend(&txt, " (", 2);
106227  for(i=0; i<nEq; i++){
106228    explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
106229  }
106230
106231  j = i;
106232  if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
106233    char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
106234    explainAppendTerm(&txt, i++, z, ">");
106235  }
106236  if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
106237    char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
106238    explainAppendTerm(&txt, i, z, "<");
106239  }
106240  sqlite3StrAccumAppend(&txt, ")", 1);
106241  return sqlite3StrAccumFinish(&txt);
106242}
106243
106244/*
106245** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
106246** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
106247** record is added to the output to describe the table scan strategy in
106248** pLevel.
106249*/
106250static void explainOneScan(
106251  Parse *pParse,                  /* Parse context */
106252  SrcList *pTabList,              /* Table list this loop refers to */
106253  WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
106254  int iLevel,                     /* Value for "level" column of output */
106255  int iFrom,                      /* Value for "from" column of output */
106256  u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
106257){
106258  if( pParse->explain==2 ){
106259    u32 flags = pLevel->plan.wsFlags;
106260    struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
106261    Vdbe *v = pParse->pVdbe;      /* VM being constructed */
106262    sqlite3 *db = pParse->db;     /* Database handle */
106263    char *zMsg;                   /* Text to add to EQP output */
106264    sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
106265    int iId = pParse->iSelectId;  /* Select id (left-most output column) */
106266    int isSearch;                 /* True for a SEARCH. False for SCAN. */
106267
106268    if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
106269
106270    isSearch = (pLevel->plan.nEq>0)
106271             || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
106272             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
106273
106274    zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
106275    if( pItem->pSelect ){
106276      zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
106277    }else{
106278      zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
106279    }
106280
106281    if( pItem->zAlias ){
106282      zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
106283    }
106284    if( (flags & WHERE_INDEXED)!=0 ){
106285      char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
106286      zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg,
106287          ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
106288          ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
106289          ((flags & WHERE_TEMP_INDEX)?"":" "),
106290          ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
106291          zWhere
106292      );
106293      sqlite3DbFree(db, zWhere);
106294    }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
106295      zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
106296
106297      if( flags&WHERE_ROWID_EQ ){
106298        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
106299      }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
106300        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
106301      }else if( flags&WHERE_BTM_LIMIT ){
106302        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
106303      }else if( flags&WHERE_TOP_LIMIT ){
106304        zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
106305      }
106306    }
106307#ifndef SQLITE_OMIT_VIRTUALTABLE
106308    else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
106309      sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
106310      zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
106311                  pVtabIdx->idxNum, pVtabIdx->idxStr);
106312    }
106313#endif
106314    if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
106315      testcase( wctrlFlags & WHERE_ORDERBY_MIN );
106316      nRow = 1;
106317    }else{
106318      nRow = (sqlite3_int64)pLevel->plan.nRow;
106319    }
106320    zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
106321    sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
106322  }
106323}
106324#else
106325# define explainOneScan(u,v,w,x,y,z)
106326#endif /* SQLITE_OMIT_EXPLAIN */
106327
106328
106329/*
106330** Generate code for the start of the iLevel-th loop in the WHERE clause
106331** implementation described by pWInfo.
106332*/
106333static Bitmask codeOneLoopStart(
106334  WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
106335  int iLevel,          /* Which level of pWInfo->a[] should be coded */
106336  u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
106337  Bitmask notReady     /* Which tables are currently available */
106338){
106339  int j, k;            /* Loop counters */
106340  int iCur;            /* The VDBE cursor for the table */
106341  int addrNxt;         /* Where to jump to continue with the next IN case */
106342  int omitTable;       /* True if we use the index only */
106343  int bRev;            /* True if we need to scan in reverse order */
106344  WhereLevel *pLevel;  /* The where level to be coded */
106345  WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
106346  WhereTerm *pTerm;               /* A WHERE clause term */
106347  Parse *pParse;                  /* Parsing context */
106348  Vdbe *v;                        /* The prepared stmt under constructions */
106349  struct SrcList_item *pTabItem;  /* FROM clause term being coded */
106350  int addrBrk;                    /* Jump here to break out of the loop */
106351  int addrCont;                   /* Jump here to continue with next cycle */
106352  int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
106353  int iReleaseReg = 0;      /* Temp register to free before returning */
106354
106355  pParse = pWInfo->pParse;
106356  v = pParse->pVdbe;
106357  pWC = pWInfo->pWC;
106358  pLevel = &pWInfo->a[iLevel];
106359  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
106360  iCur = pTabItem->iCursor;
106361  bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
106362  omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0
106363           && (wctrlFlags & WHERE_FORCE_TABLE)==0;
106364
106365  /* Create labels for the "break" and "continue" instructions
106366  ** for the current loop.  Jump to addrBrk to break out of a loop.
106367  ** Jump to cont to go immediately to the next iteration of the
106368  ** loop.
106369  **
106370  ** When there is an IN operator, we also have a "addrNxt" label that
106371  ** means to continue with the next IN value combination.  When
106372  ** there are no IN operators in the constraints, the "addrNxt" label
106373  ** is the same as "addrBrk".
106374  */
106375  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
106376  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
106377
106378  /* If this is the right table of a LEFT OUTER JOIN, allocate and
106379  ** initialize a memory cell that records if this table matches any
106380  ** row of the left table of the join.
106381  */
106382  if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
106383    pLevel->iLeftJoin = ++pParse->nMem;
106384    sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
106385    VdbeComment((v, "init LEFT JOIN no-match flag"));
106386  }
106387
106388#ifndef SQLITE_OMIT_VIRTUALTABLE
106389  if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
106390    /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
106391    **          to access the data.
106392    */
106393    int iReg;   /* P3 Value for OP_VFilter */
106394    sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
106395    int nConstraint = pVtabIdx->nConstraint;
106396    struct sqlite3_index_constraint_usage *aUsage =
106397                                                pVtabIdx->aConstraintUsage;
106398    const struct sqlite3_index_constraint *aConstraint =
106399                                                pVtabIdx->aConstraint;
106400
106401    sqlite3ExprCachePush(pParse);
106402    iReg = sqlite3GetTempRange(pParse, nConstraint+2);
106403    for(j=1; j<=nConstraint; j++){
106404      for(k=0; k<nConstraint; k++){
106405        if( aUsage[k].argvIndex==j ){
106406          int iTerm = aConstraint[k].iTermOffset;
106407          sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
106408          break;
106409        }
106410      }
106411      if( k==nConstraint ) break;
106412    }
106413    sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
106414    sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
106415    sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
106416                      pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
106417    pVtabIdx->needToFreeIdxStr = 0;
106418    for(j=0; j<nConstraint; j++){
106419      if( aUsage[j].omit ){
106420        int iTerm = aConstraint[j].iTermOffset;
106421        disableTerm(pLevel, &pWC->a[iTerm]);
106422      }
106423    }
106424    pLevel->op = OP_VNext;
106425    pLevel->p1 = iCur;
106426    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
106427    sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
106428    sqlite3ExprCachePop(pParse, 1);
106429  }else
106430#endif /* SQLITE_OMIT_VIRTUALTABLE */
106431
106432  if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
106433    /* Case 1:  We can directly reference a single row using an
106434    **          equality comparison against the ROWID field.  Or
106435    **          we reference multiple rows using a "rowid IN (...)"
106436    **          construct.
106437    */
106438    iReleaseReg = sqlite3GetTempReg(pParse);
106439    pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
106440    assert( pTerm!=0 );
106441    assert( pTerm->pExpr!=0 );
106442    assert( pTerm->leftCursor==iCur );
106443    assert( omitTable==0 );
106444    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106445    iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
106446    addrNxt = pLevel->addrNxt;
106447    sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
106448    sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
106449    sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106450    VdbeComment((v, "pk"));
106451    pLevel->op = OP_Noop;
106452  }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
106453    /* Case 2:  We have an inequality comparison against the ROWID field.
106454    */
106455    int testOp = OP_Noop;
106456    int start;
106457    int memEndValue = 0;
106458    WhereTerm *pStart, *pEnd;
106459
106460    assert( omitTable==0 );
106461    pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
106462    pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
106463    if( bRev ){
106464      pTerm = pStart;
106465      pStart = pEnd;
106466      pEnd = pTerm;
106467    }
106468    if( pStart ){
106469      Expr *pX;             /* The expression that defines the start bound */
106470      int r1, rTemp;        /* Registers for holding the start boundary */
106471
106472      /* The following constant maps TK_xx codes into corresponding
106473      ** seek opcodes.  It depends on a particular ordering of TK_xx
106474      */
106475      const u8 aMoveOp[] = {
106476           /* TK_GT */  OP_SeekGt,
106477           /* TK_LE */  OP_SeekLe,
106478           /* TK_LT */  OP_SeekLt,
106479           /* TK_GE */  OP_SeekGe
106480      };
106481      assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
106482      assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
106483      assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
106484
106485      testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106486      pX = pStart->pExpr;
106487      assert( pX!=0 );
106488      assert( pStart->leftCursor==iCur );
106489      r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
106490      sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
106491      VdbeComment((v, "pk"));
106492      sqlite3ExprCacheAffinityChange(pParse, r1, 1);
106493      sqlite3ReleaseTempReg(pParse, rTemp);
106494      disableTerm(pLevel, pStart);
106495    }else{
106496      sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
106497    }
106498    if( pEnd ){
106499      Expr *pX;
106500      pX = pEnd->pExpr;
106501      assert( pX!=0 );
106502      assert( pEnd->leftCursor==iCur );
106503      testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106504      memEndValue = ++pParse->nMem;
106505      sqlite3ExprCode(pParse, pX->pRight, memEndValue);
106506      if( pX->op==TK_LT || pX->op==TK_GT ){
106507        testOp = bRev ? OP_Le : OP_Ge;
106508      }else{
106509        testOp = bRev ? OP_Lt : OP_Gt;
106510      }
106511      disableTerm(pLevel, pEnd);
106512    }
106513    start = sqlite3VdbeCurrentAddr(v);
106514    pLevel->op = bRev ? OP_Prev : OP_Next;
106515    pLevel->p1 = iCur;
106516    pLevel->p2 = start;
106517    if( pStart==0 && pEnd==0 ){
106518      pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
106519    }else{
106520      assert( pLevel->p5==0 );
106521    }
106522    if( testOp!=OP_Noop ){
106523      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
106524      sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
106525      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106526      sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
106527      sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
106528    }
106529  }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
106530    /* Case 3: A scan using an index.
106531    **
106532    **         The WHERE clause may contain zero or more equality
106533    **         terms ("==" or "IN" operators) that refer to the N
106534    **         left-most columns of the index. It may also contain
106535    **         inequality constraints (>, <, >= or <=) on the indexed
106536    **         column that immediately follows the N equalities. Only
106537    **         the right-most column can be an inequality - the rest must
106538    **         use the "==" and "IN" operators. For example, if the
106539    **         index is on (x,y,z), then the following clauses are all
106540    **         optimized:
106541    **
106542    **            x=5
106543    **            x=5 AND y=10
106544    **            x=5 AND y<10
106545    **            x=5 AND y>5 AND y<10
106546    **            x=5 AND y=5 AND z<=10
106547    **
106548    **         The z<10 term of the following cannot be used, only
106549    **         the x=5 term:
106550    **
106551    **            x=5 AND z<10
106552    **
106553    **         N may be zero if there are inequality constraints.
106554    **         If there are no inequality constraints, then N is at
106555    **         least one.
106556    **
106557    **         This case is also used when there are no WHERE clause
106558    **         constraints but an index is selected anyway, in order
106559    **         to force the output order to conform to an ORDER BY.
106560    */
106561    static const u8 aStartOp[] = {
106562      0,
106563      0,
106564      OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
106565      OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
106566      OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
106567      OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
106568      OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
106569      OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
106570    };
106571    static const u8 aEndOp[] = {
106572      OP_Noop,             /* 0: (!end_constraints) */
106573      OP_IdxGE,            /* 1: (end_constraints && !bRev) */
106574      OP_IdxLT             /* 2: (end_constraints && bRev) */
106575    };
106576    int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
106577    int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
106578    int regBase;                 /* Base register holding constraint values */
106579    int r1;                      /* Temp register */
106580    WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
106581    WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
106582    int startEq;                 /* True if range start uses ==, >= or <= */
106583    int endEq;                   /* True if range end uses ==, >= or <= */
106584    int start_constraints;       /* Start of range is constrained */
106585    int nConstraint;             /* Number of constraint terms */
106586    Index *pIdx;                 /* The index we will be using */
106587    int iIdxCur;                 /* The VDBE cursor for the index */
106588    int nExtraReg = 0;           /* Number of extra registers needed */
106589    int op;                      /* Instruction opcode */
106590    char *zStartAff;             /* Affinity for start of range constraint */
106591    char *zEndAff;               /* Affinity for end of range constraint */
106592
106593    pIdx = pLevel->plan.u.pIdx;
106594    iIdxCur = pLevel->iIdxCur;
106595    k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
106596
106597    /* If this loop satisfies a sort order (pOrderBy) request that
106598    ** was passed to this function to implement a "SELECT min(x) ..."
106599    ** query, then the caller will only allow the loop to run for
106600    ** a single iteration. This means that the first row returned
106601    ** should not have a NULL value stored in 'x'. If column 'x' is
106602    ** the first one after the nEq equality constraints in the index,
106603    ** this requires some special handling.
106604    */
106605    if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
106606     && (pLevel->plan.wsFlags&WHERE_ORDERBY)
106607     && (pIdx->nColumn>nEq)
106608    ){
106609      /* assert( pOrderBy->nExpr==1 ); */
106610      /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
106611      isMinQuery = 1;
106612      nExtraReg = 1;
106613    }
106614
106615    /* Find any inequality constraint terms for the start and end
106616    ** of the range.
106617    */
106618    if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
106619      pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
106620      nExtraReg = 1;
106621    }
106622    if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
106623      pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
106624      nExtraReg = 1;
106625    }
106626
106627    /* Generate code to evaluate all constraint terms using == or IN
106628    ** and store the values of those terms in an array of registers
106629    ** starting at regBase.
106630    */
106631    regBase = codeAllEqualityTerms(
106632        pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
106633    );
106634    zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
106635    addrNxt = pLevel->addrNxt;
106636
106637    /* If we are doing a reverse order scan on an ascending index, or
106638    ** a forward order scan on a descending index, interchange the
106639    ** start and end terms (pRangeStart and pRangeEnd).
106640    */
106641    if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
106642     || (bRev && pIdx->nColumn==nEq)
106643    ){
106644      SWAP(WhereTerm *, pRangeEnd, pRangeStart);
106645    }
106646
106647    testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
106648    testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
106649    testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
106650    testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
106651    startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
106652    endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
106653    start_constraints = pRangeStart || nEq>0;
106654
106655    /* Seek the index cursor to the start of the range. */
106656    nConstraint = nEq;
106657    if( pRangeStart ){
106658      Expr *pRight = pRangeStart->pExpr->pRight;
106659      sqlite3ExprCode(pParse, pRight, regBase+nEq);
106660      if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
106661        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106662      }
106663      if( zStartAff ){
106664        if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
106665          /* Since the comparison is to be performed with no conversions
106666          ** applied to the operands, set the affinity to apply to pRight to
106667          ** SQLITE_AFF_NONE.  */
106668          zStartAff[nEq] = SQLITE_AFF_NONE;
106669        }
106670        if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
106671          zStartAff[nEq] = SQLITE_AFF_NONE;
106672        }
106673      }
106674      nConstraint++;
106675      testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106676    }else if( isMinQuery ){
106677      sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
106678      nConstraint++;
106679      startEq = 0;
106680      start_constraints = 1;
106681    }
106682    codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
106683    op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
106684    assert( op!=0 );
106685    testcase( op==OP_Rewind );
106686    testcase( op==OP_Last );
106687    testcase( op==OP_SeekGt );
106688    testcase( op==OP_SeekGe );
106689    testcase( op==OP_SeekLe );
106690    testcase( op==OP_SeekLt );
106691    sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106692
106693    /* Load the value for the inequality constraint at the end of the
106694    ** range (if any).
106695    */
106696    nConstraint = nEq;
106697    if( pRangeEnd ){
106698      Expr *pRight = pRangeEnd->pExpr->pRight;
106699      sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
106700      sqlite3ExprCode(pParse, pRight, regBase+nEq);
106701      if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
106702        sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
106703      }
106704      if( zEndAff ){
106705        if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
106706          /* Since the comparison is to be performed with no conversions
106707          ** applied to the operands, set the affinity to apply to pRight to
106708          ** SQLITE_AFF_NONE.  */
106709          zEndAff[nEq] = SQLITE_AFF_NONE;
106710        }
106711        if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
106712          zEndAff[nEq] = SQLITE_AFF_NONE;
106713        }
106714      }
106715      codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
106716      nConstraint++;
106717      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
106718    }
106719    sqlite3DbFree(pParse->db, zStartAff);
106720    sqlite3DbFree(pParse->db, zEndAff);
106721
106722    /* Top of the loop body */
106723    pLevel->p2 = sqlite3VdbeCurrentAddr(v);
106724
106725    /* Check if the index cursor is past the end of the range. */
106726    op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
106727    testcase( op==OP_Noop );
106728    testcase( op==OP_IdxGE );
106729    testcase( op==OP_IdxLT );
106730    if( op!=OP_Noop ){
106731      sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
106732      sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
106733    }
106734
106735    /* If there are inequality constraints, check that the value
106736    ** of the table column that the inequality contrains is not NULL.
106737    ** If it is, jump to the next iteration of the loop.
106738    */
106739    r1 = sqlite3GetTempReg(pParse);
106740    testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
106741    testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
106742    if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
106743      sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
106744      sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
106745    }
106746    sqlite3ReleaseTempReg(pParse, r1);
106747
106748    /* Seek the table cursor, if required */
106749    disableTerm(pLevel, pRangeStart);
106750    disableTerm(pLevel, pRangeEnd);
106751    if( !omitTable ){
106752      iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
106753      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
106754      sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
106755      sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
106756    }
106757
106758    /* Record the instruction used to terminate the loop. Disable
106759    ** WHERE clause terms made redundant by the index range scan.
106760    */
106761    if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
106762      pLevel->op = OP_Noop;
106763    }else if( bRev ){
106764      pLevel->op = OP_Prev;
106765    }else{
106766      pLevel->op = OP_Next;
106767    }
106768    pLevel->p1 = iIdxCur;
106769  }else
106770
106771#ifndef SQLITE_OMIT_OR_OPTIMIZATION
106772  if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
106773    /* Case 4:  Two or more separately indexed terms connected by OR
106774    **
106775    ** Example:
106776    **
106777    **   CREATE TABLE t1(a,b,c,d);
106778    **   CREATE INDEX i1 ON t1(a);
106779    **   CREATE INDEX i2 ON t1(b);
106780    **   CREATE INDEX i3 ON t1(c);
106781    **
106782    **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
106783    **
106784    ** In the example, there are three indexed terms connected by OR.
106785    ** The top of the loop looks like this:
106786    **
106787    **          Null       1                # Zero the rowset in reg 1
106788    **
106789    ** Then, for each indexed term, the following. The arguments to
106790    ** RowSetTest are such that the rowid of the current row is inserted
106791    ** into the RowSet. If it is already present, control skips the
106792    ** Gosub opcode and jumps straight to the code generated by WhereEnd().
106793    **
106794    **        sqlite3WhereBegin(<term>)
106795    **          RowSetTest                  # Insert rowid into rowset
106796    **          Gosub      2 A
106797    **        sqlite3WhereEnd()
106798    **
106799    ** Following the above, code to terminate the loop. Label A, the target
106800    ** of the Gosub above, jumps to the instruction right after the Goto.
106801    **
106802    **          Null       1                # Zero the rowset in reg 1
106803    **          Goto       B                # The loop is finished.
106804    **
106805    **       A: <loop body>                 # Return data, whatever.
106806    **
106807    **          Return     2                # Jump back to the Gosub
106808    **
106809    **       B: <after the loop>
106810    **
106811    */
106812    WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
106813    SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
106814
106815    int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
106816    int regRowset = 0;                        /* Register for RowSet object */
106817    int regRowid = 0;                         /* Register holding rowid */
106818    int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
106819    int iRetInit;                             /* Address of regReturn init */
106820    int untestedTerms = 0;             /* Some terms not completely tested */
106821    int ii;                            /* Loop counter */
106822    Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
106823
106824    pTerm = pLevel->plan.u.pTerm;
106825    assert( pTerm!=0 );
106826    assert( pTerm->eOperator==WO_OR );
106827    assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
106828    pOrWc = &pTerm->u.pOrInfo->wc;
106829    pLevel->op = OP_Return;
106830    pLevel->p1 = regReturn;
106831
106832    /* Set up a new SrcList ni pOrTab containing the table being scanned
106833    ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
106834    ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
106835    */
106836    if( pWInfo->nLevel>1 ){
106837      int nNotReady;                 /* The number of notReady tables */
106838      struct SrcList_item *origSrc;     /* Original list of tables */
106839      nNotReady = pWInfo->nLevel - iLevel - 1;
106840      pOrTab = sqlite3StackAllocRaw(pParse->db,
106841                            sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
106842      if( pOrTab==0 ) return notReady;
106843      pOrTab->nAlloc = (i16)(nNotReady + 1);
106844      pOrTab->nSrc = pOrTab->nAlloc;
106845      memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
106846      origSrc = pWInfo->pTabList->a;
106847      for(k=1; k<=nNotReady; k++){
106848        memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
106849      }
106850    }else{
106851      pOrTab = pWInfo->pTabList;
106852    }
106853
106854    /* Initialize the rowset register to contain NULL. An SQL NULL is
106855    ** equivalent to an empty rowset.
106856    **
106857    ** Also initialize regReturn to contain the address of the instruction
106858    ** immediately following the OP_Return at the bottom of the loop. This
106859    ** is required in a few obscure LEFT JOIN cases where control jumps
106860    ** over the top of the loop into the body of it. In this case the
106861    ** correct response for the end-of-loop code (the OP_Return) is to
106862    ** fall through to the next instruction, just as an OP_Next does if
106863    ** called on an uninitialized cursor.
106864    */
106865    if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
106866      regRowset = ++pParse->nMem;
106867      regRowid = ++pParse->nMem;
106868      sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
106869    }
106870    iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
106871
106872    /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
106873    ** Then for every term xN, evaluate as the subexpression: xN AND z
106874    ** That way, terms in y that are factored into the disjunction will
106875    ** be picked up by the recursive calls to sqlite3WhereBegin() below.
106876    **
106877    ** Actually, each subexpression is converted to "xN AND w" where w is
106878    ** the "interesting" terms of z - terms that did not originate in the
106879    ** ON or USING clause of a LEFT JOIN, and terms that are usable as
106880    ** indices.
106881    */
106882    if( pWC->nTerm>1 ){
106883      int iTerm;
106884      for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
106885        Expr *pExpr = pWC->a[iTerm].pExpr;
106886        if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
106887        if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
106888        if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
106889        pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
106890        pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
106891      }
106892      if( pAndExpr ){
106893        pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
106894      }
106895    }
106896
106897    for(ii=0; ii<pOrWc->nTerm; ii++){
106898      WhereTerm *pOrTerm = &pOrWc->a[ii];
106899      if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
106900        WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
106901        Expr *pOrExpr = pOrTerm->pExpr;
106902        if( pAndExpr ){
106903          pAndExpr->pLeft = pOrExpr;
106904          pOrExpr = pAndExpr;
106905        }
106906        /* Loop through table entries that match term pOrTerm. */
106907        pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
106908                        WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
106909                        WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
106910        if( pSubWInfo ){
106911          explainOneScan(
106912              pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
106913          );
106914          if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
106915            int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
106916            int r;
106917            r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
106918                                         regRowid);
106919            sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
106920                                 sqlite3VdbeCurrentAddr(v)+2, r, iSet);
106921          }
106922          sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
106923
106924          /* The pSubWInfo->untestedTerms flag means that this OR term
106925          ** contained one or more AND term from a notReady table.  The
106926          ** terms from the notReady table could not be tested and will
106927          ** need to be tested later.
106928          */
106929          if( pSubWInfo->untestedTerms ) untestedTerms = 1;
106930
106931          /* Finish the loop through table entries that match term pOrTerm. */
106932          sqlite3WhereEnd(pSubWInfo);
106933        }
106934      }
106935    }
106936    if( pAndExpr ){
106937      pAndExpr->pLeft = 0;
106938      sqlite3ExprDelete(pParse->db, pAndExpr);
106939    }
106940    sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
106941    sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
106942    sqlite3VdbeResolveLabel(v, iLoopBody);
106943
106944    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
106945    if( !untestedTerms ) disableTerm(pLevel, pTerm);
106946  }else
106947#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
106948
106949  {
106950    /* Case 5:  There is no usable index.  We must do a complete
106951    **          scan of the entire table.
106952    */
106953    static const u8 aStep[] = { OP_Next, OP_Prev };
106954    static const u8 aStart[] = { OP_Rewind, OP_Last };
106955    assert( bRev==0 || bRev==1 );
106956    assert( omitTable==0 );
106957    pLevel->op = aStep[bRev];
106958    pLevel->p1 = iCur;
106959    pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
106960    pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
106961  }
106962  notReady &= ~getMask(pWC->pMaskSet, iCur);
106963
106964  /* Insert code to test every subexpression that can be completely
106965  ** computed using the current set of tables.
106966  **
106967  ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
106968  ** the use of indices become tests that are evaluated against each row of
106969  ** the relevant input tables.
106970  */
106971  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
106972    Expr *pE;
106973    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
106974    testcase( pTerm->wtFlags & TERM_CODED );
106975    if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
106976    if( (pTerm->prereqAll & notReady)!=0 ){
106977      testcase( pWInfo->untestedTerms==0
106978               && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
106979      pWInfo->untestedTerms = 1;
106980      continue;
106981    }
106982    pE = pTerm->pExpr;
106983    assert( pE!=0 );
106984    if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
106985      continue;
106986    }
106987    sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
106988    pTerm->wtFlags |= TERM_CODED;
106989  }
106990
106991  /* For a LEFT OUTER JOIN, generate code that will record the fact that
106992  ** at least one row of the right table has matched the left table.
106993  */
106994  if( pLevel->iLeftJoin ){
106995    pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
106996    sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
106997    VdbeComment((v, "record LEFT JOIN hit"));
106998    sqlite3ExprCacheClear(pParse);
106999    for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
107000      testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
107001      testcase( pTerm->wtFlags & TERM_CODED );
107002      if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
107003      if( (pTerm->prereqAll & notReady)!=0 ){
107004        assert( pWInfo->untestedTerms );
107005        continue;
107006      }
107007      assert( pTerm->pExpr );
107008      sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
107009      pTerm->wtFlags |= TERM_CODED;
107010    }
107011  }
107012  sqlite3ReleaseTempReg(pParse, iReleaseReg);
107013
107014  return notReady;
107015}
107016
107017#if defined(SQLITE_TEST)
107018/*
107019** The following variable holds a text description of query plan generated
107020** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
107021** overwrites the previous.  This information is used for testing and
107022** analysis only.
107023*/
107024SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
107025static int nQPlan = 0;              /* Next free slow in _query_plan[] */
107026
107027#endif /* SQLITE_TEST */
107028
107029
107030/*
107031** Free a WhereInfo structure
107032*/
107033static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
107034  if( ALWAYS(pWInfo) ){
107035    int i;
107036    for(i=0; i<pWInfo->nLevel; i++){
107037      sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
107038      if( pInfo ){
107039        /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
107040        if( pInfo->needToFreeIdxStr ){
107041          sqlite3_free(pInfo->idxStr);
107042        }
107043        sqlite3DbFree(db, pInfo);
107044      }
107045      if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
107046        Index *pIdx = pWInfo->a[i].plan.u.pIdx;
107047        if( pIdx ){
107048          sqlite3DbFree(db, pIdx->zColAff);
107049          sqlite3DbFree(db, pIdx);
107050        }
107051      }
107052    }
107053    whereClauseClear(pWInfo->pWC);
107054    sqlite3DbFree(db, pWInfo);
107055  }
107056}
107057
107058
107059/*
107060** Generate the beginning of the loop used for WHERE clause processing.
107061** The return value is a pointer to an opaque structure that contains
107062** information needed to terminate the loop.  Later, the calling routine
107063** should invoke sqlite3WhereEnd() with the return value of this function
107064** in order to complete the WHERE clause processing.
107065**
107066** If an error occurs, this routine returns NULL.
107067**
107068** The basic idea is to do a nested loop, one loop for each table in
107069** the FROM clause of a select.  (INSERT and UPDATE statements are the
107070** same as a SELECT with only a single table in the FROM clause.)  For
107071** example, if the SQL is this:
107072**
107073**       SELECT * FROM t1, t2, t3 WHERE ...;
107074**
107075** Then the code generated is conceptually like the following:
107076**
107077**      foreach row1 in t1 do       \    Code generated
107078**        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
107079**          foreach row3 in t3 do   /
107080**            ...
107081**          end                     \    Code generated
107082**        end                        |-- by sqlite3WhereEnd()
107083**      end                         /
107084**
107085** Note that the loops might not be nested in the order in which they
107086** appear in the FROM clause if a different order is better able to make
107087** use of indices.  Note also that when the IN operator appears in
107088** the WHERE clause, it might result in additional nested loops for
107089** scanning through all values on the right-hand side of the IN.
107090**
107091** There are Btree cursors associated with each table.  t1 uses cursor
107092** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
107093** And so forth.  This routine generates code to open those VDBE cursors
107094** and sqlite3WhereEnd() generates the code to close them.
107095**
107096** The code that sqlite3WhereBegin() generates leaves the cursors named
107097** in pTabList pointing at their appropriate entries.  The [...] code
107098** can use OP_Column and OP_Rowid opcodes on these cursors to extract
107099** data from the various tables of the loop.
107100**
107101** If the WHERE clause is empty, the foreach loops must each scan their
107102** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
107103** the tables have indices and there are terms in the WHERE clause that
107104** refer to those indices, a complete table scan can be avoided and the
107105** code will run much faster.  Most of the work of this routine is checking
107106** to see if there are indices that can be used to speed up the loop.
107107**
107108** Terms of the WHERE clause are also used to limit which rows actually
107109** make it to the "..." in the middle of the loop.  After each "foreach",
107110** terms of the WHERE clause that use only terms in that loop and outer
107111** loops are evaluated and if false a jump is made around all subsequent
107112** inner loops (or around the "..." if the test occurs within the inner-
107113** most loop)
107114**
107115** OUTER JOINS
107116**
107117** An outer join of tables t1 and t2 is conceptally coded as follows:
107118**
107119**    foreach row1 in t1 do
107120**      flag = 0
107121**      foreach row2 in t2 do
107122**        start:
107123**          ...
107124**          flag = 1
107125**      end
107126**      if flag==0 then
107127**        move the row2 cursor to a null row
107128**        goto start
107129**      fi
107130**    end
107131**
107132** ORDER BY CLAUSE PROCESSING
107133**
107134** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
107135** if there is one.  If there is no ORDER BY clause or if this routine
107136** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
107137**
107138** If an index can be used so that the natural output order of the table
107139** scan is correct for the ORDER BY clause, then that index is used and
107140** *ppOrderBy is set to NULL.  This is an optimization that prevents an
107141** unnecessary sort of the result set if an index appropriate for the
107142** ORDER BY clause already exists.
107143**
107144** If the where clause loops cannot be arranged to provide the correct
107145** output order, then the *ppOrderBy is unchanged.
107146*/
107147SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
107148  Parse *pParse,        /* The parser context */
107149  SrcList *pTabList,    /* A list of all tables to be scanned */
107150  Expr *pWhere,         /* The WHERE clause */
107151  ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
107152  ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
107153  u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
107154){
107155  int i;                     /* Loop counter */
107156  int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
107157  int nTabList;              /* Number of elements in pTabList */
107158  WhereInfo *pWInfo;         /* Will become the return value of this function */
107159  Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
107160  Bitmask notReady;          /* Cursors that are not yet positioned */
107161  WhereMaskSet *pMaskSet;    /* The expression mask set */
107162  WhereClause *pWC;               /* Decomposition of the WHERE clause */
107163  struct SrcList_item *pTabItem;  /* A single entry from pTabList */
107164  WhereLevel *pLevel;             /* A single level in the pWInfo list */
107165  int iFrom;                      /* First unused FROM clause element */
107166  int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
107167  sqlite3 *db;               /* Database connection */
107168
107169  /* The number of tables in the FROM clause is limited by the number of
107170  ** bits in a Bitmask
107171  */
107172  testcase( pTabList->nSrc==BMS );
107173  if( pTabList->nSrc>BMS ){
107174    sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
107175    return 0;
107176  }
107177
107178  /* This function normally generates a nested loop for all tables in
107179  ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
107180  ** only generate code for the first table in pTabList and assume that
107181  ** any cursors associated with subsequent tables are uninitialized.
107182  */
107183  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
107184
107185  /* Allocate and initialize the WhereInfo structure that will become the
107186  ** return value. A single allocation is used to store the WhereInfo
107187  ** struct, the contents of WhereInfo.a[], the WhereClause structure
107188  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
107189  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
107190  ** some architectures. Hence the ROUND8() below.
107191  */
107192  db = pParse->db;
107193  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
107194  pWInfo = sqlite3DbMallocZero(db,
107195      nByteWInfo +
107196      sizeof(WhereClause) +
107197      sizeof(WhereMaskSet)
107198  );
107199  if( db->mallocFailed ){
107200    sqlite3DbFree(db, pWInfo);
107201    pWInfo = 0;
107202    goto whereBeginError;
107203  }
107204  pWInfo->nLevel = nTabList;
107205  pWInfo->pParse = pParse;
107206  pWInfo->pTabList = pTabList;
107207  pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
107208  pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
107209  pWInfo->wctrlFlags = wctrlFlags;
107210  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
107211  pMaskSet = (WhereMaskSet*)&pWC[1];
107212
107213  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
107214  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
107215  if( db->flags & SQLITE_DistinctOpt ) pDistinct = 0;
107216
107217  /* Split the WHERE clause into separate subexpressions where each
107218  ** subexpression is separated by an AND operator.
107219  */
107220  initMaskSet(pMaskSet);
107221  whereClauseInit(pWC, pParse, pMaskSet, wctrlFlags);
107222  sqlite3ExprCodeConstants(pParse, pWhere);
107223  whereSplit(pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
107224
107225  /* Special case: a WHERE clause that is constant.  Evaluate the
107226  ** expression and either jump over all of the code or fall thru.
107227  */
107228  if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
107229    sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
107230    pWhere = 0;
107231  }
107232
107233  /* Assign a bit from the bitmask to every term in the FROM clause.
107234  **
107235  ** When assigning bitmask values to FROM clause cursors, it must be
107236  ** the case that if X is the bitmask for the N-th FROM clause term then
107237  ** the bitmask for all FROM clause terms to the left of the N-th term
107238  ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
107239  ** its Expr.iRightJoinTable value to find the bitmask of the right table
107240  ** of the join.  Subtracting one from the right table bitmask gives a
107241  ** bitmask for all tables to the left of the join.  Knowing the bitmask
107242  ** for all tables to the left of a left join is important.  Ticket #3015.
107243  **
107244  ** Configure the WhereClause.vmask variable so that bits that correspond
107245  ** to virtual table cursors are set. This is used to selectively disable
107246  ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful
107247  ** with virtual tables.
107248  **
107249  ** Note that bitmasks are created for all pTabList->nSrc tables in
107250  ** pTabList, not just the first nTabList tables.  nTabList is normally
107251  ** equal to pTabList->nSrc but might be shortened to 1 if the
107252  ** WHERE_ONETABLE_ONLY flag is set.
107253  */
107254  assert( pWC->vmask==0 && pMaskSet->n==0 );
107255  for(i=0; i<pTabList->nSrc; i++){
107256    createMask(pMaskSet, pTabList->a[i].iCursor);
107257#ifndef SQLITE_OMIT_VIRTUALTABLE
107258    if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
107259      pWC->vmask |= ((Bitmask)1 << i);
107260    }
107261#endif
107262  }
107263#ifndef NDEBUG
107264  {
107265    Bitmask toTheLeft = 0;
107266    for(i=0; i<pTabList->nSrc; i++){
107267      Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
107268      assert( (m-1)==toTheLeft );
107269      toTheLeft |= m;
107270    }
107271  }
107272#endif
107273
107274  /* Analyze all of the subexpressions.  Note that exprAnalyze() might
107275  ** add new virtual terms onto the end of the WHERE clause.  We do not
107276  ** want to analyze these virtual terms, so start analyzing at the end
107277  ** and work forward so that the added virtual terms are never processed.
107278  */
107279  exprAnalyzeAll(pTabList, pWC);
107280  if( db->mallocFailed ){
107281    goto whereBeginError;
107282  }
107283
107284  /* Check if the DISTINCT qualifier, if there is one, is redundant.
107285  ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
107286  ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
107287  */
107288  if( pDistinct && isDistinctRedundant(pParse, pTabList, pWC, pDistinct) ){
107289    pDistinct = 0;
107290    pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
107291  }
107292
107293  /* Chose the best index to use for each table in the FROM clause.
107294  **
107295  ** This loop fills in the following fields:
107296  **
107297  **   pWInfo->a[].pIdx      The index to use for this level of the loop.
107298  **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
107299  **   pWInfo->a[].nEq       The number of == and IN constraints
107300  **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
107301  **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
107302  **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
107303  **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
107304  **
107305  ** This loop also figures out the nesting order of tables in the FROM
107306  ** clause.
107307  */
107308  notReady = ~(Bitmask)0;
107309  andFlags = ~0;
107310  WHERETRACE(("*** Optimizer Start ***\n"));
107311  for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
107312    WhereCost bestPlan;         /* Most efficient plan seen so far */
107313    Index *pIdx;                /* Index for FROM table at pTabItem */
107314    int j;                      /* For looping over FROM tables */
107315    int bestJ = -1;             /* The value of j */
107316    Bitmask m;                  /* Bitmask value for j or bestJ */
107317    int isOptimal;              /* Iterator for optimal/non-optimal search */
107318    int nUnconstrained;         /* Number tables without INDEXED BY */
107319    Bitmask notIndexed;         /* Mask of tables that cannot use an index */
107320
107321    memset(&bestPlan, 0, sizeof(bestPlan));
107322    bestPlan.rCost = SQLITE_BIG_DBL;
107323    WHERETRACE(("*** Begin search for loop %d ***\n", i));
107324
107325    /* Loop through the remaining entries in the FROM clause to find the
107326    ** next nested loop. The loop tests all FROM clause entries
107327    ** either once or twice.
107328    **
107329    ** The first test is always performed if there are two or more entries
107330    ** remaining and never performed if there is only one FROM clause entry
107331    ** to choose from.  The first test looks for an "optimal" scan.  In
107332    ** this context an optimal scan is one that uses the same strategy
107333    ** for the given FROM clause entry as would be selected if the entry
107334    ** were used as the innermost nested loop.  In other words, a table
107335    ** is chosen such that the cost of running that table cannot be reduced
107336    ** by waiting for other tables to run first.  This "optimal" test works
107337    ** by first assuming that the FROM clause is on the inner loop and finding
107338    ** its query plan, then checking to see if that query plan uses any
107339    ** other FROM clause terms that are notReady.  If no notReady terms are
107340    ** used then the "optimal" query plan works.
107341    **
107342    ** Note that the WhereCost.nRow parameter for an optimal scan might
107343    ** not be as small as it would be if the table really were the innermost
107344    ** join.  The nRow value can be reduced by WHERE clause constraints
107345    ** that do not use indices.  But this nRow reduction only happens if the
107346    ** table really is the innermost join.
107347    **
107348    ** The second loop iteration is only performed if no optimal scan
107349    ** strategies were found by the first iteration. This second iteration
107350    ** is used to search for the lowest cost scan overall.
107351    **
107352    ** Previous versions of SQLite performed only the second iteration -
107353    ** the next outermost loop was always that with the lowest overall
107354    ** cost. However, this meant that SQLite could select the wrong plan
107355    ** for scripts such as the following:
107356    **
107357    **   CREATE TABLE t1(a, b);
107358    **   CREATE TABLE t2(c, d);
107359    **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
107360    **
107361    ** The best strategy is to iterate through table t1 first. However it
107362    ** is not possible to determine this with a simple greedy algorithm.
107363    ** Since the cost of a linear scan through table t2 is the same
107364    ** as the cost of a linear scan through table t1, a simple greedy
107365    ** algorithm may choose to use t2 for the outer loop, which is a much
107366    ** costlier approach.
107367    */
107368    nUnconstrained = 0;
107369    notIndexed = 0;
107370    for(isOptimal=(iFrom<nTabList-1); isOptimal>=0 && bestJ<0; isOptimal--){
107371      Bitmask mask;             /* Mask of tables not yet ready */
107372      for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
107373        int doNotReorder;    /* True if this table should not be reordered */
107374        WhereCost sCost;     /* Cost information from best[Virtual]Index() */
107375        ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
107376        ExprList *pDist;     /* DISTINCT clause for index to optimize */
107377
107378        doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
107379        if( j!=iFrom && doNotReorder ) break;
107380        m = getMask(pMaskSet, pTabItem->iCursor);
107381        if( (m & notReady)==0 ){
107382          if( j==iFrom ) iFrom++;
107383          continue;
107384        }
107385        mask = (isOptimal ? m : notReady);
107386        pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
107387        pDist = (i==0 ? pDistinct : 0);
107388        if( pTabItem->pIndex==0 ) nUnconstrained++;
107389
107390        WHERETRACE(("=== trying table %d with isOptimal=%d ===\n",
107391                    j, isOptimal));
107392        assert( pTabItem->pTab );
107393#ifndef SQLITE_OMIT_VIRTUALTABLE
107394        if( IsVirtual(pTabItem->pTab) ){
107395          sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
107396          bestVirtualIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
107397                           &sCost, pp);
107398        }else
107399#endif
107400        {
107401          bestBtreeIndex(pParse, pWC, pTabItem, mask, notReady, pOrderBy,
107402              pDist, &sCost);
107403        }
107404        assert( isOptimal || (sCost.used&notReady)==0 );
107405
107406        /* If an INDEXED BY clause is present, then the plan must use that
107407        ** index if it uses any index at all */
107408        assert( pTabItem->pIndex==0
107409                  || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
107410                  || sCost.plan.u.pIdx==pTabItem->pIndex );
107411
107412        if( isOptimal && (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
107413          notIndexed |= m;
107414        }
107415
107416        /* Conditions under which this table becomes the best so far:
107417        **
107418        **   (1) The table must not depend on other tables that have not
107419        **       yet run.
107420        **
107421        **   (2) A full-table-scan plan cannot supercede indexed plan unless
107422        **       the full-table-scan is an "optimal" plan as defined above.
107423        **
107424        **   (3) All tables have an INDEXED BY clause or this table lacks an
107425        **       INDEXED BY clause or this table uses the specific
107426        **       index specified by its INDEXED BY clause.  This rule ensures
107427        **       that a best-so-far is always selected even if an impossible
107428        **       combination of INDEXED BY clauses are given.  The error
107429        **       will be detected and relayed back to the application later.
107430        **       The NEVER() comes about because rule (2) above prevents
107431        **       An indexable full-table-scan from reaching rule (3).
107432        **
107433        **   (4) The plan cost must be lower than prior plans or else the
107434        **       cost must be the same and the number of rows must be lower.
107435        */
107436        if( (sCost.used&notReady)==0                       /* (1) */
107437            && (bestJ<0 || (notIndexed&m)!=0               /* (2) */
107438                || (bestPlan.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
107439                || (sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0)
107440            && (nUnconstrained==0 || pTabItem->pIndex==0   /* (3) */
107441                || NEVER((sCost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
107442            && (bestJ<0 || sCost.rCost<bestPlan.rCost      /* (4) */
107443                || (sCost.rCost<=bestPlan.rCost
107444                 && sCost.plan.nRow<bestPlan.plan.nRow))
107445        ){
107446          WHERETRACE(("=== table %d is best so far"
107447                      " with cost=%g and nRow=%g\n",
107448                      j, sCost.rCost, sCost.plan.nRow));
107449          bestPlan = sCost;
107450          bestJ = j;
107451        }
107452        if( doNotReorder ) break;
107453      }
107454    }
107455    assert( bestJ>=0 );
107456    assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
107457    WHERETRACE(("*** Optimizer selects table %d for loop %d"
107458                " with cost=%g and nRow=%g\n",
107459                bestJ, pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow));
107460    /* The ALWAYS() that follows was added to hush up clang scan-build */
107461    if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 && ALWAYS(ppOrderBy) ){
107462      *ppOrderBy = 0;
107463    }
107464    if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
107465      assert( pWInfo->eDistinct==0 );
107466      pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
107467    }
107468    andFlags &= bestPlan.plan.wsFlags;
107469    pLevel->plan = bestPlan.plan;
107470    testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
107471    testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
107472    if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
107473      pLevel->iIdxCur = pParse->nTab++;
107474    }else{
107475      pLevel->iIdxCur = -1;
107476    }
107477    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
107478    pLevel->iFrom = (u8)bestJ;
107479    if( bestPlan.plan.nRow>=(double)1 ){
107480      pParse->nQueryLoop *= bestPlan.plan.nRow;
107481    }
107482
107483    /* Check that if the table scanned by this loop iteration had an
107484    ** INDEXED BY clause attached to it, that the named index is being
107485    ** used for the scan. If not, then query compilation has failed.
107486    ** Return an error.
107487    */
107488    pIdx = pTabList->a[bestJ].pIndex;
107489    if( pIdx ){
107490      if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
107491        sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
107492        goto whereBeginError;
107493      }else{
107494        /* If an INDEXED BY clause is used, the bestIndex() function is
107495        ** guaranteed to find the index specified in the INDEXED BY clause
107496        ** if it find an index at all. */
107497        assert( bestPlan.plan.u.pIdx==pIdx );
107498      }
107499    }
107500  }
107501  WHERETRACE(("*** Optimizer Finished ***\n"));
107502  if( pParse->nErr || db->mallocFailed ){
107503    goto whereBeginError;
107504  }
107505
107506  /* If the total query only selects a single row, then the ORDER BY
107507  ** clause is irrelevant.
107508  */
107509  if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
107510    *ppOrderBy = 0;
107511  }
107512
107513  /* If the caller is an UPDATE or DELETE statement that is requesting
107514  ** to use a one-pass algorithm, determine if this is appropriate.
107515  ** The one-pass algorithm only works if the WHERE clause constraints
107516  ** the statement to update a single row.
107517  */
107518  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
107519  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
107520    pWInfo->okOnePass = 1;
107521    pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
107522  }
107523
107524  /* Open all tables in the pTabList and any indices selected for
107525  ** searching those tables.
107526  */
107527  sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
107528  notReady = ~(Bitmask)0;
107529  pWInfo->nRowOut = (double)1;
107530  for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
107531    Table *pTab;     /* Table to open */
107532    int iDb;         /* Index of database containing table/index */
107533
107534    pTabItem = &pTabList->a[pLevel->iFrom];
107535    pTab = pTabItem->pTab;
107536    pLevel->iTabCur = pTabItem->iCursor;
107537    pWInfo->nRowOut *= pLevel->plan.nRow;
107538    iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
107539    if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
107540      /* Do nothing */
107541    }else
107542#ifndef SQLITE_OMIT_VIRTUALTABLE
107543    if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
107544      const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
107545      int iCur = pTabItem->iCursor;
107546      sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
107547    }else
107548#endif
107549    if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107550         && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
107551      int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
107552      sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
107553      testcase( pTab->nCol==BMS-1 );
107554      testcase( pTab->nCol==BMS );
107555      if( !pWInfo->okOnePass && pTab->nCol<BMS ){
107556        Bitmask b = pTabItem->colUsed;
107557        int n = 0;
107558        for(; b; b=b>>1, n++){}
107559        sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
107560                            SQLITE_INT_TO_PTR(n), P4_INT32);
107561        assert( n<=pTab->nCol );
107562      }
107563    }else{
107564      sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
107565    }
107566#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
107567    if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
107568      constructAutomaticIndex(pParse, pWC, pTabItem, notReady, pLevel);
107569    }else
107570#endif
107571    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
107572      Index *pIx = pLevel->plan.u.pIdx;
107573      KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
107574      int iIdxCur = pLevel->iIdxCur;
107575      assert( pIx->pSchema==pTab->pSchema );
107576      assert( iIdxCur>=0 );
107577      sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
107578                        (char*)pKey, P4_KEYINFO_HANDOFF);
107579      VdbeComment((v, "%s", pIx->zName));
107580    }
107581    sqlite3CodeVerifySchema(pParse, iDb);
107582    notReady &= ~getMask(pWC->pMaskSet, pTabItem->iCursor);
107583  }
107584  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
107585  if( db->mallocFailed ) goto whereBeginError;
107586
107587  /* Generate the code to do the search.  Each iteration of the for
107588  ** loop below generates code for a single nested loop of the VM
107589  ** program.
107590  */
107591  notReady = ~(Bitmask)0;
107592  for(i=0; i<nTabList; i++){
107593    pLevel = &pWInfo->a[i];
107594    explainOneScan(pParse, pTabList, pLevel, i, pLevel->iFrom, wctrlFlags);
107595    notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
107596    pWInfo->iContinue = pLevel->addrCont;
107597  }
107598
107599#ifdef SQLITE_TEST  /* For testing and debugging use only */
107600  /* Record in the query plan information about the current table
107601  ** and the index used to access it (if any).  If the table itself
107602  ** is not used, its name is just '{}'.  If no index is used
107603  ** the index is listed as "{}".  If the primary key is used the
107604  ** index name is '*'.
107605  */
107606  for(i=0; i<nTabList; i++){
107607    char *z;
107608    int n;
107609    pLevel = &pWInfo->a[i];
107610    pTabItem = &pTabList->a[pLevel->iFrom];
107611    z = pTabItem->zAlias;
107612    if( z==0 ) z = pTabItem->pTab->zName;
107613    n = sqlite3Strlen30(z);
107614    if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
107615      if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
107616        memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
107617        nQPlan += 2;
107618      }else{
107619        memcpy(&sqlite3_query_plan[nQPlan], z, n);
107620        nQPlan += n;
107621      }
107622      sqlite3_query_plan[nQPlan++] = ' ';
107623    }
107624    testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
107625    testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
107626    if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
107627      memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
107628      nQPlan += 2;
107629    }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
107630      n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
107631      if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
107632        memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
107633        nQPlan += n;
107634        sqlite3_query_plan[nQPlan++] = ' ';
107635      }
107636    }else{
107637      memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
107638      nQPlan += 3;
107639    }
107640  }
107641  while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
107642    sqlite3_query_plan[--nQPlan] = 0;
107643  }
107644  sqlite3_query_plan[nQPlan] = 0;
107645  nQPlan = 0;
107646#endif /* SQLITE_TEST // Testing and debugging use only */
107647
107648  /* Record the continuation address in the WhereInfo structure.  Then
107649  ** clean up and return.
107650  */
107651  return pWInfo;
107652
107653  /* Jump here if malloc fails */
107654whereBeginError:
107655  if( pWInfo ){
107656    pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107657    whereInfoFree(db, pWInfo);
107658  }
107659  return 0;
107660}
107661
107662/*
107663** Generate the end of the WHERE loop.  See comments on
107664** sqlite3WhereBegin() for additional information.
107665*/
107666SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
107667  Parse *pParse = pWInfo->pParse;
107668  Vdbe *v = pParse->pVdbe;
107669  int i;
107670  WhereLevel *pLevel;
107671  SrcList *pTabList = pWInfo->pTabList;
107672  sqlite3 *db = pParse->db;
107673
107674  /* Generate loop termination code.
107675  */
107676  sqlite3ExprCacheClear(pParse);
107677  for(i=pWInfo->nLevel-1; i>=0; i--){
107678    pLevel = &pWInfo->a[i];
107679    sqlite3VdbeResolveLabel(v, pLevel->addrCont);
107680    if( pLevel->op!=OP_Noop ){
107681      sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
107682      sqlite3VdbeChangeP5(v, pLevel->p5);
107683    }
107684    if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
107685      struct InLoop *pIn;
107686      int j;
107687      sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
107688      for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
107689        sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
107690        sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
107691        sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
107692      }
107693      sqlite3DbFree(db, pLevel->u.in.aInLoop);
107694    }
107695    sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
107696    if( pLevel->iLeftJoin ){
107697      int addr;
107698      addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
107699      assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107700           || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
107701      if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
107702        sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
107703      }
107704      if( pLevel->iIdxCur>=0 ){
107705        sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
107706      }
107707      if( pLevel->op==OP_Return ){
107708        sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
107709      }else{
107710        sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
107711      }
107712      sqlite3VdbeJumpHere(v, addr);
107713    }
107714  }
107715
107716  /* The "break" point is here, just past the end of the outer loop.
107717  ** Set it.
107718  */
107719  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
107720
107721  /* Close all of the cursors that were opened by sqlite3WhereBegin.
107722  */
107723  assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
107724  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
107725    struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
107726    Table *pTab = pTabItem->pTab;
107727    assert( pTab!=0 );
107728    if( (pTab->tabFlags & TF_Ephemeral)==0
107729     && pTab->pSelect==0
107730     && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
107731    ){
107732      int ws = pLevel->plan.wsFlags;
107733      if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
107734        sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
107735      }
107736      if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
107737        sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
107738      }
107739    }
107740
107741    /* If this scan uses an index, make code substitutions to read data
107742    ** from the index in preference to the table. Sometimes, this means
107743    ** the table need never be read from. This is a performance boost,
107744    ** as the vdbe level waits until the table is read before actually
107745    ** seeking the table cursor to the record corresponding to the current
107746    ** position in the index.
107747    **
107748    ** Calls to the code generator in between sqlite3WhereBegin and
107749    ** sqlite3WhereEnd will have created code that references the table
107750    ** directly.  This loop scans all that code looking for opcodes
107751    ** that reference the table and converts them into opcodes that
107752    ** reference the index.
107753    */
107754    if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
107755      int k, j, last;
107756      VdbeOp *pOp;
107757      Index *pIdx = pLevel->plan.u.pIdx;
107758
107759      assert( pIdx!=0 );
107760      pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
107761      last = sqlite3VdbeCurrentAddr(v);
107762      for(k=pWInfo->iTop; k<last; k++, pOp++){
107763        if( pOp->p1!=pLevel->iTabCur ) continue;
107764        if( pOp->opcode==OP_Column ){
107765          for(j=0; j<pIdx->nColumn; j++){
107766            if( pOp->p2==pIdx->aiColumn[j] ){
107767              pOp->p2 = j;
107768              pOp->p1 = pLevel->iIdxCur;
107769              break;
107770            }
107771          }
107772          assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
107773               || j<pIdx->nColumn );
107774        }else if( pOp->opcode==OP_Rowid ){
107775          pOp->p1 = pLevel->iIdxCur;
107776          pOp->opcode = OP_IdxRowid;
107777        }
107778      }
107779    }
107780  }
107781
107782  /* Final cleanup
107783  */
107784  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
107785  whereInfoFree(db, pWInfo);
107786  return;
107787}
107788
107789/************** End of where.c ***********************************************/
107790/************** Begin file parse.c *******************************************/
107791/* Driver template for the LEMON parser generator.
107792** The author disclaims copyright to this source code.
107793**
107794** This version of "lempar.c" is modified, slightly, for use by SQLite.
107795** The only modifications are the addition of a couple of NEVER()
107796** macros to disable tests that are needed in the case of a general
107797** LALR(1) grammar but which are always false in the
107798** specific grammar used by SQLite.
107799*/
107800/* First off, code is included that follows the "include" declaration
107801** in the input grammar file. */
107802/* #include <stdio.h> */
107803
107804
107805/*
107806** Disable all error recovery processing in the parser push-down
107807** automaton.
107808*/
107809#define YYNOERRORRECOVERY 1
107810
107811/*
107812** Make yytestcase() the same as testcase()
107813*/
107814#define yytestcase(X) testcase(X)
107815
107816/*
107817** An instance of this structure holds information about the
107818** LIMIT clause of a SELECT statement.
107819*/
107820struct LimitVal {
107821  Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
107822  Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
107823};
107824
107825/*
107826** An instance of this structure is used to store the LIKE,
107827** GLOB, NOT LIKE, and NOT GLOB operators.
107828*/
107829struct LikeOp {
107830  Token eOperator;  /* "like" or "glob" or "regexp" */
107831  int not;         /* True if the NOT keyword is present */
107832};
107833
107834/*
107835** An instance of the following structure describes the event of a
107836** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
107837** TK_DELETE, or TK_INSTEAD.  If the event is of the form
107838**
107839**      UPDATE ON (a,b,c)
107840**
107841** Then the "b" IdList records the list "a,b,c".
107842*/
107843struct TrigEvent { int a; IdList * b; };
107844
107845/*
107846** An instance of this structure holds the ATTACH key and the key type.
107847*/
107848struct AttachKey { int type;  Token key; };
107849
107850/*
107851** One or more VALUES claues
107852*/
107853struct ValueList {
107854  ExprList *pList;
107855  Select *pSelect;
107856};
107857
107858
107859  /* This is a utility routine used to set the ExprSpan.zStart and
107860  ** ExprSpan.zEnd values of pOut so that the span covers the complete
107861  ** range of text beginning with pStart and going to the end of pEnd.
107862  */
107863  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
107864    pOut->zStart = pStart->z;
107865    pOut->zEnd = &pEnd->z[pEnd->n];
107866  }
107867
107868  /* Construct a new Expr object from a single identifier.  Use the
107869  ** new Expr to populate pOut.  Set the span of pOut to be the identifier
107870  ** that created the expression.
107871  */
107872  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
107873    pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
107874    pOut->zStart = pValue->z;
107875    pOut->zEnd = &pValue->z[pValue->n];
107876  }
107877
107878  /* This routine constructs a binary expression node out of two ExprSpan
107879  ** objects and uses the result to populate a new ExprSpan object.
107880  */
107881  static void spanBinaryExpr(
107882    ExprSpan *pOut,     /* Write the result here */
107883    Parse *pParse,      /* The parsing context.  Errors accumulate here */
107884    int op,             /* The binary operation */
107885    ExprSpan *pLeft,    /* The left operand */
107886    ExprSpan *pRight    /* The right operand */
107887  ){
107888    pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
107889    pOut->zStart = pLeft->zStart;
107890    pOut->zEnd = pRight->zEnd;
107891  }
107892
107893  /* Construct an expression node for a unary postfix operator
107894  */
107895  static void spanUnaryPostfix(
107896    ExprSpan *pOut,        /* Write the new expression node here */
107897    Parse *pParse,         /* Parsing context to record errors */
107898    int op,                /* The operator */
107899    ExprSpan *pOperand,    /* The operand */
107900    Token *pPostOp         /* The operand token for setting the span */
107901  ){
107902    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107903    pOut->zStart = pOperand->zStart;
107904    pOut->zEnd = &pPostOp->z[pPostOp->n];
107905  }
107906
107907  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
107908  ** unary TK_ISNULL or TK_NOTNULL expression. */
107909  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
107910    sqlite3 *db = pParse->db;
107911    if( db->mallocFailed==0 && pY->op==TK_NULL ){
107912      pA->op = (u8)op;
107913      sqlite3ExprDelete(db, pA->pRight);
107914      pA->pRight = 0;
107915    }
107916  }
107917
107918  /* Construct an expression node for a unary prefix operator
107919  */
107920  static void spanUnaryPrefix(
107921    ExprSpan *pOut,        /* Write the new expression node here */
107922    Parse *pParse,         /* Parsing context to record errors */
107923    int op,                /* The operator */
107924    ExprSpan *pOperand,    /* The operand */
107925    Token *pPreOp         /* The operand token for setting the span */
107926  ){
107927    pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
107928    pOut->zStart = pPreOp->z;
107929    pOut->zEnd = pOperand->zEnd;
107930  }
107931/* Next is all token values, in a form suitable for use by makeheaders.
107932** This section will be null unless lemon is run with the -m switch.
107933*/
107934/*
107935** These constants (all generated automatically by the parser generator)
107936** specify the various kinds of tokens (terminals) that the parser
107937** understands.
107938**
107939** Each symbol here is a terminal symbol in the grammar.
107940*/
107941/* Make sure the INTERFACE macro is defined.
107942*/
107943#ifndef INTERFACE
107944# define INTERFACE 1
107945#endif
107946/* The next thing included is series of defines which control
107947** various aspects of the generated parser.
107948**    YYCODETYPE         is the data type used for storing terminal
107949**                       and nonterminal numbers.  "unsigned char" is
107950**                       used if there are fewer than 250 terminals
107951**                       and nonterminals.  "int" is used otherwise.
107952**    YYNOCODE           is a number of type YYCODETYPE which corresponds
107953**                       to no legal terminal or nonterminal number.  This
107954**                       number is used to fill in empty slots of the hash
107955**                       table.
107956**    YYFALLBACK         If defined, this indicates that one or more tokens
107957**                       have fall-back values which should be used if the
107958**                       original value of the token will not parse.
107959**    YYACTIONTYPE       is the data type used for storing terminal
107960**                       and nonterminal numbers.  "unsigned char" is
107961**                       used if there are fewer than 250 rules and
107962**                       states combined.  "int" is used otherwise.
107963**    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given
107964**                       directly to the parser from the tokenizer.
107965**    YYMINORTYPE        is the data type used for all minor tokens.
107966**                       This is typically a union of many types, one of
107967**                       which is sqlite3ParserTOKENTYPE.  The entry in the union
107968**                       for base tokens is called "yy0".
107969**    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
107970**                       zero the stack is dynamically sized using realloc()
107971**    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
107972**    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
107973**    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
107974**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
107975**    YYNSTATE           the combined number of states.
107976**    YYNRULE            the number of rules in the grammar
107977**    YYERRORSYMBOL      is the code number of the error symbol.  If not
107978**                       defined, then do no error processing.
107979*/
107980#define YYCODETYPE unsigned char
107981#define YYNOCODE 251
107982#define YYACTIONTYPE unsigned short int
107983#define YYWILDCARD 67
107984#define sqlite3ParserTOKENTYPE Token
107985typedef union {
107986  int yyinit;
107987  sqlite3ParserTOKENTYPE yy0;
107988  struct LimitVal yy64;
107989  Expr* yy122;
107990  Select* yy159;
107991  IdList* yy180;
107992  struct {int value; int mask;} yy207;
107993  u8 yy258;
107994  struct LikeOp yy318;
107995  TriggerStep* yy327;
107996  ExprSpan yy342;
107997  SrcList* yy347;
107998  int yy392;
107999  struct TrigEvent yy410;
108000  ExprList* yy442;
108001  struct ValueList yy487;
108002} YYMINORTYPE;
108003#ifndef YYSTACKDEPTH
108004#define YYSTACKDEPTH 100
108005#endif
108006#define sqlite3ParserARG_SDECL Parse *pParse;
108007#define sqlite3ParserARG_PDECL ,Parse *pParse
108008#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
108009#define sqlite3ParserARG_STORE yypParser->pParse = pParse
108010#define YYNSTATE 629
108011#define YYNRULE 327
108012#define YYFALLBACK 1
108013#define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
108014#define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
108015#define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
108016
108017/* The yyzerominor constant is used to initialize instances of
108018** YYMINORTYPE objects to zero. */
108019static const YYMINORTYPE yyzerominor = { 0 };
108020
108021/* Define the yytestcase() macro to be a no-op if is not already defined
108022** otherwise.
108023**
108024** Applications can choose to define yytestcase() in the %include section
108025** to a macro that can assist in verifying code coverage.  For production
108026** code the yytestcase() macro should be turned off.  But it is useful
108027** for testing.
108028*/
108029#ifndef yytestcase
108030# define yytestcase(X)
108031#endif
108032
108033
108034/* Next are the tables used to determine what action to take based on the
108035** current state and lookahead token.  These tables are used to implement
108036** functions that take a state number and lookahead value and return an
108037** action integer.
108038**
108039** Suppose the action integer is N.  Then the action is determined as
108040** follows
108041**
108042**   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
108043**                                      token onto the stack and goto state N.
108044**
108045**   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
108046**
108047**   N == YYNSTATE+YYNRULE              A syntax error has occurred.
108048**
108049**   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
108050**
108051**   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
108052**                                      slots in the yy_action[] table.
108053**
108054** The action table is constructed as a single large table named yy_action[].
108055** Given state S and lookahead X, the action is computed as
108056**
108057**      yy_action[ yy_shift_ofst[S] + X ]
108058**
108059** If the index value yy_shift_ofst[S]+X is out of range or if the value
108060** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
108061** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
108062** and that yy_default[S] should be used instead.
108063**
108064** The formula above is for computing the action when the lookahead is
108065** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
108066** a reduce action) then the yy_reduce_ofst[] array is used in place of
108067** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
108068** YY_SHIFT_USE_DFLT.
108069**
108070** The following are the tables generated in this section:
108071**
108072**  yy_action[]        A single table containing all actions.
108073**  yy_lookahead[]     A table containing the lookahead for each entry in
108074**                     yy_action.  Used to detect hash collisions.
108075**  yy_shift_ofst[]    For each state, the offset into yy_action for
108076**                     shifting terminals.
108077**  yy_reduce_ofst[]   For each state, the offset into yy_action for
108078**                     shifting non-terminals after a reduce.
108079**  yy_default[]       Default action for each state.
108080*/
108081#define YY_ACTTAB_COUNT (1580)
108082static const YYACTIONTYPE yy_action[] = {
108083 /*     0 */   310,  328,  574,  573,   15,  172,  187,  596,   56,   56,
108084 /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
108085 /*    20 */    52,   52,   51,  234,  622,  621,  626,  622,  621,  299,
108086 /*    30 */   589,  583,   56,   56,   56,   56,  236,   54,   54,   54,
108087 /*    40 */    54,   53,   53,   52,   52,   52,   51,  234,  351,   57,
108088 /*    50 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
108089 /*    60 */    56,   56,  570,   54,   54,   54,   54,   53,   53,   52,
108090 /*    70 */    52,   52,   51,  234,  310,  596,  326,  607,  233,  232,
108091 /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108092 /*    90 */    51,  234,  619,  618,  326,  619,  618,  166,  605,  492,
108093 /*   100 */   381,  378,  377,  235,  589,  583,  554,  495,    1,   59,
108094 /*   110 */    19,  376,  622,  621,   53,   53,   52,   52,   52,   51,
108095 /*   120 */   234,  571,  571,   57,   58,   48,  581,  580,  582,  582,
108096 /*   130 */    55,   55,   56,   56,   56,   56,  215,   54,   54,   54,
108097 /*   140 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  224,
108098 /*   150 */    50,   47,  147,  177,  139,  281,  384,  276,  383,  169,
108099 /*   160 */   408,  553,  578,  578,  622,  621,  272,  224,  439,  550,
108100 /*   170 */   552,  410,  139,  281,  384,  276,  383,  169,  589,  583,
108101 /*   180 */   619,  618,  280,  620,  272,  195,  413,  309,  440,  441,
108102 /*   190 */   567,  491,  214,  279,  560,  600,   92,   57,   58,   48,
108103 /*   200 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
108104 /*   210 */   559,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108105 /*   220 */    51,  234,  310,  464,  233,  232,  558,  133,  519,   50,
108106 /*   230 */    47,  147,  619,  618,  565,  436,  397,  515,  514,  518,
108107 /*   240 */   410,  387,  438,  389,  437,  622,  621,  442,  570,  433,
108108 /*   250 */   203,  390,  589,  583,    6,  413,  166,  670,  250,  381,
108109 /*   260 */   378,  377,  525,  190,  600,   92,  594,  571,  571,  465,
108110 /*   270 */   376,   57,   58,   48,  581,  580,  582,  582,   55,   55,
108111 /*   280 */    56,   56,   56,   56,  599,   54,   54,   54,   54,   53,
108112 /*   290 */    53,   52,   52,   52,   51,  234,  310,  592,  592,  592,
108113 /*   300 */   490,  182,  247,  548,  249,  397,  273,  410,    7,  439,
108114 /*   310 */   398,  606,   67,  619,  618,  620,  472,  256,  347,  255,
108115 /*   320 */   473,  620,  413,  576,  620,   65,  589,  583,  236,  440,
108116 /*   330 */   336,  600,   92,   68,  364,  192,  481,  622,  621,  547,
108117 /*   340 */   622,  621,  560,  323,  207,   57,   58,   48,  581,  580,
108118 /*   350 */   582,  582,   55,   55,   56,   56,   56,   56,  559,   54,
108119 /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
108120 /*   370 */   310,  410,  397,  146,  558,  531,  401,  348,  599,  166,
108121 /*   380 */   248,  204,  381,  378,  377,  541,  413,  171,  337,  570,
108122 /*   390 */   622,  621,   40,  376,   38,  600,   74,  465,  548,  490,
108123 /*   400 */   589,  583,  532,  350,  579,  619,  618,  297,  619,  618,
108124 /*   410 */   480,   67,  470,   39,  620,  599,  406,  574,  573,   57,
108125 /*   420 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
108126 /*   430 */    56,   56,  577,   54,   54,   54,   54,   53,   53,   52,
108127 /*   440 */    52,   52,   51,  234,  310,  256,  347,  255,  530,   52,
108128 /*   450 */    52,   52,   51,  234,  345,  564,  236,  386,  619,  618,
108129 /*   460 */   957,  185,  418,    2,  408,  410,  578,  578,  198,  197,
108130 /*   470 */   196,  499,  183,  167,  589,  583,  671,  570,  505,  506,
108131 /*   480 */   413,  267,  601,  672,  546,  208,  602,   36,  601,  600,
108132 /*   490 */    91,  468,  602,   57,   58,   48,  581,  580,  582,  582,
108133 /*   500 */    55,   55,   56,   56,   56,   56,  202,   54,   54,   54,
108134 /*   510 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  599,
108135 /*   520 */   157,  408,  527,  578,  578,  263,  490,  265,  410,  873,
108136 /*   530 */   410,  474,  474,  366,  373,  410,  504,  428,   67,  290,
108137 /*   540 */   599,  620,  352,  413,  408,  413,  578,  578,  589,  583,
108138 /*   550 */   413,  382,  600,   92,  600,   16,  543,   62,  503,  600,
108139 /*   560 */    92,  408,  346,  578,  578,  168,   45,   57,   58,   48,
108140 /*   570 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
108141 /*   580 */   200,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108142 /*   590 */    51,  234,  310,  393,  395,  534,  510,  617,  616,  615,
108143 /*   600 */   318,  314,  172,   66,  596,  410,  338,  596,  324,  571,
108144 /*   610 */   571,   50,   47,  147,  599,  629,  627,  330,  539,  315,
108145 /*   620 */   413,   30,  589,  583,  272,  236,  199,  144,  176,  600,
108146 /*   630 */    73,  420,  947,  620,  947,  420,  946,  351,  946,  175,
108147 /*   640 */   596,   57,   58,   48,  581,  580,  582,  582,   55,   55,
108148 /*   650 */    56,   56,   56,   56,  410,   54,   54,   54,   54,   53,
108149 /*   660 */    53,   52,   52,   52,   51,  234,  310,  261,  410,  413,
108150 /*   670 */   269,  208,  596,  363,  410,  596,  424,  360,  600,   69,
108151 /*   680 */   424,  327,  620,  413,   50,   47,  147,  410,  358,  413,
108152 /*   690 */   575,  553,  600,   94,  483,  509,  589,  583,  600,   97,
108153 /*   700 */   552,  484,  413,  620,  188,  599,  551,  563,  596,  566,
108154 /*   710 */   334,  600,   95,  205,  201,   57,   58,   48,  581,  580,
108155 /*   720 */   582,  582,   55,   55,   56,   56,   56,   56,  352,   54,
108156 /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
108157 /*   740 */   310,  410,  261,  410,  167,   22,  356,  599,  359,  623,
108158 /*   750 */    50,   47,  147,  548,  357,  562,  413,  620,  413,  332,
108159 /*   760 */   523,  270,  410,  167,  620,  600,  104,  600,  103,  603,
108160 /*   770 */   589,  583,  339,  539,  304,  423,  222,  413,  174,  304,
108161 /*   780 */   422,  561,  567,  405,  214,  260,  600,  106,  620,   57,
108162 /*   790 */    58,   48,  581,  580,  582,  582,   55,   55,   56,   56,
108163 /*   800 */    56,   56,  410,   54,   54,   54,   54,   53,   53,   52,
108164 /*   810 */    52,   52,   51,  234,  310,  410,  557,  413,  410,  421,
108165 /*   820 */   273,   35,  512,  146,  421,   12,  600,  107,  213,  144,
108166 /*   830 */   413,  410,   32,  413,  410,  620,  365,  353,  358,  600,
108167 /*   840 */   134,   11,  600,  135,  589,  583,  413,   21,  548,  413,
108168 /*   850 */   316,  148,  620,  620,  170,  600,   98,  223,  600,  102,
108169 /*   860 */   374,  168,  167,   57,   58,   48,  581,  580,  582,  582,
108170 /*   870 */    55,   55,   56,   56,   56,   56,  410,   54,   54,   54,
108171 /*   880 */    54,   53,   53,   52,   52,   52,   51,  234,  310,  410,
108172 /*   890 */   273,  413,  410,  273,  212,  469,  410,  167,  628,    2,
108173 /*   900 */   600,  101,  545,  221,  413,  620,  130,  413,  620,  410,
108174 /*   910 */   539,  413,  537,  600,   93,  315,  600,  100,  589,  583,
108175 /*   920 */   600,   77,  425,  305,  413,  620,  254,  322,  599,  458,
108176 /*   930 */   320,  171,  543,  600,   96,  521,  520,   57,   58,   48,
108177 /*   940 */   581,  580,  582,  582,   55,   55,   56,   56,   56,   56,
108178 /*   950 */   410,   54,   54,   54,   54,   53,   53,   52,   52,   52,
108179 /*   960 */    51,  234,  310,  410,  273,  413,  410,  457,  358,   35,
108180 /*   970 */   426,  230,  306,  319,  600,  138,  467,  520,  413,  620,
108181 /*   980 */   143,  413,  410,  620,  410,  353,  529,  600,  137,  142,
108182 /*   990 */   600,  136,  589,  583,  604,  261,  528,  413,  229,  413,
108183 /*  1000 */   620,  321,  495,   28,  543,  543,  600,   76,  600,   90,
108184 /*  1010 */   620,   57,   46,   48,  581,  580,  582,  582,   55,   55,
108185 /*  1020 */    56,   56,   56,   56,  410,   54,   54,   54,   54,   53,
108186 /*  1030 */    53,   52,   52,   52,   51,  234,  310,  261,  451,  413,
108187 /*  1040 */   410,  211,  611,  285,  283,  610,  609,  502,  600,   89,
108188 /*  1050 */   380,  217,  620,  128,  140,  413,  220,  620,  410,  409,
108189 /*  1060 */   620,  620,  588,  587,  600,   75,  589,  583,  271,  620,
108190 /*  1070 */    51,  234,  127,  413,  620,  599,  627,  330,   27,  375,
108191 /*  1080 */   449,  279,  600,   88,  585,  584,   58,   48,  581,  580,
108192 /*  1090 */   582,  582,   55,   55,   56,   56,   56,   56,  410,   54,
108193 /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  234,
108194 /*  1110 */   310,  586,  410,  413,  410,  261,  593,  165,  399,  556,
108195 /*  1120 */   126,  371,  600,   87,  478,  186,  123,  413,  367,  413,
108196 /*  1130 */   620,  620,  410,  620,  620,  410,  600,   99,  600,   86,
108197 /*  1140 */   589,  583,  475,  122,  258,  171,  471,  413,  160,  121,
108198 /*  1150 */   413,   14,  159,  463,   25,   24,  600,   17,  448,  600,
108199 /*  1160 */    85,   48,  581,  580,  582,  582,   55,   55,   56,   56,
108200 /*  1170 */    56,   56,  158,   54,   54,   54,   54,   53,   53,   52,
108201 /*  1180 */    52,   52,   51,  234,   44,  404,  261,    3,  544,  261,
108202 /*  1190 */   540,  414,  621,  460,  119,  118,  538,  275,   10,  349,
108203 /*  1200 */     4,  620,  407,  620,  620,  620,  116,   44,  404,  410,
108204 /*  1210 */     3,  620,  620,  410,  414,  621,  456,  454,  252,  450,
108205 /*  1220 */   508,  402,  111,  109,  413,  407,  155,  444,  413,  447,
108206 /*  1230 */   435,  565,  219,  600,   84,  620,  108,  600,   83,   64,
108207 /*  1240 */   434,  417,  625,  150,  402,  333,  410,  237,  238,  124,
108208 /*  1250 */   274,   41,   42,  533,  565,  206,  189,  261,   43,  412,
108209 /*  1260 */   411,  413,  261,  594,  488,  620,  329,  149,  419,  268,
108210 /*  1270 */   600,   72,  620,  266,   41,   42,  181,  620,  410,  620,
108211 /*  1280 */   105,   43,  412,  411,  620,  624,  594,  614,  620,  599,
108212 /*  1290 */   228,  125,  313,  413,  592,  592,  592,  591,  590,   13,
108213 /*  1300 */   218,  410,  600,   71,  236,  244,   44,  404,  264,    3,
108214 /*  1310 */   312,  613,  340,  414,  621,  180,  413,  592,  592,  592,
108215 /*  1320 */   591,  590,   13,  620,  407,  600,   82,  410,  416,   34,
108216 /*  1330 */   404,  410,    3,  410,  262,  410,  414,  621,  612,  331,
108217 /*  1340 */   178,  415,  413,  402,    8,  236,  413,  407,  413,  620,
108218 /*  1350 */   413,  600,   81,  565,  257,  600,   80,  600,   70,  600,
108219 /*  1360 */    18,  598,  361,  462,  461,   30,  402,  294,   31,  620,
108220 /*  1370 */   293,  354,  251,   41,   42,  410,  565,  620,  620,  620,
108221 /*  1380 */    43,  412,  411,  453,  396,  594,  620,  620,  394,   61,
108222 /*  1390 */   413,  292,  443,  622,  621,  243,   41,   42,  620,  600,
108223 /*  1400 */    79,  597,  291,   43,  412,  411,   60,  620,  594,  240,
108224 /*  1410 */   620,  410,  231,   37,  555,  173,  592,  592,  592,  591,
108225 /*  1420 */   590,   13,  216,  239,  620,  184,  413,  302,  301,  300,
108226 /*  1430 */   179,  298,  388,  565,  452,  600,   78,  286,  620,  592,
108227 /*  1440 */   592,  592,  591,  590,   13,  429,   29,  413,  151,  289,
108228 /*  1450 */   242,  145,  392,  194,  193,  288,  600,    9,  542,  241,
108229 /*  1460 */   620,  525,  391,  284,  620,  594,  620,  620,  522,  536,
108230 /*  1470 */   620,  535,  153,  385,  465,  516,  282,  325,  154,  517,
108231 /*  1480 */   277,  152,  512,  511,  513,  129,  226,  308,  487,  486,
108232 /*  1490 */   485,  164,  372,  493,  307,  227,  592,  592,  592,  225,
108233 /*  1500 */   479,  163,  368,  370,  162,  476,  210,  477,   26,  259,
108234 /*  1510 */   161,  466,  362,  141,  132,  120,  117,  455,  156,  115,
108235 /*  1520 */   344,  343,  256,  342,  245,  114,  113,  446,  311,  112,
108236 /*  1530 */    23,  317,  432,  236,  131,  431,  110,  430,   20,  427,
108237 /*  1540 */   608,  595,  295,   63,  379,  287,  509,  191,  278,  403,
108238 /*  1550 */   572,  569,  497,  498,  496,  494,  335,  459,  445,  303,
108239 /*  1560 */   296,  246,  341,  355,    5,  568,  369,  507,  253,  549,
108240 /*  1570 */   526,  209,  400,  501,  500,  524,  234,  958,  489,  482,
108241};
108242static const YYCODETYPE yy_lookahead[] = {
108243 /*     0 */    19,  169,  170,  171,   22,   24,   24,   26,   77,   78,
108244 /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
108245 /*    20 */    89,   90,   91,   92,   26,   27,    1,   26,   27,   15,
108246 /*    30 */    49,   50,   77,   78,   79,   80,  116,   82,   83,   84,
108247 /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,  128,   68,
108248 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108249 /*    60 */    79,   80,  230,   82,   83,   84,   85,   86,   87,   88,
108250 /*    70 */    89,   90,   91,   92,   19,   94,   19,   23,   86,   87,
108251 /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108252 /*    90 */    91,   92,   94,   95,   19,   94,   95,   96,  172,  173,
108253 /*   100 */    99,  100,  101,  197,   49,   50,  177,  181,   22,   54,
108254 /*   110 */   204,  110,   26,   27,   86,   87,   88,   89,   90,   91,
108255 /*   120 */    92,  129,  130,   68,   69,   70,   71,   72,   73,   74,
108256 /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
108257 /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
108258 /*   150 */   221,  222,  223,   96,   97,   98,   99,  100,  101,  102,
108259 /*   160 */   112,   32,  114,  115,   26,   27,  109,   92,  150,   25,
108260 /*   170 */    41,  150,   97,   98,   99,  100,  101,  102,   49,   50,
108261 /*   180 */    94,   95,   98,  165,  109,   25,  165,  163,  170,  171,
108262 /*   190 */   166,  167,  168,  109,   12,  174,  175,   68,   69,   70,
108263 /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
108264 /*   210 */    28,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108265 /*   220 */    91,   92,   19,   11,   86,   87,   44,   24,   46,  221,
108266 /*   230 */   222,  223,   94,   95,   66,   97,  215,    7,    8,   57,
108267 /*   240 */   150,  220,  104,   19,  106,   26,   27,  229,  230,  241,
108268 /*   250 */   160,   27,   49,   50,   22,  165,   96,  118,   16,   99,
108269 /*   260 */   100,  101,   94,  119,  174,  175,   98,  129,  130,   57,
108270 /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
108271 /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
108272 /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
108273 /*   300 */   150,   23,   60,   25,   62,  215,  150,  150,   76,  150,
108274 /*   310 */   220,  161,  162,   94,   95,  165,   30,  105,  106,  107,
108275 /*   320 */    34,  165,  165,   23,  165,   25,   49,   50,  116,  170,
108276 /*   330 */   171,  174,  175,   22,   48,  185,  186,   26,   27,  120,
108277 /*   340 */    26,   27,   12,  187,  160,   68,   69,   70,   71,   72,
108278 /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   28,   82,
108279 /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
108280 /*   370 */    19,  150,  215,   95,   44,   23,   46,  220,  194,   96,
108281 /*   380 */   138,  160,   99,  100,  101,   23,  165,   25,  229,  230,
108282 /*   390 */    26,   27,  135,  110,  137,  174,  175,   57,  120,  150,
108283 /*   400 */    49,   50,   88,  219,  113,   94,   95,  158,   94,   95,
108284 /*   410 */   161,  162,   21,  136,  165,  194,  169,  170,  171,   68,
108285 /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108286 /*   430 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
108287 /*   440 */    89,   90,   91,   92,   19,  105,  106,  107,   23,   88,
108288 /*   450 */    89,   90,   91,   92,   63,   23,  116,   88,   94,   95,
108289 /*   460 */   142,  143,  144,  145,  112,  150,  114,  115,  105,  106,
108290 /*   470 */   107,   23,   23,   25,   49,   50,  118,  230,   97,   98,
108291 /*   480 */   165,   16,  113,  118,  120,  160,  117,  136,  113,  174,
108292 /*   490 */   175,  100,  117,   68,   69,   70,   71,   72,   73,   74,
108293 /*   500 */    75,   76,   77,   78,   79,   80,  160,   82,   83,   84,
108294 /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  194,
108295 /*   520 */    25,  112,   23,  114,  115,   60,  150,   62,  150,  138,
108296 /*   530 */   150,  105,  106,  107,   19,  150,   36,  161,  162,  224,
108297 /*   540 */   194,  165,  217,  165,  112,  165,  114,  115,   49,   50,
108298 /*   550 */   165,   51,  174,  175,  174,  175,  166,  232,   58,  174,
108299 /*   560 */   175,  112,  237,  114,  115,   50,   22,   68,   69,   70,
108300 /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
108301 /*   580 */   160,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108302 /*   590 */    91,   92,   19,  215,  214,  205,   23,    7,    8,    9,
108303 /*   600 */   215,  155,   24,   22,   26,  150,   97,   26,  108,  129,
108304 /*   610 */   130,  221,  222,  223,  194,    0,    1,    2,  150,  104,
108305 /*   620 */   165,  126,   49,   50,  109,  116,  206,  207,  118,  174,
108306 /*   630 */   175,   22,   23,  165,   25,   22,   23,  128,   25,  118,
108307 /*   640 */    26,   68,   69,   70,   71,   72,   73,   74,   75,   76,
108308 /*   650 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
108309 /*   660 */    87,   88,   89,   90,   91,   92,   19,  150,  150,  165,
108310 /*   670 */    23,  160,   94,  227,  150,   94,   67,  231,  174,  175,
108311 /*   680 */    67,  213,  165,  165,  221,  222,  223,  150,  150,  165,
108312 /*   690 */    23,   32,  174,  175,  181,  182,   49,   50,  174,  175,
108313 /*   700 */    41,  188,  165,  165,   22,  194,  177,   11,   94,   23,
108314 /*   710 */   193,  174,  175,  160,   22,   68,   69,   70,   71,   72,
108315 /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  217,   82,
108316 /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
108317 /*   740 */    19,  150,  150,  150,   25,   24,   19,  194,  237,  150,
108318 /*   750 */   221,  222,  223,   25,   27,   23,  165,  165,  165,  242,
108319 /*   760 */   165,   23,  150,   25,  165,  174,  175,  174,  175,  174,
108320 /*   770 */    49,   50,  219,  150,   22,   23,  238,  165,   25,   22,
108321 /*   780 */    23,   23,  166,  167,  168,  193,  174,  175,  165,   68,
108322 /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108323 /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
108324 /*   810 */    89,   90,   91,   92,   19,  150,   23,  165,  150,   67,
108325 /*   820 */   150,   25,  103,   95,   67,   35,  174,  175,  206,  207,
108326 /*   830 */   165,  150,   25,  165,  150,  165,  213,  150,  150,  174,
108327 /*   840 */   175,   35,  174,  175,   49,   50,  165,   52,  120,  165,
108328 /*   850 */   245,  246,  165,  165,   35,  174,  175,  187,  174,  175,
108329 /*   860 */    23,   50,   25,   68,   69,   70,   71,   72,   73,   74,
108330 /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
108331 /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
108332 /*   890 */   150,  165,  150,  150,  160,   23,  150,   25,  144,  145,
108333 /*   900 */   174,  175,  120,  216,  165,  165,   22,  165,  165,  150,
108334 /*   910 */   150,  165,   27,  174,  175,  104,  174,  175,   49,   50,
108335 /*   920 */   174,  175,  247,  248,  165,  165,  238,  187,  194,   23,
108336 /*   930 */   187,   25,  166,  174,  175,  190,  191,   68,   69,   70,
108337 /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
108338 /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
108339 /*   960 */    91,   92,   19,  150,  150,  165,  150,   23,  150,   25,
108340 /*   970 */    23,  205,   25,  213,  174,  175,  190,  191,  165,  165,
108341 /*   980 */   118,  165,  150,  165,  150,  150,   23,  174,  175,   39,
108342 /*   990 */   174,  175,   49,   50,  173,  150,   23,  165,   52,  165,
108343 /*  1000 */   165,  187,  181,   22,  166,  166,  174,  175,  174,  175,
108344 /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
108345 /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
108346 /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
108347 /*  1040 */   150,  160,  150,  205,  205,  150,  150,   29,  174,  175,
108348 /*  1050 */    52,  216,  165,   22,  150,  165,  238,  165,  150,  150,
108349 /*  1060 */   165,  165,   49,   50,  174,  175,   49,   50,   23,  165,
108350 /*  1070 */    91,   92,   22,  165,  165,  194,    1,    2,   22,   52,
108351 /*  1080 */   193,  109,  174,  175,   71,   72,   69,   70,   71,   72,
108352 /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
108353 /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
108354 /*  1110 */    19,   98,  150,  165,  150,  150,  150,  102,  150,  150,
108355 /*  1120 */    22,   19,  174,  175,   20,   24,  104,  165,   43,  165,
108356 /*  1130 */   165,  165,  150,  165,  165,  150,  174,  175,  174,  175,
108357 /*  1140 */    49,   50,   59,   53,  138,   25,   53,  165,  104,   22,
108358 /*  1150 */   165,    5,  118,    1,   76,   76,  174,  175,  193,  174,
108359 /*  1160 */   175,   70,   71,   72,   73,   74,   75,   76,   77,   78,
108360 /*  1170 */    79,   80,   35,   82,   83,   84,   85,   86,   87,   88,
108361 /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,  150,
108362 /*  1190 */   150,   26,   27,   27,  108,  127,  150,  150,   22,   25,
108363 /*  1200 */    22,  165,   37,  165,  165,  165,  119,   19,   20,  150,
108364 /*  1210 */    22,  165,  165,  150,   26,   27,   23,    1,   16,   20,
108365 /*  1220 */   150,   56,  119,  108,  165,   37,  121,  128,  165,  193,
108366 /*  1230 */    23,   66,  193,  174,  175,  165,  127,  174,  175,   16,
108367 /*  1240 */    23,  146,  147,   15,   56,   65,  150,  152,  140,  154,
108368 /*  1250 */   150,   86,   87,   88,   66,  160,   22,  150,   93,   94,
108369 /*  1260 */    95,  165,  150,   98,  150,  165,    3,  246,    4,  150,
108370 /*  1270 */   174,  175,  165,  150,   86,   87,    6,  165,  150,  165,
108371 /*  1280 */   164,   93,   94,   95,  165,  149,   98,  149,  165,  194,
108372 /*  1290 */   180,  180,  249,  165,  129,  130,  131,  132,  133,  134,
108373 /*  1300 */   193,  150,  174,  175,  116,  193,   19,   20,  150,   22,
108374 /*  1310 */   249,  149,  217,   26,   27,  151,  165,  129,  130,  131,
108375 /*  1320 */   132,  133,  134,  165,   37,  174,  175,  150,  149,   19,
108376 /*  1330 */    20,  150,   22,  150,  150,  150,   26,   27,   13,  244,
108377 /*  1340 */   151,  159,  165,   56,   25,  116,  165,   37,  165,  165,
108378 /*  1350 */   165,  174,  175,   66,  150,  174,  175,  174,  175,  174,
108379 /*  1360 */   175,  194,  150,  150,  150,  126,   56,  199,  124,  165,
108380 /*  1370 */   200,  150,  150,   86,   87,  150,   66,  165,  165,  165,
108381 /*  1380 */    93,   94,   95,  150,  122,   98,  165,  165,  123,   22,
108382 /*  1390 */   165,  201,  150,   26,   27,  150,   86,   87,  165,  174,
108383 /*  1400 */   175,  203,  202,   93,   94,   95,  125,  165,   98,  150,
108384 /*  1410 */   165,  150,  225,  135,  157,  118,  129,  130,  131,  132,
108385 /*  1420 */   133,  134,    5,  150,  165,  157,  165,   10,   11,   12,
108386 /*  1430 */    13,   14,  150,   66,   17,  174,  175,  210,  165,  129,
108387 /*  1440 */   130,  131,  132,  133,  134,  150,  104,  165,   31,  150,
108388 /*  1450 */    33,  150,  150,   86,   87,  150,  174,  175,  211,   42,
108389 /*  1460 */   165,   94,  121,  210,  165,   98,  165,  165,  176,  211,
108390 /*  1470 */   165,  211,   55,  104,   57,  184,  210,   47,   61,  176,
108391 /*  1480 */   176,   64,  103,  176,  178,   22,   92,  179,  176,  176,
108392 /*  1490 */   176,  156,   18,  184,  179,  228,  129,  130,  131,  228,
108393 /*  1500 */   157,  156,   45,  157,  156,  236,  157,  157,  135,  235,
108394 /*  1510 */   156,  189,  157,   68,  218,  189,   22,  199,  156,  192,
108395 /*  1520 */   157,   18,  105,  106,  107,  192,  192,  199,  111,  192,
108396 /*  1530 */   240,  157,   40,  116,  218,  157,  189,  157,  240,   38,
108397 /*  1540 */   153,  166,  198,  243,  178,  209,  182,  196,  177,  226,
108398 /*  1550 */   230,  230,  166,  177,  177,  166,  139,  199,  199,  148,
108399 /*  1560 */   195,  209,  209,  239,  196,  166,  234,  183,  239,  208,
108400 /*  1570 */   174,  233,  191,  183,  183,  174,   92,  250,  186,  186,
108401};
108402#define YY_SHIFT_USE_DFLT (-81)
108403#define YY_SHIFT_COUNT (417)
108404#define YY_SHIFT_MIN   (-80)
108405#define YY_SHIFT_MAX   (1503)
108406static const short yy_shift_ofst[] = {
108407 /*     0 */  1075, 1188, 1417, 1188, 1287, 1287,  138,  138,    1,  -19,
108408 /*    10 */  1287, 1287, 1287, 1287,  340,   -2,  129,  129,  795, 1165,
108409 /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
108410 /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
108411 /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
108412 /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
108413 /*    60 */  1287, 1287,  212,   -2,   -2,   -8,   -8,  614, 1229,   55,
108414 /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
108415 /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
108416 /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
108417 /*   100 */   -45,  -45,  -45,  -45,   -1,   57,   28,  361,   -2,   -2,
108418 /*   110 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
108419 /*   120 */    -2,   -2,   -2,   -2,  391,  515,   -2,   -2,   -2,   -2,
108420 /*   130 */    -2,  509,  -80,  614,  979, 1484,  -81,  -81,  -81, 1367,
108421 /*   140 */    75,  182,  182,  314,  311,  364,  219,   86,  613,  609,
108422 /*   150 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
108423 /*   160 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
108424 /*   170 */    -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,   -2,
108425 /*   180 */    -2,   -2,  578,  578,  578,  615, 1229, 1229, 1229,  -81,
108426 /*   190 */   -81,  -81,  160,  168,  168,  283,  500,  500,  500,  278,
108427 /*   200 */   449,  330,  432,  409,  352,   48,   48,   48,   48,  426,
108428 /*   210 */   286,   48,   48,  728,  581,  369,  590,  495,  224,  224,
108429 /*   220 */   727,  495,  727,  719,  614,  659,  614,  659,  811,  659,
108430 /*   230 */   224,  257,  480,  480,  614,  144,  375,  -18, 1501, 1297,
108431 /*   240 */  1297, 1492, 1492, 1297, 1494, 1445, 1239, 1503, 1503, 1503,
108432 /*   250 */  1503, 1297, 1474, 1239, 1494, 1445, 1445, 1297, 1474, 1373,
108433 /*   260 */  1457, 1297, 1297, 1474, 1297, 1474, 1297, 1474, 1463, 1369,
108434 /*   270 */  1369, 1369, 1430, 1394, 1394, 1463, 1369, 1379, 1369, 1430,
108435 /*   280 */  1369, 1369, 1341, 1342, 1341, 1342, 1341, 1342, 1297, 1297,
108436 /*   290 */  1278, 1281, 1262, 1244, 1265, 1239, 1229, 1319, 1325, 1325,
108437 /*   300 */  1270, 1270, 1270, 1270,  -81,  -81,  -81,  -81,  -81,  -81,
108438 /*   310 */  1013,  242,  757,  752,  465,  363,  947,  232,  944,  906,
108439 /*   320 */   872,  837,  738,  448,  381,  230,   84,  362,  300, 1264,
108440 /*   330 */  1263, 1234, 1108, 1228, 1180, 1223, 1217, 1207, 1099, 1174,
108441 /*   340 */  1109, 1115, 1103, 1199, 1105, 1202, 1216, 1087, 1193, 1178,
108442 /*   350 */  1174, 1176, 1068, 1079, 1078, 1086, 1166, 1137, 1034, 1152,
108443 /*   360 */  1146, 1127, 1044, 1006, 1093, 1120, 1090, 1083, 1085, 1022,
108444 /*   370 */  1101, 1104, 1102,  972, 1015, 1098, 1027, 1056, 1050, 1045,
108445 /*   380 */  1031,  998, 1018,  981,  946,  950,  973,  963,  862,  885,
108446 /*   390 */   819,  884,  782,  796,  806,  807,  790,  796,  793,  758,
108447 /*   400 */   753,  732,  692,  696,  682,  686,  667,  544,  291,  521,
108448 /*   410 */   510,  365,  358,  139,  114,   54,   14,   25,
108449};
108450#define YY_REDUCE_USE_DFLT (-169)
108451#define YY_REDUCE_COUNT (309)
108452#define YY_REDUCE_MIN   (-168)
108453#define YY_REDUCE_MAX   (1411)
108454static const short yy_reduce_ofst[] = {
108455 /*     0 */   318,   90, 1095,  221,  157,   21,  159,   18,  150,  390,
108456 /*    10 */   385,  378,  380,  315,  325,  249,  529,  -71,    8, 1282,
108457 /*    20 */  1261, 1225, 1185, 1183, 1181, 1177, 1151, 1128, 1096, 1063,
108458 /*    30 */  1059,  985,  982,  964,  962,  948,  908,  890,  874,  834,
108459 /*    40 */   832,  816,  813,  800,  759,  746,  742,  739,  726,  684,
108460 /*    50 */   681,  668,  665,  652,  612,  593,  591,  537,  524,  518,
108461 /*    60 */   504,  455,  511,  376,  517,  247, -168,   24,  420,  463,
108462 /*    70 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
108463 /*    80 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
108464 /*    90 */   463,  463,  463,  463,  463,  463,  463,  463,  463,  463,
108465 /*   100 */   463,  463,  463,  463,  463,  -74,  463,  463, 1112,  835,
108466 /*   110 */  1107, 1039, 1036,  965,  887,  845,  818,  760,  688,  687,
108467 /*   120 */   538,  743,  623,  592,  446,  513,  814,  740,  670,  156,
108468 /*   130 */   468,  553,  184,  616,  463,  463,  463,  463,  463,  595,
108469 /*   140 */   821,  786,  745,  909, 1305, 1302, 1301, 1299,  675,  675,
108470 /*   150 */  1295, 1273, 1259, 1245, 1242, 1233, 1222, 1221, 1214, 1213,
108471 /*   160 */  1212, 1204, 1184, 1158, 1123, 1119, 1114, 1100, 1070, 1047,
108472 /*   170 */  1046, 1040, 1038,  969,  968,  966,  909,  904,  896,  895,
108473 /*   180 */   892,  599,  839,  838,  766,  754,  881,  734,  346,  605,
108474 /*   190 */   622,  -94, 1393, 1401, 1396, 1392, 1391, 1390, 1384, 1361,
108475 /*   200 */  1365, 1381, 1365, 1365, 1365, 1365, 1365, 1365, 1365, 1332,
108476 /*   210 */  1338, 1365, 1365, 1361, 1399, 1368, 1411, 1359, 1353, 1352,
108477 /*   220 */  1329, 1358, 1324, 1366, 1389, 1377, 1386, 1376, 1364, 1371,
108478 /*   230 */  1336, 1323, 1321, 1320, 1375, 1344, 1351, 1387, 1300, 1380,
108479 /*   240 */  1378, 1298, 1290, 1374, 1316, 1347, 1328, 1337, 1334, 1333,
108480 /*   250 */  1327, 1363, 1362, 1318, 1296, 1326, 1322, 1355, 1354, 1269,
108481 /*   260 */  1274, 1350, 1349, 1348, 1346, 1345, 1343, 1335, 1315, 1314,
108482 /*   270 */  1313, 1312, 1309, 1271, 1267, 1308, 1307, 1306, 1304, 1291,
108483 /*   280 */  1303, 1292, 1260, 1266, 1258, 1253, 1247, 1227, 1268, 1257,
108484 /*   290 */  1187, 1198, 1200, 1190, 1170, 1168, 1167, 1182, 1189, 1164,
108485 /*   300 */  1179, 1162, 1138, 1136, 1061, 1043, 1021, 1111, 1110, 1116,
108486};
108487static const YYACTIONTYPE yy_default[] = {
108488 /*     0 */   634,  868,  956,  956,  868,  868,  956,  956,  956,  758,
108489 /*    10 */   956,  956,  956,  866,  956,  956,  786,  786,  930,  956,
108490 /*    20 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108491 /*    30 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108492 /*    40 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108493 /*    50 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108494 /*    60 */   956,  956,  956,  956,  956,  956,  956,  673,  762,  792,
108495 /*    70 */   956,  956,  956,  956,  956,  956,  956,  956,  929,  931,
108496 /*    80 */   800,  799,  909,  773,  797,  790,  794,  869,  862,  863,
108497 /*    90 */   861,  865,  870,  956,  793,  829,  846,  828,  840,  845,
108498 /*   100 */   852,  844,  841,  831,  830,  665,  832,  833,  956,  956,
108499 /*   110 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108500 /*   120 */   956,  956,  956,  956,  660,  727,  956,  956,  956,  956,
108501 /*   130 */   956,  956,  956,  956,  834,  835,  849,  848,  847,  956,
108502 /*   140 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108503 /*   150 */   956,  936,  934,  956,  881,  956,  956,  956,  956,  956,
108504 /*   160 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108505 /*   170 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108506 /*   180 */   956,  640,  758,  758,  758,  634,  956,  956,  956,  948,
108507 /*   190 */   762,  752,  718,  956,  956,  956,  956,  956,  956,  956,
108508 /*   200 */   956,  956,  956,  956,  956,  802,  741,  919,  921,  956,
108509 /*   210 */   902,  739,  662,  760,  675,  750,  642,  796,  775,  775,
108510 /*   220 */   914,  796,  914,  699,  956,  786,  956,  786,  696,  786,
108511 /*   230 */   775,  864,  956,  956,  956,  759,  750,  956,  941,  766,
108512 /*   240 */   766,  933,  933,  766,  808,  731,  796,  738,  738,  738,
108513 /*   250 */   738,  766,  657,  796,  808,  731,  731,  766,  657,  908,
108514 /*   260 */   906,  766,  766,  657,  766,  657,  766,  657,  874,  729,
108515 /*   270 */   729,  729,  714,  878,  878,  874,  729,  699,  729,  714,
108516 /*   280 */   729,  729,  779,  774,  779,  774,  779,  774,  766,  766,
108517 /*   290 */   956,  791,  780,  789,  787,  796,  956,  717,  650,  650,
108518 /*   300 */   639,  639,  639,  639,  953,  953,  948,  701,  701,  683,
108519 /*   310 */   956,  956,  956,  956,  956,  956,  956,  883,  956,  956,
108520 /*   320 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108521 /*   330 */   635,  943,  956,  956,  940,  956,  956,  956,  956,  801,
108522 /*   340 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108523 /*   350 */   918,  956,  956,  956,  956,  956,  956,  956,  912,  956,
108524 /*   360 */   956,  956,  956,  956,  956,  905,  904,  956,  956,  956,
108525 /*   370 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108526 /*   380 */   956,  956,  956,  956,  956,  956,  956,  956,  956,  956,
108527 /*   390 */   956,  956,  956,  788,  956,  781,  956,  867,  956,  956,
108528 /*   400 */   956,  956,  956,  956,  956,  956,  956,  956,  744,  817,
108529 /*   410 */   956,  816,  820,  815,  667,  956,  648,  956,  631,  636,
108530 /*   420 */   952,  955,  954,  951,  950,  949,  944,  942,  939,  938,
108531 /*   430 */   937,  935,  932,  928,  887,  885,  892,  891,  890,  889,
108532 /*   440 */   888,  886,  884,  882,  803,  798,  795,  927,  880,  740,
108533 /*   450 */   737,  736,  656,  945,  911,  920,  807,  806,  809,  917,
108534 /*   460 */   916,  915,  913,  910,  897,  805,  804,  732,  872,  871,
108535 /*   470 */   659,  901,  900,  899,  903,  907,  898,  768,  658,  655,
108536 /*   480 */   664,  721,  720,  728,  726,  725,  724,  723,  722,  719,
108537 /*   490 */   666,  674,  685,  713,  698,  697,  877,  879,  876,  875,
108538 /*   500 */   706,  705,  711,  710,  709,  708,  707,  704,  703,  702,
108539 /*   510 */   695,  694,  700,  693,  716,  715,  712,  692,  735,  734,
108540 /*   520 */   733,  730,  691,  690,  689,  820,  688,  687,  826,  825,
108541 /*   530 */   813,  856,  755,  754,  753,  765,  764,  777,  776,  811,
108542 /*   540 */   810,  778,  763,  757,  756,  772,  771,  770,  769,  761,
108543 /*   550 */   751,  783,  785,  784,  782,  858,  767,  855,  926,  925,
108544 /*   560 */   924,  923,  922,  860,  859,  827,  824,  678,  679,  895,
108545 /*   570 */   894,  896,  893,  681,  680,  677,  676,  857,  746,  745,
108546 /*   580 */   853,  850,  842,  838,  854,  851,  843,  839,  837,  836,
108547 /*   590 */   822,  821,  819,  818,  814,  823,  669,  747,  743,  742,
108548 /*   600 */   812,  749,  748,  686,  684,  682,  663,  661,  654,  652,
108549 /*   610 */   651,  653,  649,  647,  646,  645,  644,  643,  672,  671,
108550 /*   620 */   670,  668,  667,  641,  638,  637,  633,  632,  630,
108551};
108552
108553/* The next table maps tokens into fallback tokens.  If a construct
108554** like the following:
108555**
108556**      %fallback ID X Y Z.
108557**
108558** appears in the grammar, then ID becomes a fallback token for X, Y,
108559** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
108560** but it does not parse, the type of the token is changed to ID and
108561** the parse is retried before an error is thrown.
108562*/
108563#ifdef YYFALLBACK
108564static const YYCODETYPE yyFallback[] = {
108565    0,  /*          $ => nothing */
108566    0,  /*       SEMI => nothing */
108567   26,  /*    EXPLAIN => ID */
108568   26,  /*      QUERY => ID */
108569   26,  /*       PLAN => ID */
108570   26,  /*      BEGIN => ID */
108571    0,  /* TRANSACTION => nothing */
108572   26,  /*   DEFERRED => ID */
108573   26,  /*  IMMEDIATE => ID */
108574   26,  /*  EXCLUSIVE => ID */
108575    0,  /*     COMMIT => nothing */
108576   26,  /*        END => ID */
108577   26,  /*   ROLLBACK => ID */
108578   26,  /*  SAVEPOINT => ID */
108579   26,  /*    RELEASE => ID */
108580    0,  /*         TO => nothing */
108581    0,  /*      TABLE => nothing */
108582    0,  /*     CREATE => nothing */
108583   26,  /*         IF => ID */
108584    0,  /*        NOT => nothing */
108585    0,  /*     EXISTS => nothing */
108586   26,  /*       TEMP => ID */
108587    0,  /*         LP => nothing */
108588    0,  /*         RP => nothing */
108589    0,  /*         AS => nothing */
108590    0,  /*      COMMA => nothing */
108591    0,  /*         ID => nothing */
108592    0,  /*    INDEXED => nothing */
108593   26,  /*      ABORT => ID */
108594   26,  /*     ACTION => ID */
108595   26,  /*      AFTER => ID */
108596   26,  /*    ANALYZE => ID */
108597   26,  /*        ASC => ID */
108598   26,  /*     ATTACH => ID */
108599   26,  /*     BEFORE => ID */
108600   26,  /*         BY => ID */
108601   26,  /*    CASCADE => ID */
108602   26,  /*       CAST => ID */
108603   26,  /*   COLUMNKW => ID */
108604   26,  /*   CONFLICT => ID */
108605   26,  /*   DATABASE => ID */
108606   26,  /*       DESC => ID */
108607   26,  /*     DETACH => ID */
108608   26,  /*       EACH => ID */
108609   26,  /*       FAIL => ID */
108610   26,  /*        FOR => ID */
108611   26,  /*     IGNORE => ID */
108612   26,  /*  INITIALLY => ID */
108613   26,  /*    INSTEAD => ID */
108614   26,  /*    LIKE_KW => ID */
108615   26,  /*      MATCH => ID */
108616   26,  /*         NO => ID */
108617   26,  /*        KEY => ID */
108618   26,  /*         OF => ID */
108619   26,  /*     OFFSET => ID */
108620   26,  /*     PRAGMA => ID */
108621   26,  /*      RAISE => ID */
108622   26,  /*    REPLACE => ID */
108623   26,  /*   RESTRICT => ID */
108624   26,  /*        ROW => ID */
108625   26,  /*    TRIGGER => ID */
108626   26,  /*     VACUUM => ID */
108627   26,  /*       VIEW => ID */
108628   26,  /*    VIRTUAL => ID */
108629   26,  /*    REINDEX => ID */
108630   26,  /*     RENAME => ID */
108631   26,  /*   CTIME_KW => ID */
108632};
108633#endif /* YYFALLBACK */
108634
108635/* The following structure represents a single element of the
108636** parser's stack.  Information stored includes:
108637**
108638**   +  The state number for the parser at this level of the stack.
108639**
108640**   +  The value of the token stored at this level of the stack.
108641**      (In other words, the "major" token.)
108642**
108643**   +  The semantic value stored at this level of the stack.  This is
108644**      the information used by the action routines in the grammar.
108645**      It is sometimes called the "minor" token.
108646*/
108647struct yyStackEntry {
108648  YYACTIONTYPE stateno;  /* The state-number */
108649  YYCODETYPE major;      /* The major token value.  This is the code
108650                         ** number for the token at this stack level */
108651  YYMINORTYPE minor;     /* The user-supplied minor token value.  This
108652                         ** is the value of the token  */
108653};
108654typedef struct yyStackEntry yyStackEntry;
108655
108656/* The state of the parser is completely contained in an instance of
108657** the following structure */
108658struct yyParser {
108659  int yyidx;                    /* Index of top element in stack */
108660#ifdef YYTRACKMAXSTACKDEPTH
108661  int yyidxMax;                 /* Maximum value of yyidx */
108662#endif
108663  int yyerrcnt;                 /* Shifts left before out of the error */
108664  sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
108665#if YYSTACKDEPTH<=0
108666  int yystksz;                  /* Current side of the stack */
108667  yyStackEntry *yystack;        /* The parser's stack */
108668#else
108669  yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
108670#endif
108671};
108672typedef struct yyParser yyParser;
108673
108674#ifndef NDEBUG
108675/* #include <stdio.h> */
108676static FILE *yyTraceFILE = 0;
108677static char *yyTracePrompt = 0;
108678#endif /* NDEBUG */
108679
108680#ifndef NDEBUG
108681/*
108682** Turn parser tracing on by giving a stream to which to write the trace
108683** and a prompt to preface each trace message.  Tracing is turned off
108684** by making either argument NULL
108685**
108686** Inputs:
108687** <ul>
108688** <li> A FILE* to which trace output should be written.
108689**      If NULL, then tracing is turned off.
108690** <li> A prefix string written at the beginning of every
108691**      line of trace output.  If NULL, then tracing is
108692**      turned off.
108693** </ul>
108694**
108695** Outputs:
108696** None.
108697*/
108698SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
108699  yyTraceFILE = TraceFILE;
108700  yyTracePrompt = zTracePrompt;
108701  if( yyTraceFILE==0 ) yyTracePrompt = 0;
108702  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
108703}
108704#endif /* NDEBUG */
108705
108706#ifndef NDEBUG
108707/* For tracing shifts, the names of all terminals and nonterminals
108708** are required.  The following table supplies these names */
108709static const char *const yyTokenName[] = {
108710  "$",             "SEMI",          "EXPLAIN",       "QUERY",
108711  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",
108712  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",
108713  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",
108714  "TABLE",         "CREATE",        "IF",            "NOT",
108715  "EXISTS",        "TEMP",          "LP",            "RP",
108716  "AS",            "COMMA",         "ID",            "INDEXED",
108717  "ABORT",         "ACTION",        "AFTER",         "ANALYZE",
108718  "ASC",           "ATTACH",        "BEFORE",        "BY",
108719  "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",
108720  "DATABASE",      "DESC",          "DETACH",        "EACH",
108721  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",
108722  "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",
108723  "KEY",           "OF",            "OFFSET",        "PRAGMA",
108724  "RAISE",         "REPLACE",       "RESTRICT",      "ROW",
108725  "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",
108726  "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",
108727  "OR",            "AND",           "IS",            "BETWEEN",
108728  "IN",            "ISNULL",        "NOTNULL",       "NE",
108729  "EQ",            "GT",            "LE",            "LT",
108730  "GE",            "ESCAPE",        "BITAND",        "BITOR",
108731  "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",
108732  "STAR",          "SLASH",         "REM",           "CONCAT",
108733  "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",
108734  "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",
108735  "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",
108736  "ON",            "INSERT",        "DELETE",        "UPDATE",
108737  "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",
108738  "UNION",         "ALL",           "EXCEPT",        "INTERSECT",
108739  "SELECT",        "DISTINCT",      "DOT",           "FROM",
108740  "JOIN",          "USING",         "ORDER",         "GROUP",
108741  "HAVING",        "LIMIT",         "WHERE",         "INTO",
108742  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",
108743  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",
108744  "THEN",          "ELSE",          "INDEX",         "ALTER",
108745  "ADD",           "error",         "input",         "cmdlist",
108746  "ecmd",          "explain",       "cmdx",          "cmd",
108747  "transtype",     "trans_opt",     "nm",            "savepoint_opt",
108748  "create_table",  "create_table_args",  "createkw",      "temp",
108749  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
108750  "select",        "column",        "columnid",      "type",
108751  "carglist",      "id",            "ids",           "typetoken",
108752  "typename",      "signed",        "plus_num",      "minus_num",
108753  "carg",          "ccons",         "term",          "expr",
108754  "onconf",        "sortorder",     "autoinc",       "idxlist_opt",
108755  "refargs",       "defer_subclause",  "refarg",        "refact",
108756  "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",
108757  "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",
108758  "ifexists",      "fullname",      "oneselect",     "multiselect_op",
108759  "distinct",      "selcollist",    "from",          "where_opt",
108760  "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",
108761  "sclp",          "as",            "seltablist",    "stl_prefix",
108762  "joinop",        "indexed_opt",   "on_opt",        "using_opt",
108763  "joinop2",       "inscollist",    "sortlist",      "nexprlist",
108764  "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",
108765  "exprlist",      "likeop",        "between_op",    "in_op",
108766  "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",
108767  "collate",       "nmnum",         "number",        "trigger_decl",
108768  "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
108769  "when_clause",   "trigger_cmd",   "trnm",          "tridxby",
108770  "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
108771  "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
108772  "lp",            "anylist",
108773};
108774#endif /* NDEBUG */
108775
108776#ifndef NDEBUG
108777/* For tracing reduce actions, the names of all rules are required.
108778*/
108779static const char *const yyRuleName[] = {
108780 /*   0 */ "input ::= cmdlist",
108781 /*   1 */ "cmdlist ::= cmdlist ecmd",
108782 /*   2 */ "cmdlist ::= ecmd",
108783 /*   3 */ "ecmd ::= SEMI",
108784 /*   4 */ "ecmd ::= explain cmdx SEMI",
108785 /*   5 */ "explain ::=",
108786 /*   6 */ "explain ::= EXPLAIN",
108787 /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
108788 /*   8 */ "cmdx ::= cmd",
108789 /*   9 */ "cmd ::= BEGIN transtype trans_opt",
108790 /*  10 */ "trans_opt ::=",
108791 /*  11 */ "trans_opt ::= TRANSACTION",
108792 /*  12 */ "trans_opt ::= TRANSACTION nm",
108793 /*  13 */ "transtype ::=",
108794 /*  14 */ "transtype ::= DEFERRED",
108795 /*  15 */ "transtype ::= IMMEDIATE",
108796 /*  16 */ "transtype ::= EXCLUSIVE",
108797 /*  17 */ "cmd ::= COMMIT trans_opt",
108798 /*  18 */ "cmd ::= END trans_opt",
108799 /*  19 */ "cmd ::= ROLLBACK trans_opt",
108800 /*  20 */ "savepoint_opt ::= SAVEPOINT",
108801 /*  21 */ "savepoint_opt ::=",
108802 /*  22 */ "cmd ::= SAVEPOINT nm",
108803 /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
108804 /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
108805 /*  25 */ "cmd ::= create_table create_table_args",
108806 /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
108807 /*  27 */ "createkw ::= CREATE",
108808 /*  28 */ "ifnotexists ::=",
108809 /*  29 */ "ifnotexists ::= IF NOT EXISTS",
108810 /*  30 */ "temp ::= TEMP",
108811 /*  31 */ "temp ::=",
108812 /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
108813 /*  33 */ "create_table_args ::= AS select",
108814 /*  34 */ "columnlist ::= columnlist COMMA column",
108815 /*  35 */ "columnlist ::= column",
108816 /*  36 */ "column ::= columnid type carglist",
108817 /*  37 */ "columnid ::= nm",
108818 /*  38 */ "id ::= ID",
108819 /*  39 */ "id ::= INDEXED",
108820 /*  40 */ "ids ::= ID|STRING",
108821 /*  41 */ "nm ::= id",
108822 /*  42 */ "nm ::= STRING",
108823 /*  43 */ "nm ::= JOIN_KW",
108824 /*  44 */ "type ::=",
108825 /*  45 */ "type ::= typetoken",
108826 /*  46 */ "typetoken ::= typename",
108827 /*  47 */ "typetoken ::= typename LP signed RP",
108828 /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
108829 /*  49 */ "typename ::= ids",
108830 /*  50 */ "typename ::= typename ids",
108831 /*  51 */ "signed ::= plus_num",
108832 /*  52 */ "signed ::= minus_num",
108833 /*  53 */ "carglist ::= carglist carg",
108834 /*  54 */ "carglist ::=",
108835 /*  55 */ "carg ::= CONSTRAINT nm ccons",
108836 /*  56 */ "carg ::= ccons",
108837 /*  57 */ "ccons ::= DEFAULT term",
108838 /*  58 */ "ccons ::= DEFAULT LP expr RP",
108839 /*  59 */ "ccons ::= DEFAULT PLUS term",
108840 /*  60 */ "ccons ::= DEFAULT MINUS term",
108841 /*  61 */ "ccons ::= DEFAULT id",
108842 /*  62 */ "ccons ::= NULL onconf",
108843 /*  63 */ "ccons ::= NOT NULL onconf",
108844 /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
108845 /*  65 */ "ccons ::= UNIQUE onconf",
108846 /*  66 */ "ccons ::= CHECK LP expr RP",
108847 /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
108848 /*  68 */ "ccons ::= defer_subclause",
108849 /*  69 */ "ccons ::= COLLATE ids",
108850 /*  70 */ "autoinc ::=",
108851 /*  71 */ "autoinc ::= AUTOINCR",
108852 /*  72 */ "refargs ::=",
108853 /*  73 */ "refargs ::= refargs refarg",
108854 /*  74 */ "refarg ::= MATCH nm",
108855 /*  75 */ "refarg ::= ON INSERT refact",
108856 /*  76 */ "refarg ::= ON DELETE refact",
108857 /*  77 */ "refarg ::= ON UPDATE refact",
108858 /*  78 */ "refact ::= SET NULL",
108859 /*  79 */ "refact ::= SET DEFAULT",
108860 /*  80 */ "refact ::= CASCADE",
108861 /*  81 */ "refact ::= RESTRICT",
108862 /*  82 */ "refact ::= NO ACTION",
108863 /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
108864 /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
108865 /*  85 */ "init_deferred_pred_opt ::=",
108866 /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
108867 /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
108868 /*  88 */ "conslist_opt ::=",
108869 /*  89 */ "conslist_opt ::= COMMA conslist",
108870 /*  90 */ "conslist ::= conslist COMMA tcons",
108871 /*  91 */ "conslist ::= conslist tcons",
108872 /*  92 */ "conslist ::= tcons",
108873 /*  93 */ "tcons ::= CONSTRAINT nm",
108874 /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
108875 /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
108876 /*  96 */ "tcons ::= CHECK LP expr RP onconf",
108877 /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
108878 /*  98 */ "defer_subclause_opt ::=",
108879 /*  99 */ "defer_subclause_opt ::= defer_subclause",
108880 /* 100 */ "onconf ::=",
108881 /* 101 */ "onconf ::= ON CONFLICT resolvetype",
108882 /* 102 */ "orconf ::=",
108883 /* 103 */ "orconf ::= OR resolvetype",
108884 /* 104 */ "resolvetype ::= raisetype",
108885 /* 105 */ "resolvetype ::= IGNORE",
108886 /* 106 */ "resolvetype ::= REPLACE",
108887 /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
108888 /* 108 */ "ifexists ::= IF EXISTS",
108889 /* 109 */ "ifexists ::=",
108890 /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
108891 /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
108892 /* 112 */ "cmd ::= select",
108893 /* 113 */ "select ::= oneselect",
108894 /* 114 */ "select ::= select multiselect_op oneselect",
108895 /* 115 */ "multiselect_op ::= UNION",
108896 /* 116 */ "multiselect_op ::= UNION ALL",
108897 /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
108898 /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
108899 /* 119 */ "distinct ::= DISTINCT",
108900 /* 120 */ "distinct ::= ALL",
108901 /* 121 */ "distinct ::=",
108902 /* 122 */ "sclp ::= selcollist COMMA",
108903 /* 123 */ "sclp ::=",
108904 /* 124 */ "selcollist ::= sclp expr as",
108905 /* 125 */ "selcollist ::= sclp STAR",
108906 /* 126 */ "selcollist ::= sclp nm DOT STAR",
108907 /* 127 */ "as ::= AS nm",
108908 /* 128 */ "as ::= ids",
108909 /* 129 */ "as ::=",
108910 /* 130 */ "from ::=",
108911 /* 131 */ "from ::= FROM seltablist",
108912 /* 132 */ "stl_prefix ::= seltablist joinop",
108913 /* 133 */ "stl_prefix ::=",
108914 /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
108915 /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
108916 /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
108917 /* 137 */ "dbnm ::=",
108918 /* 138 */ "dbnm ::= DOT nm",
108919 /* 139 */ "fullname ::= nm dbnm",
108920 /* 140 */ "joinop ::= COMMA|JOIN",
108921 /* 141 */ "joinop ::= JOIN_KW JOIN",
108922 /* 142 */ "joinop ::= JOIN_KW nm JOIN",
108923 /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
108924 /* 144 */ "on_opt ::= ON expr",
108925 /* 145 */ "on_opt ::=",
108926 /* 146 */ "indexed_opt ::=",
108927 /* 147 */ "indexed_opt ::= INDEXED BY nm",
108928 /* 148 */ "indexed_opt ::= NOT INDEXED",
108929 /* 149 */ "using_opt ::= USING LP inscollist RP",
108930 /* 150 */ "using_opt ::=",
108931 /* 151 */ "orderby_opt ::=",
108932 /* 152 */ "orderby_opt ::= ORDER BY sortlist",
108933 /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
108934 /* 154 */ "sortlist ::= expr sortorder",
108935 /* 155 */ "sortorder ::= ASC",
108936 /* 156 */ "sortorder ::= DESC",
108937 /* 157 */ "sortorder ::=",
108938 /* 158 */ "groupby_opt ::=",
108939 /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
108940 /* 160 */ "having_opt ::=",
108941 /* 161 */ "having_opt ::= HAVING expr",
108942 /* 162 */ "limit_opt ::=",
108943 /* 163 */ "limit_opt ::= LIMIT expr",
108944 /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
108945 /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
108946 /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
108947 /* 167 */ "where_opt ::=",
108948 /* 168 */ "where_opt ::= WHERE expr",
108949 /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
108950 /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
108951 /* 171 */ "setlist ::= nm EQ expr",
108952 /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
108953 /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
108954 /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
108955 /* 175 */ "insert_cmd ::= INSERT orconf",
108956 /* 176 */ "insert_cmd ::= REPLACE",
108957 /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
108958 /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
108959 /* 179 */ "inscollist_opt ::=",
108960 /* 180 */ "inscollist_opt ::= LP inscollist RP",
108961 /* 181 */ "inscollist ::= inscollist COMMA nm",
108962 /* 182 */ "inscollist ::= nm",
108963 /* 183 */ "expr ::= term",
108964 /* 184 */ "expr ::= LP expr RP",
108965 /* 185 */ "term ::= NULL",
108966 /* 186 */ "expr ::= id",
108967 /* 187 */ "expr ::= JOIN_KW",
108968 /* 188 */ "expr ::= nm DOT nm",
108969 /* 189 */ "expr ::= nm DOT nm DOT nm",
108970 /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
108971 /* 191 */ "term ::= STRING",
108972 /* 192 */ "expr ::= REGISTER",
108973 /* 193 */ "expr ::= VARIABLE",
108974 /* 194 */ "expr ::= expr COLLATE ids",
108975 /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
108976 /* 196 */ "expr ::= ID LP distinct exprlist RP",
108977 /* 197 */ "expr ::= ID LP STAR RP",
108978 /* 198 */ "term ::= CTIME_KW",
108979 /* 199 */ "expr ::= expr AND expr",
108980 /* 200 */ "expr ::= expr OR expr",
108981 /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
108982 /* 202 */ "expr ::= expr EQ|NE expr",
108983 /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
108984 /* 204 */ "expr ::= expr PLUS|MINUS expr",
108985 /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
108986 /* 206 */ "expr ::= expr CONCAT expr",
108987 /* 207 */ "likeop ::= LIKE_KW",
108988 /* 208 */ "likeop ::= NOT LIKE_KW",
108989 /* 209 */ "likeop ::= MATCH",
108990 /* 210 */ "likeop ::= NOT MATCH",
108991 /* 211 */ "expr ::= expr likeop expr",
108992 /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
108993 /* 213 */ "expr ::= expr ISNULL|NOTNULL",
108994 /* 214 */ "expr ::= expr NOT NULL",
108995 /* 215 */ "expr ::= expr IS expr",
108996 /* 216 */ "expr ::= expr IS NOT expr",
108997 /* 217 */ "expr ::= NOT expr",
108998 /* 218 */ "expr ::= BITNOT expr",
108999 /* 219 */ "expr ::= MINUS expr",
109000 /* 220 */ "expr ::= PLUS expr",
109001 /* 221 */ "between_op ::= BETWEEN",
109002 /* 222 */ "between_op ::= NOT BETWEEN",
109003 /* 223 */ "expr ::= expr between_op expr AND expr",
109004 /* 224 */ "in_op ::= IN",
109005 /* 225 */ "in_op ::= NOT IN",
109006 /* 226 */ "expr ::= expr in_op LP exprlist RP",
109007 /* 227 */ "expr ::= LP select RP",
109008 /* 228 */ "expr ::= expr in_op LP select RP",
109009 /* 229 */ "expr ::= expr in_op nm dbnm",
109010 /* 230 */ "expr ::= EXISTS LP select RP",
109011 /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
109012 /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
109013 /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
109014 /* 234 */ "case_else ::= ELSE expr",
109015 /* 235 */ "case_else ::=",
109016 /* 236 */ "case_operand ::= expr",
109017 /* 237 */ "case_operand ::=",
109018 /* 238 */ "exprlist ::= nexprlist",
109019 /* 239 */ "exprlist ::=",
109020 /* 240 */ "nexprlist ::= nexprlist COMMA expr",
109021 /* 241 */ "nexprlist ::= expr",
109022 /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
109023 /* 243 */ "uniqueflag ::= UNIQUE",
109024 /* 244 */ "uniqueflag ::=",
109025 /* 245 */ "idxlist_opt ::=",
109026 /* 246 */ "idxlist_opt ::= LP idxlist RP",
109027 /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
109028 /* 248 */ "idxlist ::= nm collate sortorder",
109029 /* 249 */ "collate ::=",
109030 /* 250 */ "collate ::= COLLATE ids",
109031 /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
109032 /* 252 */ "cmd ::= VACUUM",
109033 /* 253 */ "cmd ::= VACUUM nm",
109034 /* 254 */ "cmd ::= PRAGMA nm dbnm",
109035 /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
109036 /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
109037 /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
109038 /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
109039 /* 259 */ "nmnum ::= plus_num",
109040 /* 260 */ "nmnum ::= nm",
109041 /* 261 */ "nmnum ::= ON",
109042 /* 262 */ "nmnum ::= DELETE",
109043 /* 263 */ "nmnum ::= DEFAULT",
109044 /* 264 */ "plus_num ::= PLUS number",
109045 /* 265 */ "plus_num ::= number",
109046 /* 266 */ "minus_num ::= MINUS number",
109047 /* 267 */ "number ::= INTEGER|FLOAT",
109048 /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
109049 /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
109050 /* 270 */ "trigger_time ::= BEFORE",
109051 /* 271 */ "trigger_time ::= AFTER",
109052 /* 272 */ "trigger_time ::= INSTEAD OF",
109053 /* 273 */ "trigger_time ::=",
109054 /* 274 */ "trigger_event ::= DELETE|INSERT",
109055 /* 275 */ "trigger_event ::= UPDATE",
109056 /* 276 */ "trigger_event ::= UPDATE OF inscollist",
109057 /* 277 */ "foreach_clause ::=",
109058 /* 278 */ "foreach_clause ::= FOR EACH ROW",
109059 /* 279 */ "when_clause ::=",
109060 /* 280 */ "when_clause ::= WHEN expr",
109061 /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
109062 /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
109063 /* 283 */ "trnm ::= nm",
109064 /* 284 */ "trnm ::= nm DOT nm",
109065 /* 285 */ "tridxby ::=",
109066 /* 286 */ "tridxby ::= INDEXED BY nm",
109067 /* 287 */ "tridxby ::= NOT INDEXED",
109068 /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
109069 /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
109070 /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
109071 /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
109072 /* 292 */ "trigger_cmd ::= select",
109073 /* 293 */ "expr ::= RAISE LP IGNORE RP",
109074 /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
109075 /* 295 */ "raisetype ::= ROLLBACK",
109076 /* 296 */ "raisetype ::= ABORT",
109077 /* 297 */ "raisetype ::= FAIL",
109078 /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
109079 /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
109080 /* 300 */ "cmd ::= DETACH database_kw_opt expr",
109081 /* 301 */ "key_opt ::=",
109082 /* 302 */ "key_opt ::= KEY expr",
109083 /* 303 */ "database_kw_opt ::= DATABASE",
109084 /* 304 */ "database_kw_opt ::=",
109085 /* 305 */ "cmd ::= REINDEX",
109086 /* 306 */ "cmd ::= REINDEX nm dbnm",
109087 /* 307 */ "cmd ::= ANALYZE",
109088 /* 308 */ "cmd ::= ANALYZE nm dbnm",
109089 /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
109090 /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
109091 /* 311 */ "add_column_fullname ::= fullname",
109092 /* 312 */ "kwcolumn_opt ::=",
109093 /* 313 */ "kwcolumn_opt ::= COLUMNKW",
109094 /* 314 */ "cmd ::= create_vtab",
109095 /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
109096 /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
109097 /* 317 */ "vtabarglist ::= vtabarg",
109098 /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
109099 /* 319 */ "vtabarg ::=",
109100 /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
109101 /* 321 */ "vtabargtoken ::= ANY",
109102 /* 322 */ "vtabargtoken ::= lp anylist RP",
109103 /* 323 */ "lp ::= LP",
109104 /* 324 */ "anylist ::=",
109105 /* 325 */ "anylist ::= anylist LP anylist RP",
109106 /* 326 */ "anylist ::= anylist ANY",
109107};
109108#endif /* NDEBUG */
109109
109110
109111#if YYSTACKDEPTH<=0
109112/*
109113** Try to increase the size of the parser stack.
109114*/
109115static void yyGrowStack(yyParser *p){
109116  int newSize;
109117  yyStackEntry *pNew;
109118
109119  newSize = p->yystksz*2 + 100;
109120  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
109121  if( pNew ){
109122    p->yystack = pNew;
109123    p->yystksz = newSize;
109124#ifndef NDEBUG
109125    if( yyTraceFILE ){
109126      fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
109127              yyTracePrompt, p->yystksz);
109128    }
109129#endif
109130  }
109131}
109132#endif
109133
109134/*
109135** This function allocates a new parser.
109136** The only argument is a pointer to a function which works like
109137** malloc.
109138**
109139** Inputs:
109140** A pointer to the function used to allocate memory.
109141**
109142** Outputs:
109143** A pointer to a parser.  This pointer is used in subsequent calls
109144** to sqlite3Parser and sqlite3ParserFree.
109145*/
109146SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
109147  yyParser *pParser;
109148  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
109149  if( pParser ){
109150    pParser->yyidx = -1;
109151#ifdef YYTRACKMAXSTACKDEPTH
109152    pParser->yyidxMax = 0;
109153#endif
109154#if YYSTACKDEPTH<=0
109155    pParser->yystack = NULL;
109156    pParser->yystksz = 0;
109157    yyGrowStack(pParser);
109158#endif
109159  }
109160  return pParser;
109161}
109162
109163/* The following function deletes the value associated with a
109164** symbol.  The symbol can be either a terminal or nonterminal.
109165** "yymajor" is the symbol code, and "yypminor" is a pointer to
109166** the value.
109167*/
109168static void yy_destructor(
109169  yyParser *yypParser,    /* The parser */
109170  YYCODETYPE yymajor,     /* Type code for object to destroy */
109171  YYMINORTYPE *yypminor   /* The object to be destroyed */
109172){
109173  sqlite3ParserARG_FETCH;
109174  switch( yymajor ){
109175    /* Here is inserted the actions which take place when a
109176    ** terminal or non-terminal is destroyed.  This can happen
109177    ** when the symbol is popped from the stack during a
109178    ** reduce or during error processing or when a parser is
109179    ** being destroyed before it is finished parsing.
109180    **
109181    ** Note: during a reduce, the only symbols destroyed are those
109182    ** which appear on the RHS of the rule, but which are not used
109183    ** inside the C code.
109184    */
109185    case 160: /* select */
109186    case 194: /* oneselect */
109187{
109188sqlite3SelectDelete(pParse->db, (yypminor->yy159));
109189}
109190      break;
109191    case 174: /* term */
109192    case 175: /* expr */
109193{
109194sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
109195}
109196      break;
109197    case 179: /* idxlist_opt */
109198    case 187: /* idxlist */
109199    case 197: /* selcollist */
109200    case 200: /* groupby_opt */
109201    case 202: /* orderby_opt */
109202    case 204: /* sclp */
109203    case 214: /* sortlist */
109204    case 215: /* nexprlist */
109205    case 216: /* setlist */
109206    case 220: /* exprlist */
109207    case 225: /* case_exprlist */
109208{
109209sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
109210}
109211      break;
109212    case 193: /* fullname */
109213    case 198: /* from */
109214    case 206: /* seltablist */
109215    case 207: /* stl_prefix */
109216{
109217sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
109218}
109219      break;
109220    case 199: /* where_opt */
109221    case 201: /* having_opt */
109222    case 210: /* on_opt */
109223    case 224: /* case_operand */
109224    case 226: /* case_else */
109225    case 236: /* when_clause */
109226    case 241: /* key_opt */
109227{
109228sqlite3ExprDelete(pParse->db, (yypminor->yy122));
109229}
109230      break;
109231    case 211: /* using_opt */
109232    case 213: /* inscollist */
109233    case 218: /* inscollist_opt */
109234{
109235sqlite3IdListDelete(pParse->db, (yypminor->yy180));
109236}
109237      break;
109238    case 219: /* valuelist */
109239{
109240
109241  sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
109242  sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
109243
109244}
109245      break;
109246    case 232: /* trigger_cmd_list */
109247    case 237: /* trigger_cmd */
109248{
109249sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
109250}
109251      break;
109252    case 234: /* trigger_event */
109253{
109254sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
109255}
109256      break;
109257    default:  break;   /* If no destructor action specified: do nothing */
109258  }
109259}
109260
109261/*
109262** Pop the parser's stack once.
109263**
109264** If there is a destructor routine associated with the token which
109265** is popped from the stack, then call it.
109266**
109267** Return the major token number for the symbol popped.
109268*/
109269static int yy_pop_parser_stack(yyParser *pParser){
109270  YYCODETYPE yymajor;
109271  yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
109272
109273  /* There is no mechanism by which the parser stack can be popped below
109274  ** empty in SQLite.  */
109275  if( NEVER(pParser->yyidx<0) ) return 0;
109276#ifndef NDEBUG
109277  if( yyTraceFILE && pParser->yyidx>=0 ){
109278    fprintf(yyTraceFILE,"%sPopping %s\n",
109279      yyTracePrompt,
109280      yyTokenName[yytos->major]);
109281  }
109282#endif
109283  yymajor = yytos->major;
109284  yy_destructor(pParser, yymajor, &yytos->minor);
109285  pParser->yyidx--;
109286  return yymajor;
109287}
109288
109289/*
109290** Deallocate and destroy a parser.  Destructors are all called for
109291** all stack elements before shutting the parser down.
109292**
109293** Inputs:
109294** <ul>
109295** <li>  A pointer to the parser.  This should be a pointer
109296**       obtained from sqlite3ParserAlloc.
109297** <li>  A pointer to a function used to reclaim memory obtained
109298**       from malloc.
109299** </ul>
109300*/
109301SQLITE_PRIVATE void sqlite3ParserFree(
109302  void *p,                    /* The parser to be deleted */
109303  void (*freeProc)(void*)     /* Function used to reclaim memory */
109304){
109305  yyParser *pParser = (yyParser*)p;
109306  /* In SQLite, we never try to destroy a parser that was not successfully
109307  ** created in the first place. */
109308  if( NEVER(pParser==0) ) return;
109309  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
109310#if YYSTACKDEPTH<=0
109311  free(pParser->yystack);
109312#endif
109313  (*freeProc)((void*)pParser);
109314}
109315
109316/*
109317** Return the peak depth of the stack for a parser.
109318*/
109319#ifdef YYTRACKMAXSTACKDEPTH
109320SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
109321  yyParser *pParser = (yyParser*)p;
109322  return pParser->yyidxMax;
109323}
109324#endif
109325
109326/*
109327** Find the appropriate action for a parser given the terminal
109328** look-ahead token iLookAhead.
109329**
109330** If the look-ahead token is YYNOCODE, then check to see if the action is
109331** independent of the look-ahead.  If it is, return the action, otherwise
109332** return YY_NO_ACTION.
109333*/
109334static int yy_find_shift_action(
109335  yyParser *pParser,        /* The parser */
109336  YYCODETYPE iLookAhead     /* The look-ahead token */
109337){
109338  int i;
109339  int stateno = pParser->yystack[pParser->yyidx].stateno;
109340
109341  if( stateno>YY_SHIFT_COUNT
109342   || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
109343    return yy_default[stateno];
109344  }
109345  assert( iLookAhead!=YYNOCODE );
109346  i += iLookAhead;
109347  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
109348    if( iLookAhead>0 ){
109349#ifdef YYFALLBACK
109350      YYCODETYPE iFallback;            /* Fallback token */
109351      if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
109352             && (iFallback = yyFallback[iLookAhead])!=0 ){
109353#ifndef NDEBUG
109354        if( yyTraceFILE ){
109355          fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
109356             yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
109357        }
109358#endif
109359        return yy_find_shift_action(pParser, iFallback);
109360      }
109361#endif
109362#ifdef YYWILDCARD
109363      {
109364        int j = i - iLookAhead + YYWILDCARD;
109365        if(
109366#if YY_SHIFT_MIN+YYWILDCARD<0
109367          j>=0 &&
109368#endif
109369#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
109370          j<YY_ACTTAB_COUNT &&
109371#endif
109372          yy_lookahead[j]==YYWILDCARD
109373        ){
109374#ifndef NDEBUG
109375          if( yyTraceFILE ){
109376            fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
109377               yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
109378          }
109379#endif /* NDEBUG */
109380          return yy_action[j];
109381        }
109382      }
109383#endif /* YYWILDCARD */
109384    }
109385    return yy_default[stateno];
109386  }else{
109387    return yy_action[i];
109388  }
109389}
109390
109391/*
109392** Find the appropriate action for a parser given the non-terminal
109393** look-ahead token iLookAhead.
109394**
109395** If the look-ahead token is YYNOCODE, then check to see if the action is
109396** independent of the look-ahead.  If it is, return the action, otherwise
109397** return YY_NO_ACTION.
109398*/
109399static int yy_find_reduce_action(
109400  int stateno,              /* Current state number */
109401  YYCODETYPE iLookAhead     /* The look-ahead token */
109402){
109403  int i;
109404#ifdef YYERRORSYMBOL
109405  if( stateno>YY_REDUCE_COUNT ){
109406    return yy_default[stateno];
109407  }
109408#else
109409  assert( stateno<=YY_REDUCE_COUNT );
109410#endif
109411  i = yy_reduce_ofst[stateno];
109412  assert( i!=YY_REDUCE_USE_DFLT );
109413  assert( iLookAhead!=YYNOCODE );
109414  i += iLookAhead;
109415#ifdef YYERRORSYMBOL
109416  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
109417    return yy_default[stateno];
109418  }
109419#else
109420  assert( i>=0 && i<YY_ACTTAB_COUNT );
109421  assert( yy_lookahead[i]==iLookAhead );
109422#endif
109423  return yy_action[i];
109424}
109425
109426/*
109427** The following routine is called if the stack overflows.
109428*/
109429static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
109430   sqlite3ParserARG_FETCH;
109431   yypParser->yyidx--;
109432#ifndef NDEBUG
109433   if( yyTraceFILE ){
109434     fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
109435   }
109436#endif
109437   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
109438   /* Here code is inserted which will execute if the parser
109439   ** stack every overflows */
109440
109441  UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
109442  sqlite3ErrorMsg(pParse, "parser stack overflow");
109443   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
109444}
109445
109446/*
109447** Perform a shift action.
109448*/
109449static void yy_shift(
109450  yyParser *yypParser,          /* The parser to be shifted */
109451  int yyNewState,               /* The new state to shift in */
109452  int yyMajor,                  /* The major token to shift in */
109453  YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
109454){
109455  yyStackEntry *yytos;
109456  yypParser->yyidx++;
109457#ifdef YYTRACKMAXSTACKDEPTH
109458  if( yypParser->yyidx>yypParser->yyidxMax ){
109459    yypParser->yyidxMax = yypParser->yyidx;
109460  }
109461#endif
109462#if YYSTACKDEPTH>0
109463  if( yypParser->yyidx>=YYSTACKDEPTH ){
109464    yyStackOverflow(yypParser, yypMinor);
109465    return;
109466  }
109467#else
109468  if( yypParser->yyidx>=yypParser->yystksz ){
109469    yyGrowStack(yypParser);
109470    if( yypParser->yyidx>=yypParser->yystksz ){
109471      yyStackOverflow(yypParser, yypMinor);
109472      return;
109473    }
109474  }
109475#endif
109476  yytos = &yypParser->yystack[yypParser->yyidx];
109477  yytos->stateno = (YYACTIONTYPE)yyNewState;
109478  yytos->major = (YYCODETYPE)yyMajor;
109479  yytos->minor = *yypMinor;
109480#ifndef NDEBUG
109481  if( yyTraceFILE && yypParser->yyidx>0 ){
109482    int i;
109483    fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
109484    fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
109485    for(i=1; i<=yypParser->yyidx; i++)
109486      fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
109487    fprintf(yyTraceFILE,"\n");
109488  }
109489#endif
109490}
109491
109492/* The following table contains information about every rule that
109493** is used during the reduce.
109494*/
109495static const struct {
109496  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
109497  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
109498} yyRuleInfo[] = {
109499  { 142, 1 },
109500  { 143, 2 },
109501  { 143, 1 },
109502  { 144, 1 },
109503  { 144, 3 },
109504  { 145, 0 },
109505  { 145, 1 },
109506  { 145, 3 },
109507  { 146, 1 },
109508  { 147, 3 },
109509  { 149, 0 },
109510  { 149, 1 },
109511  { 149, 2 },
109512  { 148, 0 },
109513  { 148, 1 },
109514  { 148, 1 },
109515  { 148, 1 },
109516  { 147, 2 },
109517  { 147, 2 },
109518  { 147, 2 },
109519  { 151, 1 },
109520  { 151, 0 },
109521  { 147, 2 },
109522  { 147, 3 },
109523  { 147, 5 },
109524  { 147, 2 },
109525  { 152, 6 },
109526  { 154, 1 },
109527  { 156, 0 },
109528  { 156, 3 },
109529  { 155, 1 },
109530  { 155, 0 },
109531  { 153, 4 },
109532  { 153, 2 },
109533  { 158, 3 },
109534  { 158, 1 },
109535  { 161, 3 },
109536  { 162, 1 },
109537  { 165, 1 },
109538  { 165, 1 },
109539  { 166, 1 },
109540  { 150, 1 },
109541  { 150, 1 },
109542  { 150, 1 },
109543  { 163, 0 },
109544  { 163, 1 },
109545  { 167, 1 },
109546  { 167, 4 },
109547  { 167, 6 },
109548  { 168, 1 },
109549  { 168, 2 },
109550  { 169, 1 },
109551  { 169, 1 },
109552  { 164, 2 },
109553  { 164, 0 },
109554  { 172, 3 },
109555  { 172, 1 },
109556  { 173, 2 },
109557  { 173, 4 },
109558  { 173, 3 },
109559  { 173, 3 },
109560  { 173, 2 },
109561  { 173, 2 },
109562  { 173, 3 },
109563  { 173, 5 },
109564  { 173, 2 },
109565  { 173, 4 },
109566  { 173, 4 },
109567  { 173, 1 },
109568  { 173, 2 },
109569  { 178, 0 },
109570  { 178, 1 },
109571  { 180, 0 },
109572  { 180, 2 },
109573  { 182, 2 },
109574  { 182, 3 },
109575  { 182, 3 },
109576  { 182, 3 },
109577  { 183, 2 },
109578  { 183, 2 },
109579  { 183, 1 },
109580  { 183, 1 },
109581  { 183, 2 },
109582  { 181, 3 },
109583  { 181, 2 },
109584  { 184, 0 },
109585  { 184, 2 },
109586  { 184, 2 },
109587  { 159, 0 },
109588  { 159, 2 },
109589  { 185, 3 },
109590  { 185, 2 },
109591  { 185, 1 },
109592  { 186, 2 },
109593  { 186, 7 },
109594  { 186, 5 },
109595  { 186, 5 },
109596  { 186, 10 },
109597  { 188, 0 },
109598  { 188, 1 },
109599  { 176, 0 },
109600  { 176, 3 },
109601  { 189, 0 },
109602  { 189, 2 },
109603  { 190, 1 },
109604  { 190, 1 },
109605  { 190, 1 },
109606  { 147, 4 },
109607  { 192, 2 },
109608  { 192, 0 },
109609  { 147, 8 },
109610  { 147, 4 },
109611  { 147, 1 },
109612  { 160, 1 },
109613  { 160, 3 },
109614  { 195, 1 },
109615  { 195, 2 },
109616  { 195, 1 },
109617  { 194, 9 },
109618  { 196, 1 },
109619  { 196, 1 },
109620  { 196, 0 },
109621  { 204, 2 },
109622  { 204, 0 },
109623  { 197, 3 },
109624  { 197, 2 },
109625  { 197, 4 },
109626  { 205, 2 },
109627  { 205, 1 },
109628  { 205, 0 },
109629  { 198, 0 },
109630  { 198, 2 },
109631  { 207, 2 },
109632  { 207, 0 },
109633  { 206, 7 },
109634  { 206, 7 },
109635  { 206, 7 },
109636  { 157, 0 },
109637  { 157, 2 },
109638  { 193, 2 },
109639  { 208, 1 },
109640  { 208, 2 },
109641  { 208, 3 },
109642  { 208, 4 },
109643  { 210, 2 },
109644  { 210, 0 },
109645  { 209, 0 },
109646  { 209, 3 },
109647  { 209, 2 },
109648  { 211, 4 },
109649  { 211, 0 },
109650  { 202, 0 },
109651  { 202, 3 },
109652  { 214, 4 },
109653  { 214, 2 },
109654  { 177, 1 },
109655  { 177, 1 },
109656  { 177, 0 },
109657  { 200, 0 },
109658  { 200, 3 },
109659  { 201, 0 },
109660  { 201, 2 },
109661  { 203, 0 },
109662  { 203, 2 },
109663  { 203, 4 },
109664  { 203, 4 },
109665  { 147, 5 },
109666  { 199, 0 },
109667  { 199, 2 },
109668  { 147, 7 },
109669  { 216, 5 },
109670  { 216, 3 },
109671  { 147, 5 },
109672  { 147, 5 },
109673  { 147, 6 },
109674  { 217, 2 },
109675  { 217, 1 },
109676  { 219, 4 },
109677  { 219, 5 },
109678  { 218, 0 },
109679  { 218, 3 },
109680  { 213, 3 },
109681  { 213, 1 },
109682  { 175, 1 },
109683  { 175, 3 },
109684  { 174, 1 },
109685  { 175, 1 },
109686  { 175, 1 },
109687  { 175, 3 },
109688  { 175, 5 },
109689  { 174, 1 },
109690  { 174, 1 },
109691  { 175, 1 },
109692  { 175, 1 },
109693  { 175, 3 },
109694  { 175, 6 },
109695  { 175, 5 },
109696  { 175, 4 },
109697  { 174, 1 },
109698  { 175, 3 },
109699  { 175, 3 },
109700  { 175, 3 },
109701  { 175, 3 },
109702  { 175, 3 },
109703  { 175, 3 },
109704  { 175, 3 },
109705  { 175, 3 },
109706  { 221, 1 },
109707  { 221, 2 },
109708  { 221, 1 },
109709  { 221, 2 },
109710  { 175, 3 },
109711  { 175, 5 },
109712  { 175, 2 },
109713  { 175, 3 },
109714  { 175, 3 },
109715  { 175, 4 },
109716  { 175, 2 },
109717  { 175, 2 },
109718  { 175, 2 },
109719  { 175, 2 },
109720  { 222, 1 },
109721  { 222, 2 },
109722  { 175, 5 },
109723  { 223, 1 },
109724  { 223, 2 },
109725  { 175, 5 },
109726  { 175, 3 },
109727  { 175, 5 },
109728  { 175, 4 },
109729  { 175, 4 },
109730  { 175, 5 },
109731  { 225, 5 },
109732  { 225, 4 },
109733  { 226, 2 },
109734  { 226, 0 },
109735  { 224, 1 },
109736  { 224, 0 },
109737  { 220, 1 },
109738  { 220, 0 },
109739  { 215, 3 },
109740  { 215, 1 },
109741  { 147, 11 },
109742  { 227, 1 },
109743  { 227, 0 },
109744  { 179, 0 },
109745  { 179, 3 },
109746  { 187, 5 },
109747  { 187, 3 },
109748  { 228, 0 },
109749  { 228, 2 },
109750  { 147, 4 },
109751  { 147, 1 },
109752  { 147, 2 },
109753  { 147, 3 },
109754  { 147, 5 },
109755  { 147, 6 },
109756  { 147, 5 },
109757  { 147, 6 },
109758  { 229, 1 },
109759  { 229, 1 },
109760  { 229, 1 },
109761  { 229, 1 },
109762  { 229, 1 },
109763  { 170, 2 },
109764  { 170, 1 },
109765  { 171, 2 },
109766  { 230, 1 },
109767  { 147, 5 },
109768  { 231, 11 },
109769  { 233, 1 },
109770  { 233, 1 },
109771  { 233, 2 },
109772  { 233, 0 },
109773  { 234, 1 },
109774  { 234, 1 },
109775  { 234, 3 },
109776  { 235, 0 },
109777  { 235, 3 },
109778  { 236, 0 },
109779  { 236, 2 },
109780  { 232, 3 },
109781  { 232, 2 },
109782  { 238, 1 },
109783  { 238, 3 },
109784  { 239, 0 },
109785  { 239, 3 },
109786  { 239, 2 },
109787  { 237, 7 },
109788  { 237, 5 },
109789  { 237, 5 },
109790  { 237, 5 },
109791  { 237, 1 },
109792  { 175, 4 },
109793  { 175, 6 },
109794  { 191, 1 },
109795  { 191, 1 },
109796  { 191, 1 },
109797  { 147, 4 },
109798  { 147, 6 },
109799  { 147, 3 },
109800  { 241, 0 },
109801  { 241, 2 },
109802  { 240, 1 },
109803  { 240, 0 },
109804  { 147, 1 },
109805  { 147, 3 },
109806  { 147, 1 },
109807  { 147, 3 },
109808  { 147, 6 },
109809  { 147, 6 },
109810  { 242, 1 },
109811  { 243, 0 },
109812  { 243, 1 },
109813  { 147, 1 },
109814  { 147, 4 },
109815  { 244, 8 },
109816  { 245, 1 },
109817  { 245, 3 },
109818  { 246, 0 },
109819  { 246, 2 },
109820  { 247, 1 },
109821  { 247, 3 },
109822  { 248, 1 },
109823  { 249, 0 },
109824  { 249, 4 },
109825  { 249, 2 },
109826};
109827
109828static void yy_accept(yyParser*);  /* Forward Declaration */
109829
109830/*
109831** Perform a reduce action and the shift that must immediately
109832** follow the reduce.
109833*/
109834static void yy_reduce(
109835  yyParser *yypParser,         /* The parser */
109836  int yyruleno                 /* Number of the rule by which to reduce */
109837){
109838  int yygoto;                     /* The next state */
109839  int yyact;                      /* The next action */
109840  YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
109841  yyStackEntry *yymsp;            /* The top of the parser's stack */
109842  int yysize;                     /* Amount to pop the stack */
109843  sqlite3ParserARG_FETCH;
109844  yymsp = &yypParser->yystack[yypParser->yyidx];
109845#ifndef NDEBUG
109846  if( yyTraceFILE && yyruleno>=0
109847        && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
109848    fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
109849      yyRuleName[yyruleno]);
109850  }
109851#endif /* NDEBUG */
109852
109853  /* Silence complaints from purify about yygotominor being uninitialized
109854  ** in some cases when it is copied into the stack after the following
109855  ** switch.  yygotominor is uninitialized when a rule reduces that does
109856  ** not set the value of its left-hand side nonterminal.  Leaving the
109857  ** value of the nonterminal uninitialized is utterly harmless as long
109858  ** as the value is never used.  So really the only thing this code
109859  ** accomplishes is to quieten purify.
109860  **
109861  ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
109862  ** without this code, their parser segfaults.  I'm not sure what there
109863  ** parser is doing to make this happen.  This is the second bug report
109864  ** from wireshark this week.  Clearly they are stressing Lemon in ways
109865  ** that it has not been previously stressed...  (SQLite ticket #2172)
109866  */
109867  /*memset(&yygotominor, 0, sizeof(yygotominor));*/
109868  yygotominor = yyzerominor;
109869
109870
109871  switch( yyruleno ){
109872  /* Beginning here are the reduction cases.  A typical example
109873  ** follows:
109874  **   case 0:
109875  **  #line <lineno> <grammarfile>
109876  **     { ... }           // User supplied code
109877  **  #line <lineno> <thisfile>
109878  **     break;
109879  */
109880      case 5: /* explain ::= */
109881{ sqlite3BeginParse(pParse, 0); }
109882        break;
109883      case 6: /* explain ::= EXPLAIN */
109884{ sqlite3BeginParse(pParse, 1); }
109885        break;
109886      case 7: /* explain ::= EXPLAIN QUERY PLAN */
109887{ sqlite3BeginParse(pParse, 2); }
109888        break;
109889      case 8: /* cmdx ::= cmd */
109890{ sqlite3FinishCoding(pParse); }
109891        break;
109892      case 9: /* cmd ::= BEGIN transtype trans_opt */
109893{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
109894        break;
109895      case 13: /* transtype ::= */
109896{yygotominor.yy392 = TK_DEFERRED;}
109897        break;
109898      case 14: /* transtype ::= DEFERRED */
109899      case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
109900      case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
109901      case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
109902      case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
109903{yygotominor.yy392 = yymsp[0].major;}
109904        break;
109905      case 17: /* cmd ::= COMMIT trans_opt */
109906      case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
109907{sqlite3CommitTransaction(pParse);}
109908        break;
109909      case 19: /* cmd ::= ROLLBACK trans_opt */
109910{sqlite3RollbackTransaction(pParse);}
109911        break;
109912      case 22: /* cmd ::= SAVEPOINT nm */
109913{
109914  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
109915}
109916        break;
109917      case 23: /* cmd ::= RELEASE savepoint_opt nm */
109918{
109919  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
109920}
109921        break;
109922      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
109923{
109924  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
109925}
109926        break;
109927      case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
109928{
109929   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
109930}
109931        break;
109932      case 27: /* createkw ::= CREATE */
109933{
109934  pParse->db->lookaside.bEnabled = 0;
109935  yygotominor.yy0 = yymsp[0].minor.yy0;
109936}
109937        break;
109938      case 28: /* ifnotexists ::= */
109939      case 31: /* temp ::= */ yytestcase(yyruleno==31);
109940      case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
109941      case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
109942      case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
109943      case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
109944      case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
109945      case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
109946      case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
109947      case 121: /* distinct ::= */ yytestcase(yyruleno==121);
109948      case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
109949      case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
109950{yygotominor.yy392 = 0;}
109951        break;
109952      case 29: /* ifnotexists ::= IF NOT EXISTS */
109953      case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
109954      case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
109955      case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
109956      case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
109957      case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
109958      case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
109959      case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
109960{yygotominor.yy392 = 1;}
109961        break;
109962      case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
109963{
109964  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
109965}
109966        break;
109967      case 33: /* create_table_args ::= AS select */
109968{
109969  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
109970  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
109971}
109972        break;
109973      case 36: /* column ::= columnid type carglist */
109974{
109975  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
109976  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
109977}
109978        break;
109979      case 37: /* columnid ::= nm */
109980{
109981  sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
109982  yygotominor.yy0 = yymsp[0].minor.yy0;
109983}
109984        break;
109985      case 38: /* id ::= ID */
109986      case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
109987      case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
109988      case 41: /* nm ::= id */ yytestcase(yyruleno==41);
109989      case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
109990      case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
109991      case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
109992      case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
109993      case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
109994      case 128: /* as ::= ids */ yytestcase(yyruleno==128);
109995      case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
109996      case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
109997      case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
109998      case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
109999      case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
110000      case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
110001      case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
110002      case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
110003      case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
110004      case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
110005      case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
110006      case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
110007      case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
110008{yygotominor.yy0 = yymsp[0].minor.yy0;}
110009        break;
110010      case 45: /* type ::= typetoken */
110011{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
110012        break;
110013      case 47: /* typetoken ::= typename LP signed RP */
110014{
110015  yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
110016  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
110017}
110018        break;
110019      case 48: /* typetoken ::= typename LP signed COMMA signed RP */
110020{
110021  yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
110022  yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
110023}
110024        break;
110025      case 50: /* typename ::= typename ids */
110026{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);}
110027        break;
110028      case 57: /* ccons ::= DEFAULT term */
110029      case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
110030{sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
110031        break;
110032      case 58: /* ccons ::= DEFAULT LP expr RP */
110033{sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
110034        break;
110035      case 60: /* ccons ::= DEFAULT MINUS term */
110036{
110037  ExprSpan v;
110038  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
110039  v.zStart = yymsp[-1].minor.yy0.z;
110040  v.zEnd = yymsp[0].minor.yy342.zEnd;
110041  sqlite3AddDefaultValue(pParse,&v);
110042}
110043        break;
110044      case 61: /* ccons ::= DEFAULT id */
110045{
110046  ExprSpan v;
110047  spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
110048  sqlite3AddDefaultValue(pParse,&v);
110049}
110050        break;
110051      case 63: /* ccons ::= NOT NULL onconf */
110052{sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
110053        break;
110054      case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
110055{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
110056        break;
110057      case 65: /* ccons ::= UNIQUE onconf */
110058{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
110059        break;
110060      case 66: /* ccons ::= CHECK LP expr RP */
110061{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
110062        break;
110063      case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
110064{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
110065        break;
110066      case 68: /* ccons ::= defer_subclause */
110067{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
110068        break;
110069      case 69: /* ccons ::= COLLATE ids */
110070{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
110071        break;
110072      case 72: /* refargs ::= */
110073{ yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
110074        break;
110075      case 73: /* refargs ::= refargs refarg */
110076{ yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
110077        break;
110078      case 74: /* refarg ::= MATCH nm */
110079      case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
110080{ yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
110081        break;
110082      case 76: /* refarg ::= ON DELETE refact */
110083{ yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
110084        break;
110085      case 77: /* refarg ::= ON UPDATE refact */
110086{ yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
110087        break;
110088      case 78: /* refact ::= SET NULL */
110089{ yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
110090        break;
110091      case 79: /* refact ::= SET DEFAULT */
110092{ yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
110093        break;
110094      case 80: /* refact ::= CASCADE */
110095{ yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
110096        break;
110097      case 81: /* refact ::= RESTRICT */
110098{ yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
110099        break;
110100      case 82: /* refact ::= NO ACTION */
110101{ yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
110102        break;
110103      case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
110104      case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
110105      case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
110106      case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
110107{yygotominor.yy392 = yymsp[0].minor.yy392;}
110108        break;
110109      case 88: /* conslist_opt ::= */
110110{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
110111        break;
110112      case 89: /* conslist_opt ::= COMMA conslist */
110113{yygotominor.yy0 = yymsp[-1].minor.yy0;}
110114        break;
110115      case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
110116{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
110117        break;
110118      case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
110119{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
110120        break;
110121      case 96: /* tcons ::= CHECK LP expr RP onconf */
110122{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
110123        break;
110124      case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
110125{
110126    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
110127    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
110128}
110129        break;
110130      case 100: /* onconf ::= */
110131{yygotominor.yy392 = OE_Default;}
110132        break;
110133      case 102: /* orconf ::= */
110134{yygotominor.yy258 = OE_Default;}
110135        break;
110136      case 103: /* orconf ::= OR resolvetype */
110137{yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
110138        break;
110139      case 105: /* resolvetype ::= IGNORE */
110140{yygotominor.yy392 = OE_Ignore;}
110141        break;
110142      case 106: /* resolvetype ::= REPLACE */
110143{yygotominor.yy392 = OE_Replace;}
110144        break;
110145      case 107: /* cmd ::= DROP TABLE ifexists fullname */
110146{
110147  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
110148}
110149        break;
110150      case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
110151{
110152  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
110153}
110154        break;
110155      case 111: /* cmd ::= DROP VIEW ifexists fullname */
110156{
110157  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
110158}
110159        break;
110160      case 112: /* cmd ::= select */
110161{
110162  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
110163  sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
110164  sqlite3ExplainBegin(pParse->pVdbe);
110165  sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
110166  sqlite3ExplainFinish(pParse->pVdbe);
110167  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
110168}
110169        break;
110170      case 113: /* select ::= oneselect */
110171{yygotominor.yy159 = yymsp[0].minor.yy159;}
110172        break;
110173      case 114: /* select ::= select multiselect_op oneselect */
110174{
110175  if( yymsp[0].minor.yy159 ){
110176    yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
110177    yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
110178  }else{
110179    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
110180  }
110181  yygotominor.yy159 = yymsp[0].minor.yy159;
110182}
110183        break;
110184      case 116: /* multiselect_op ::= UNION ALL */
110185{yygotominor.yy392 = TK_ALL;}
110186        break;
110187      case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
110188{
110189  yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
110190}
110191        break;
110192      case 122: /* sclp ::= selcollist COMMA */
110193      case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
110194{yygotominor.yy442 = yymsp[-1].minor.yy442;}
110195        break;
110196      case 123: /* sclp ::= */
110197      case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
110198      case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
110199      case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
110200      case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
110201{yygotominor.yy442 = 0;}
110202        break;
110203      case 124: /* selcollist ::= sclp expr as */
110204{
110205   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
110206   if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
110207   sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
110208}
110209        break;
110210      case 125: /* selcollist ::= sclp STAR */
110211{
110212  Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
110213  yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
110214}
110215        break;
110216      case 126: /* selcollist ::= sclp nm DOT STAR */
110217{
110218  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
110219  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110220  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
110221  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
110222}
110223        break;
110224      case 129: /* as ::= */
110225{yygotominor.yy0.n = 0;}
110226        break;
110227      case 130: /* from ::= */
110228{yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
110229        break;
110230      case 131: /* from ::= FROM seltablist */
110231{
110232  yygotominor.yy347 = yymsp[0].minor.yy347;
110233  sqlite3SrcListShiftJoinType(yygotominor.yy347);
110234}
110235        break;
110236      case 132: /* stl_prefix ::= seltablist joinop */
110237{
110238   yygotominor.yy347 = yymsp[-1].minor.yy347;
110239   if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
110240}
110241        break;
110242      case 133: /* stl_prefix ::= */
110243{yygotominor.yy347 = 0;}
110244        break;
110245      case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
110246{
110247  yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
110248  sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
110249}
110250        break;
110251      case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
110252{
110253    yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
110254  }
110255        break;
110256      case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
110257{
110258    if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
110259      yygotominor.yy347 = yymsp[-4].minor.yy347;
110260    }else{
110261      Select *pSubquery;
110262      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
110263      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,0,0,0);
110264      yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
110265    }
110266  }
110267        break;
110268      case 137: /* dbnm ::= */
110269      case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
110270{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
110271        break;
110272      case 139: /* fullname ::= nm dbnm */
110273{yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
110274        break;
110275      case 140: /* joinop ::= COMMA|JOIN */
110276{ yygotominor.yy392 = JT_INNER; }
110277        break;
110278      case 141: /* joinop ::= JOIN_KW JOIN */
110279{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
110280        break;
110281      case 142: /* joinop ::= JOIN_KW nm JOIN */
110282{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
110283        break;
110284      case 143: /* joinop ::= JOIN_KW nm nm JOIN */
110285{ yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
110286        break;
110287      case 144: /* on_opt ::= ON expr */
110288      case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
110289      case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
110290      case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
110291      case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
110292{yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
110293        break;
110294      case 145: /* on_opt ::= */
110295      case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
110296      case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
110297      case 235: /* case_else ::= */ yytestcase(yyruleno==235);
110298      case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
110299{yygotominor.yy122 = 0;}
110300        break;
110301      case 148: /* indexed_opt ::= NOT INDEXED */
110302{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
110303        break;
110304      case 149: /* using_opt ::= USING LP inscollist RP */
110305      case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
110306{yygotominor.yy180 = yymsp[-1].minor.yy180;}
110307        break;
110308      case 150: /* using_opt ::= */
110309      case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
110310{yygotominor.yy180 = 0;}
110311        break;
110312      case 152: /* orderby_opt ::= ORDER BY sortlist */
110313      case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
110314      case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
110315{yygotominor.yy442 = yymsp[0].minor.yy442;}
110316        break;
110317      case 153: /* sortlist ::= sortlist COMMA expr sortorder */
110318{
110319  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
110320  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
110321}
110322        break;
110323      case 154: /* sortlist ::= expr sortorder */
110324{
110325  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
110326  if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
110327}
110328        break;
110329      case 155: /* sortorder ::= ASC */
110330      case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
110331{yygotominor.yy392 = SQLITE_SO_ASC;}
110332        break;
110333      case 156: /* sortorder ::= DESC */
110334{yygotominor.yy392 = SQLITE_SO_DESC;}
110335        break;
110336      case 162: /* limit_opt ::= */
110337{yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
110338        break;
110339      case 163: /* limit_opt ::= LIMIT expr */
110340{yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
110341        break;
110342      case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
110343{yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
110344        break;
110345      case 165: /* limit_opt ::= LIMIT expr COMMA expr */
110346{yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
110347        break;
110348      case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
110349{
110350  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
110351  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
110352}
110353        break;
110354      case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
110355{
110356  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
110357  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
110358  sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
110359}
110360        break;
110361      case 170: /* setlist ::= setlist COMMA nm EQ expr */
110362{
110363  yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
110364  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
110365}
110366        break;
110367      case 171: /* setlist ::= nm EQ expr */
110368{
110369  yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
110370  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
110371}
110372        break;
110373      case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
110374{sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
110375        break;
110376      case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
110377{sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
110378        break;
110379      case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
110380{sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
110381        break;
110382      case 175: /* insert_cmd ::= INSERT orconf */
110383{yygotominor.yy258 = yymsp[0].minor.yy258;}
110384        break;
110385      case 176: /* insert_cmd ::= REPLACE */
110386{yygotominor.yy258 = OE_Replace;}
110387        break;
110388      case 177: /* valuelist ::= VALUES LP nexprlist RP */
110389{
110390  yygotominor.yy487.pList = yymsp[-1].minor.yy442;
110391  yygotominor.yy487.pSelect = 0;
110392}
110393        break;
110394      case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
110395{
110396  Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
110397  if( yymsp[-4].minor.yy487.pList ){
110398    yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
110399    yymsp[-4].minor.yy487.pList = 0;
110400  }
110401  yygotominor.yy487.pList = 0;
110402  if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
110403    sqlite3SelectDelete(pParse->db, pRight);
110404    sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
110405    yygotominor.yy487.pSelect = 0;
110406  }else{
110407    pRight->op = TK_ALL;
110408    pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
110409    pRight->selFlags |= SF_Values;
110410    pRight->pPrior->selFlags |= SF_Values;
110411    yygotominor.yy487.pSelect = pRight;
110412  }
110413}
110414        break;
110415      case 181: /* inscollist ::= inscollist COMMA nm */
110416{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
110417        break;
110418      case 182: /* inscollist ::= nm */
110419{yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
110420        break;
110421      case 183: /* expr ::= term */
110422{yygotominor.yy342 = yymsp[0].minor.yy342;}
110423        break;
110424      case 184: /* expr ::= LP expr RP */
110425{yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
110426        break;
110427      case 185: /* term ::= NULL */
110428      case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
110429      case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
110430{spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
110431        break;
110432      case 186: /* expr ::= id */
110433      case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
110434{spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
110435        break;
110436      case 188: /* expr ::= nm DOT nm */
110437{
110438  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110439  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
110440  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
110441  spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
110442}
110443        break;
110444      case 189: /* expr ::= nm DOT nm DOT nm */
110445{
110446  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
110447  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
110448  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
110449  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
110450  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
110451  spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110452}
110453        break;
110454      case 192: /* expr ::= REGISTER */
110455{
110456  /* When doing a nested parse, one can include terms in an expression
110457  ** that look like this:   #1 #2 ...  These terms refer to registers
110458  ** in the virtual machine.  #N is the N-th register. */
110459  if( pParse->nested==0 ){
110460    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
110461    yygotominor.yy342.pExpr = 0;
110462  }else{
110463    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
110464    if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
110465  }
110466  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110467}
110468        break;
110469      case 193: /* expr ::= VARIABLE */
110470{
110471  spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
110472  sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
110473  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110474}
110475        break;
110476      case 194: /* expr ::= expr COLLATE ids */
110477{
110478  yygotominor.yy342.pExpr = sqlite3ExprSetCollByToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
110479  yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
110480  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110481}
110482        break;
110483      case 195: /* expr ::= CAST LP expr AS typetoken RP */
110484{
110485  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
110486  spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
110487}
110488        break;
110489      case 196: /* expr ::= ID LP distinct exprlist RP */
110490{
110491  if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
110492    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
110493  }
110494  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
110495  spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
110496  if( yymsp[-2].minor.yy392 && yygotominor.yy342.pExpr ){
110497    yygotominor.yy342.pExpr->flags |= EP_Distinct;
110498  }
110499}
110500        break;
110501      case 197: /* expr ::= ID LP STAR RP */
110502{
110503  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
110504  spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
110505}
110506        break;
110507      case 198: /* term ::= CTIME_KW */
110508{
110509  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
110510  ** treated as functions that return constants */
110511  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
110512  if( yygotominor.yy342.pExpr ){
110513    yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
110514  }
110515  spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
110516}
110517        break;
110518      case 199: /* expr ::= expr AND expr */
110519      case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
110520      case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
110521      case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
110522      case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
110523      case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
110524      case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
110525      case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
110526{spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
110527        break;
110528      case 207: /* likeop ::= LIKE_KW */
110529      case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
110530{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 0;}
110531        break;
110532      case 208: /* likeop ::= NOT LIKE_KW */
110533      case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
110534{yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.not = 1;}
110535        break;
110536      case 211: /* expr ::= expr likeop expr */
110537{
110538  ExprList *pList;
110539  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
110540  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
110541  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
110542  if( yymsp[-1].minor.yy318.not ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110543  yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
110544  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
110545  if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
110546}
110547        break;
110548      case 212: /* expr ::= expr likeop expr ESCAPE expr */
110549{
110550  ExprList *pList;
110551  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
110552  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
110553  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
110554  yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
110555  if( yymsp[-3].minor.yy318.not ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110556  yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110557  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
110558  if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
110559}
110560        break;
110561      case 213: /* expr ::= expr ISNULL|NOTNULL */
110562{spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
110563        break;
110564      case 214: /* expr ::= expr NOT NULL */
110565{spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
110566        break;
110567      case 215: /* expr ::= expr IS expr */
110568{
110569  spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
110570  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
110571}
110572        break;
110573      case 216: /* expr ::= expr IS NOT expr */
110574{
110575  spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
110576  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
110577}
110578        break;
110579      case 217: /* expr ::= NOT expr */
110580      case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
110581{spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
110582        break;
110583      case 219: /* expr ::= MINUS expr */
110584{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
110585        break;
110586      case 220: /* expr ::= PLUS expr */
110587{spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
110588        break;
110589      case 223: /* expr ::= expr between_op expr AND expr */
110590{
110591  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
110592  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
110593  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
110594  if( yygotominor.yy342.pExpr ){
110595    yygotominor.yy342.pExpr->x.pList = pList;
110596  }else{
110597    sqlite3ExprListDelete(pParse->db, pList);
110598  }
110599  if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110600  yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110601  yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
110602}
110603        break;
110604      case 226: /* expr ::= expr in_op LP exprlist RP */
110605{
110606    if( yymsp[-1].minor.yy442==0 ){
110607      /* Expressions of the form
110608      **
110609      **      expr1 IN ()
110610      **      expr1 NOT IN ()
110611      **
110612      ** simplify to constants 0 (false) and 1 (true), respectively,
110613      ** regardless of the value of expr1.
110614      */
110615      yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
110616      sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
110617    }else{
110618      yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
110619      if( yygotominor.yy342.pExpr ){
110620        yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
110621        sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110622      }else{
110623        sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
110624      }
110625      if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110626    }
110627    yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110628    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110629  }
110630        break;
110631      case 227: /* expr ::= LP select RP */
110632{
110633    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
110634    if( yygotominor.yy342.pExpr ){
110635      yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
110636      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
110637      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110638    }else{
110639      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
110640    }
110641    yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
110642    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110643  }
110644        break;
110645      case 228: /* expr ::= expr in_op LP select RP */
110646{
110647    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
110648    if( yygotominor.yy342.pExpr ){
110649      yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
110650      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
110651      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110652    }else{
110653      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
110654    }
110655    if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110656    yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
110657    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110658  }
110659        break;
110660      case 229: /* expr ::= expr in_op nm dbnm */
110661{
110662    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
110663    yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
110664    if( yygotominor.yy342.pExpr ){
110665      yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
110666      ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
110667      sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110668    }else{
110669      sqlite3SrcListDelete(pParse->db, pSrc);
110670    }
110671    if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
110672    yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
110673    yygotominor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
110674  }
110675        break;
110676      case 230: /* expr ::= EXISTS LP select RP */
110677{
110678    Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
110679    if( p ){
110680      p->x.pSelect = yymsp[-1].minor.yy159;
110681      ExprSetProperty(p, EP_xIsSelect);
110682      sqlite3ExprSetHeight(pParse, p);
110683    }else{
110684      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
110685    }
110686    yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
110687    yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110688  }
110689        break;
110690      case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
110691{
110692  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
110693  if( yygotominor.yy342.pExpr ){
110694    yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
110695    sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
110696  }else{
110697    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
110698  }
110699  yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
110700  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110701}
110702        break;
110703      case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
110704{
110705  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
110706  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
110707}
110708        break;
110709      case 233: /* case_exprlist ::= WHEN expr THEN expr */
110710{
110711  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
110712  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
110713}
110714        break;
110715      case 240: /* nexprlist ::= nexprlist COMMA expr */
110716{yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
110717        break;
110718      case 241: /* nexprlist ::= expr */
110719{yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
110720        break;
110721      case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
110722{
110723  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0,
110724                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
110725                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
110726}
110727        break;
110728      case 243: /* uniqueflag ::= UNIQUE */
110729      case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
110730{yygotominor.yy392 = OE_Abort;}
110731        break;
110732      case 244: /* uniqueflag ::= */
110733{yygotominor.yy392 = OE_None;}
110734        break;
110735      case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
110736{
110737  Expr *p = 0;
110738  if( yymsp[-1].minor.yy0.n>0 ){
110739    p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
110740    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
110741  }
110742  yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
110743  sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
110744  sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
110745  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
110746}
110747        break;
110748      case 248: /* idxlist ::= nm collate sortorder */
110749{
110750  Expr *p = 0;
110751  if( yymsp[-1].minor.yy0.n>0 ){
110752    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
110753    sqlite3ExprSetCollByToken(pParse, p, &yymsp[-1].minor.yy0);
110754  }
110755  yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
110756  sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
110757  sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
110758  if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
110759}
110760        break;
110761      case 249: /* collate ::= */
110762{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
110763        break;
110764      case 251: /* cmd ::= DROP INDEX ifexists fullname */
110765{sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
110766        break;
110767      case 252: /* cmd ::= VACUUM */
110768      case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
110769{sqlite3Vacuum(pParse);}
110770        break;
110771      case 254: /* cmd ::= PRAGMA nm dbnm */
110772{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
110773        break;
110774      case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
110775{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
110776        break;
110777      case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
110778{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
110779        break;
110780      case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
110781{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
110782        break;
110783      case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
110784{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
110785        break;
110786      case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
110787{
110788  Token all;
110789  all.z = yymsp[-3].minor.yy0.z;
110790  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
110791  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
110792}
110793        break;
110794      case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
110795{
110796  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
110797  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
110798}
110799        break;
110800      case 270: /* trigger_time ::= BEFORE */
110801      case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
110802{ yygotominor.yy392 = TK_BEFORE; }
110803        break;
110804      case 271: /* trigger_time ::= AFTER */
110805{ yygotominor.yy392 = TK_AFTER;  }
110806        break;
110807      case 272: /* trigger_time ::= INSTEAD OF */
110808{ yygotominor.yy392 = TK_INSTEAD;}
110809        break;
110810      case 274: /* trigger_event ::= DELETE|INSERT */
110811      case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
110812{yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
110813        break;
110814      case 276: /* trigger_event ::= UPDATE OF inscollist */
110815{yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
110816        break;
110817      case 279: /* when_clause ::= */
110818      case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
110819{ yygotominor.yy122 = 0; }
110820        break;
110821      case 280: /* when_clause ::= WHEN expr */
110822      case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
110823{ yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
110824        break;
110825      case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
110826{
110827  assert( yymsp[-2].minor.yy327!=0 );
110828  yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
110829  yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
110830  yygotominor.yy327 = yymsp[-2].minor.yy327;
110831}
110832        break;
110833      case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
110834{
110835  assert( yymsp[-1].minor.yy327!=0 );
110836  yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
110837  yygotominor.yy327 = yymsp[-1].minor.yy327;
110838}
110839        break;
110840      case 284: /* trnm ::= nm DOT nm */
110841{
110842  yygotominor.yy0 = yymsp[0].minor.yy0;
110843  sqlite3ErrorMsg(pParse,
110844        "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
110845        "statements within triggers");
110846}
110847        break;
110848      case 286: /* tridxby ::= INDEXED BY nm */
110849{
110850  sqlite3ErrorMsg(pParse,
110851        "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
110852        "within triggers");
110853}
110854        break;
110855      case 287: /* tridxby ::= NOT INDEXED */
110856{
110857  sqlite3ErrorMsg(pParse,
110858        "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
110859        "within triggers");
110860}
110861        break;
110862      case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
110863{ yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
110864        break;
110865      case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
110866{yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
110867        break;
110868      case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
110869{yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
110870        break;
110871      case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
110872{yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
110873        break;
110874      case 292: /* trigger_cmd ::= select */
110875{yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
110876        break;
110877      case 293: /* expr ::= RAISE LP IGNORE RP */
110878{
110879  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
110880  if( yygotominor.yy342.pExpr ){
110881    yygotominor.yy342.pExpr->affinity = OE_Ignore;
110882  }
110883  yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
110884  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110885}
110886        break;
110887      case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
110888{
110889  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
110890  if( yygotominor.yy342.pExpr ) {
110891    yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
110892  }
110893  yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
110894  yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
110895}
110896        break;
110897      case 295: /* raisetype ::= ROLLBACK */
110898{yygotominor.yy392 = OE_Rollback;}
110899        break;
110900      case 297: /* raisetype ::= FAIL */
110901{yygotominor.yy392 = OE_Fail;}
110902        break;
110903      case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
110904{
110905  sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
110906}
110907        break;
110908      case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
110909{
110910  sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
110911}
110912        break;
110913      case 300: /* cmd ::= DETACH database_kw_opt expr */
110914{
110915  sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
110916}
110917        break;
110918      case 305: /* cmd ::= REINDEX */
110919{sqlite3Reindex(pParse, 0, 0);}
110920        break;
110921      case 306: /* cmd ::= REINDEX nm dbnm */
110922{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110923        break;
110924      case 307: /* cmd ::= ANALYZE */
110925{sqlite3Analyze(pParse, 0, 0);}
110926        break;
110927      case 308: /* cmd ::= ANALYZE nm dbnm */
110928{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
110929        break;
110930      case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
110931{
110932  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
110933}
110934        break;
110935      case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
110936{
110937  sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
110938}
110939        break;
110940      case 311: /* add_column_fullname ::= fullname */
110941{
110942  pParse->db->lookaside.bEnabled = 0;
110943  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
110944}
110945        break;
110946      case 314: /* cmd ::= create_vtab */
110947{sqlite3VtabFinishParse(pParse,0);}
110948        break;
110949      case 315: /* cmd ::= create_vtab LP vtabarglist RP */
110950{sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
110951        break;
110952      case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
110953{
110954    sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
110955}
110956        break;
110957      case 319: /* vtabarg ::= */
110958{sqlite3VtabArgInit(pParse);}
110959        break;
110960      case 321: /* vtabargtoken ::= ANY */
110961      case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
110962      case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
110963{sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
110964        break;
110965      default:
110966      /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
110967      /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
110968      /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
110969      /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
110970      /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
110971      /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
110972      /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
110973      /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
110974      /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
110975      /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
110976      /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
110977      /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
110978      /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
110979      /* (44) type ::= */ yytestcase(yyruleno==44);
110980      /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
110981      /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
110982      /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
110983      /* (54) carglist ::= */ yytestcase(yyruleno==54);
110984      /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
110985      /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
110986      /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
110987      /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
110988      /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
110989      /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
110990      /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
110991      /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
110992      /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
110993      /* (285) tridxby ::= */ yytestcase(yyruleno==285);
110994      /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
110995      /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
110996      /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
110997      /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
110998      /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
110999      /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
111000      /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
111001      /* (324) anylist ::= */ yytestcase(yyruleno==324);
111002      /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
111003      /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
111004        break;
111005  };
111006  yygoto = yyRuleInfo[yyruleno].lhs;
111007  yysize = yyRuleInfo[yyruleno].nrhs;
111008  yypParser->yyidx -= yysize;
111009  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
111010  if( yyact < YYNSTATE ){
111011#ifdef NDEBUG
111012    /* If we are not debugging and the reduce action popped at least
111013    ** one element off the stack, then we can push the new element back
111014    ** onto the stack here, and skip the stack overflow test in yy_shift().
111015    ** That gives a significant speed improvement. */
111016    if( yysize ){
111017      yypParser->yyidx++;
111018      yymsp -= yysize-1;
111019      yymsp->stateno = (YYACTIONTYPE)yyact;
111020      yymsp->major = (YYCODETYPE)yygoto;
111021      yymsp->minor = yygotominor;
111022    }else
111023#endif
111024    {
111025      yy_shift(yypParser,yyact,yygoto,&yygotominor);
111026    }
111027  }else{
111028    assert( yyact == YYNSTATE + YYNRULE + 1 );
111029    yy_accept(yypParser);
111030  }
111031}
111032
111033/*
111034** The following code executes when the parse fails
111035*/
111036#ifndef YYNOERRORRECOVERY
111037static void yy_parse_failed(
111038  yyParser *yypParser           /* The parser */
111039){
111040  sqlite3ParserARG_FETCH;
111041#ifndef NDEBUG
111042  if( yyTraceFILE ){
111043    fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
111044  }
111045#endif
111046  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111047  /* Here code is inserted which will be executed whenever the
111048  ** parser fails */
111049  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111050}
111051#endif /* YYNOERRORRECOVERY */
111052
111053/*
111054** The following code executes when a syntax error first occurs.
111055*/
111056static void yy_syntax_error(
111057  yyParser *yypParser,           /* The parser */
111058  int yymajor,                   /* The major type of the error token */
111059  YYMINORTYPE yyminor            /* The minor type of the error token */
111060){
111061  sqlite3ParserARG_FETCH;
111062#define TOKEN (yyminor.yy0)
111063
111064  UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
111065  assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
111066  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
111067  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111068}
111069
111070/*
111071** The following is executed when the parser accepts
111072*/
111073static void yy_accept(
111074  yyParser *yypParser           /* The parser */
111075){
111076  sqlite3ParserARG_FETCH;
111077#ifndef NDEBUG
111078  if( yyTraceFILE ){
111079    fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
111080  }
111081#endif
111082  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111083  /* Here code is inserted which will be executed whenever the
111084  ** parser accepts */
111085  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
111086}
111087
111088/* The main parser program.
111089** The first argument is a pointer to a structure obtained from
111090** "sqlite3ParserAlloc" which describes the current state of the parser.
111091** The second argument is the major token number.  The third is
111092** the minor token.  The fourth optional argument is whatever the
111093** user wants (and specified in the grammar) and is available for
111094** use by the action routines.
111095**
111096** Inputs:
111097** <ul>
111098** <li> A pointer to the parser (an opaque structure.)
111099** <li> The major token number.
111100** <li> The minor token number.
111101** <li> An option argument of a grammar-specified type.
111102** </ul>
111103**
111104** Outputs:
111105** None.
111106*/
111107SQLITE_PRIVATE void sqlite3Parser(
111108  void *yyp,                   /* The parser */
111109  int yymajor,                 /* The major token code number */
111110  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
111111  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
111112){
111113  YYMINORTYPE yyminorunion;
111114  int yyact;            /* The parser action. */
111115#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
111116  int yyendofinput;     /* True if we are at the end of input */
111117#endif
111118#ifdef YYERRORSYMBOL
111119  int yyerrorhit = 0;   /* True if yymajor has invoked an error */
111120#endif
111121  yyParser *yypParser;  /* The parser */
111122
111123  /* (re)initialize the parser, if necessary */
111124  yypParser = (yyParser*)yyp;
111125  if( yypParser->yyidx<0 ){
111126#if YYSTACKDEPTH<=0
111127    if( yypParser->yystksz <=0 ){
111128      /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
111129      yyminorunion = yyzerominor;
111130      yyStackOverflow(yypParser, &yyminorunion);
111131      return;
111132    }
111133#endif
111134    yypParser->yyidx = 0;
111135    yypParser->yyerrcnt = -1;
111136    yypParser->yystack[0].stateno = 0;
111137    yypParser->yystack[0].major = 0;
111138  }
111139  yyminorunion.yy0 = yyminor;
111140#if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
111141  yyendofinput = (yymajor==0);
111142#endif
111143  sqlite3ParserARG_STORE;
111144
111145#ifndef NDEBUG
111146  if( yyTraceFILE ){
111147    fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
111148  }
111149#endif
111150
111151  do{
111152    yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
111153    if( yyact<YYNSTATE ){
111154      yy_shift(yypParser,yyact,yymajor,&yyminorunion);
111155      yypParser->yyerrcnt--;
111156      yymajor = YYNOCODE;
111157    }else if( yyact < YYNSTATE + YYNRULE ){
111158      yy_reduce(yypParser,yyact-YYNSTATE);
111159    }else{
111160      assert( yyact == YY_ERROR_ACTION );
111161#ifdef YYERRORSYMBOL
111162      int yymx;
111163#endif
111164#ifndef NDEBUG
111165      if( yyTraceFILE ){
111166        fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
111167      }
111168#endif
111169#ifdef YYERRORSYMBOL
111170      /* A syntax error has occurred.
111171      ** The response to an error depends upon whether or not the
111172      ** grammar defines an error token "ERROR".
111173      **
111174      ** This is what we do if the grammar does define ERROR:
111175      **
111176      **  * Call the %syntax_error function.
111177      **
111178      **  * Begin popping the stack until we enter a state where
111179      **    it is legal to shift the error symbol, then shift
111180      **    the error symbol.
111181      **
111182      **  * Set the error count to three.
111183      **
111184      **  * Begin accepting and shifting new tokens.  No new error
111185      **    processing will occur until three tokens have been
111186      **    shifted successfully.
111187      **
111188      */
111189      if( yypParser->yyerrcnt<0 ){
111190        yy_syntax_error(yypParser,yymajor,yyminorunion);
111191      }
111192      yymx = yypParser->yystack[yypParser->yyidx].major;
111193      if( yymx==YYERRORSYMBOL || yyerrorhit ){
111194#ifndef NDEBUG
111195        if( yyTraceFILE ){
111196          fprintf(yyTraceFILE,"%sDiscard input token %s\n",
111197             yyTracePrompt,yyTokenName[yymajor]);
111198        }
111199#endif
111200        yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
111201        yymajor = YYNOCODE;
111202      }else{
111203         while(
111204          yypParser->yyidx >= 0 &&
111205          yymx != YYERRORSYMBOL &&
111206          (yyact = yy_find_reduce_action(
111207                        yypParser->yystack[yypParser->yyidx].stateno,
111208                        YYERRORSYMBOL)) >= YYNSTATE
111209        ){
111210          yy_pop_parser_stack(yypParser);
111211        }
111212        if( yypParser->yyidx < 0 || yymajor==0 ){
111213          yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
111214          yy_parse_failed(yypParser);
111215          yymajor = YYNOCODE;
111216        }else if( yymx!=YYERRORSYMBOL ){
111217          YYMINORTYPE u2;
111218          u2.YYERRSYMDT = 0;
111219          yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
111220        }
111221      }
111222      yypParser->yyerrcnt = 3;
111223      yyerrorhit = 1;
111224#elif defined(YYNOERRORRECOVERY)
111225      /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
111226      ** do any kind of error recovery.  Instead, simply invoke the syntax
111227      ** error routine and continue going as if nothing had happened.
111228      **
111229      ** Applications can set this macro (for example inside %include) if
111230      ** they intend to abandon the parse upon the first syntax error seen.
111231      */
111232      yy_syntax_error(yypParser,yymajor,yyminorunion);
111233      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
111234      yymajor = YYNOCODE;
111235
111236#else  /* YYERRORSYMBOL is not defined */
111237      /* This is what we do if the grammar does not define ERROR:
111238      **
111239      **  * Report an error message, and throw away the input token.
111240      **
111241      **  * If the input token is $, then fail the parse.
111242      **
111243      ** As before, subsequent error messages are suppressed until
111244      ** three input tokens have been successfully shifted.
111245      */
111246      if( yypParser->yyerrcnt<=0 ){
111247        yy_syntax_error(yypParser,yymajor,yyminorunion);
111248      }
111249      yypParser->yyerrcnt = 3;
111250      yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
111251      if( yyendofinput ){
111252        yy_parse_failed(yypParser);
111253      }
111254      yymajor = YYNOCODE;
111255#endif
111256    }
111257  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
111258  return;
111259}
111260
111261/************** End of parse.c ***********************************************/
111262/************** Begin file tokenize.c ****************************************/
111263/*
111264** 2001 September 15
111265**
111266** The author disclaims copyright to this source code.  In place of
111267** a legal notice, here is a blessing:
111268**
111269**    May you do good and not evil.
111270**    May you find forgiveness for yourself and forgive others.
111271**    May you share freely, never taking more than you give.
111272**
111273*************************************************************************
111274** An tokenizer for SQL
111275**
111276** This file contains C code that splits an SQL input string up into
111277** individual tokens and sends those tokens one-by-one over to the
111278** parser for analysis.
111279*/
111280/* #include <stdlib.h> */
111281
111282/*
111283** The charMap() macro maps alphabetic characters into their
111284** lower-case ASCII equivalent.  On ASCII machines, this is just
111285** an upper-to-lower case map.  On EBCDIC machines we also need
111286** to adjust the encoding.  Only alphabetic characters and underscores
111287** need to be translated.
111288*/
111289#ifdef SQLITE_ASCII
111290# define charMap(X) sqlite3UpperToLower[(unsigned char)X]
111291#endif
111292#ifdef SQLITE_EBCDIC
111293# define charMap(X) ebcdicToAscii[(unsigned char)X]
111294const unsigned char ebcdicToAscii[] = {
111295/* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
111296   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
111297   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
111298   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
111299   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
111300   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
111301   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
111302   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
111303   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
111304   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
111305   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
111306   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
111307   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
111308   0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
111309   0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
111310   0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
111311   0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
111312};
111313#endif
111314
111315/*
111316** The sqlite3KeywordCode function looks up an identifier to determine if
111317** it is a keyword.  If it is a keyword, the token code of that keyword is
111318** returned.  If the input is not a keyword, TK_ID is returned.
111319**
111320** The implementation of this routine was generated by a program,
111321** mkkeywordhash.h, located in the tool subdirectory of the distribution.
111322** The output of the mkkeywordhash.c program is written into a file
111323** named keywordhash.h and then included into this source file by
111324** the #include below.
111325*/
111326/************** Include keywordhash.h in the middle of tokenize.c ************/
111327/************** Begin file keywordhash.h *************************************/
111328/***** This file contains automatically generated code ******
111329**
111330** The code in this file has been automatically generated by
111331**
111332**   sqlite/tool/mkkeywordhash.c
111333**
111334** The code in this file implements a function that determines whether
111335** or not a given identifier is really an SQL keyword.  The same thing
111336** might be implemented more directly using a hand-written hash table.
111337** But by using this automatically generated code, the size of the code
111338** is substantially reduced.  This is important for embedded applications
111339** on platforms with limited memory.
111340*/
111341/* Hash score: 175 */
111342static int keywordCode(const char *z, int n){
111343  /* zText[] encodes 811 bytes of keywords in 541 bytes */
111344  /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
111345  /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
111346  /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
111347  /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
111348  /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
111349  /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
111350  /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
111351  /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
111352  /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
111353  /*   INITIALLY                                                          */
111354  static const char zText[540] = {
111355    'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
111356    'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
111357    'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
111358    'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
111359    'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
111360    'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
111361    'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
111362    'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
111363    'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
111364    'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
111365    'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
111366    'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
111367    'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
111368    'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
111369    'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
111370    'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
111371    'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
111372    'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
111373    'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
111374    'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
111375    'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
111376    'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
111377    'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
111378    'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
111379    'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
111380    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
111381    'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
111382    'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
111383    'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
111384    'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
111385  };
111386  static const unsigned char aHash[127] = {
111387      72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
111388      42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
111389     118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
111390       0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
111391       0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
111392      92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
111393      96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
111394      39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
111395      58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
111396      29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
111397  };
111398  static const unsigned char aNext[121] = {
111399       0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
111400       0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
111401       0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
111402       0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
111403       0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
111404      62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
111405      61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
111406       0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
111407     103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
111408      35,  64,   0,   0,
111409  };
111410  static const unsigned char aLen[121] = {
111411       7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
111412       7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
111413      11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
111414       4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
111415       5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
111416       7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
111417       7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
111418       6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
111419       4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
111420       6,   4,   9,   3,
111421  };
111422  static const unsigned short int aOffset[121] = {
111423       0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
111424      36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
111425      86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
111426     159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
111427     203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
111428     248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
111429     326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
111430     387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
111431     462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
111432     521, 527, 531, 536,
111433  };
111434  static const unsigned char aCode[121] = {
111435    TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,
111436    TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,
111437    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,
111438    TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,
111439    TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,
111440    TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,
111441    TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,
111442    TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
111443    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,
111444    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,
111445    TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,
111446    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,
111447    TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,
111448    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,
111449    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,
111450    TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,
111451    TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,
111452    TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,
111453    TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,
111454    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,
111455    TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,
111456    TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,
111457    TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,
111458    TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,
111459    TK_ALL,
111460  };
111461  int h, i;
111462  if( n<2 ) return TK_ID;
111463  h = ((charMap(z[0])*4) ^
111464      (charMap(z[n-1])*3) ^
111465      n) % 127;
111466  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
111467    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
111468      testcase( i==0 ); /* REINDEX */
111469      testcase( i==1 ); /* INDEXED */
111470      testcase( i==2 ); /* INDEX */
111471      testcase( i==3 ); /* DESC */
111472      testcase( i==4 ); /* ESCAPE */
111473      testcase( i==5 ); /* EACH */
111474      testcase( i==6 ); /* CHECK */
111475      testcase( i==7 ); /* KEY */
111476      testcase( i==8 ); /* BEFORE */
111477      testcase( i==9 ); /* FOREIGN */
111478      testcase( i==10 ); /* FOR */
111479      testcase( i==11 ); /* IGNORE */
111480      testcase( i==12 ); /* REGEXP */
111481      testcase( i==13 ); /* EXPLAIN */
111482      testcase( i==14 ); /* INSTEAD */
111483      testcase( i==15 ); /* ADD */
111484      testcase( i==16 ); /* DATABASE */
111485      testcase( i==17 ); /* AS */
111486      testcase( i==18 ); /* SELECT */
111487      testcase( i==19 ); /* TABLE */
111488      testcase( i==20 ); /* LEFT */
111489      testcase( i==21 ); /* THEN */
111490      testcase( i==22 ); /* END */
111491      testcase( i==23 ); /* DEFERRABLE */
111492      testcase( i==24 ); /* ELSE */
111493      testcase( i==25 ); /* EXCEPT */
111494      testcase( i==26 ); /* TRANSACTION */
111495      testcase( i==27 ); /* ACTION */
111496      testcase( i==28 ); /* ON */
111497      testcase( i==29 ); /* NATURAL */
111498      testcase( i==30 ); /* ALTER */
111499      testcase( i==31 ); /* RAISE */
111500      testcase( i==32 ); /* EXCLUSIVE */
111501      testcase( i==33 ); /* EXISTS */
111502      testcase( i==34 ); /* SAVEPOINT */
111503      testcase( i==35 ); /* INTERSECT */
111504      testcase( i==36 ); /* TRIGGER */
111505      testcase( i==37 ); /* REFERENCES */
111506      testcase( i==38 ); /* CONSTRAINT */
111507      testcase( i==39 ); /* INTO */
111508      testcase( i==40 ); /* OFFSET */
111509      testcase( i==41 ); /* OF */
111510      testcase( i==42 ); /* SET */
111511      testcase( i==43 ); /* TEMPORARY */
111512      testcase( i==44 ); /* TEMP */
111513      testcase( i==45 ); /* OR */
111514      testcase( i==46 ); /* UNIQUE */
111515      testcase( i==47 ); /* QUERY */
111516      testcase( i==48 ); /* ATTACH */
111517      testcase( i==49 ); /* HAVING */
111518      testcase( i==50 ); /* GROUP */
111519      testcase( i==51 ); /* UPDATE */
111520      testcase( i==52 ); /* BEGIN */
111521      testcase( i==53 ); /* INNER */
111522      testcase( i==54 ); /* RELEASE */
111523      testcase( i==55 ); /* BETWEEN */
111524      testcase( i==56 ); /* NOTNULL */
111525      testcase( i==57 ); /* NOT */
111526      testcase( i==58 ); /* NO */
111527      testcase( i==59 ); /* NULL */
111528      testcase( i==60 ); /* LIKE */
111529      testcase( i==61 ); /* CASCADE */
111530      testcase( i==62 ); /* ASC */
111531      testcase( i==63 ); /* DELETE */
111532      testcase( i==64 ); /* CASE */
111533      testcase( i==65 ); /* COLLATE */
111534      testcase( i==66 ); /* CREATE */
111535      testcase( i==67 ); /* CURRENT_DATE */
111536      testcase( i==68 ); /* DETACH */
111537      testcase( i==69 ); /* IMMEDIATE */
111538      testcase( i==70 ); /* JOIN */
111539      testcase( i==71 ); /* INSERT */
111540      testcase( i==72 ); /* MATCH */
111541      testcase( i==73 ); /* PLAN */
111542      testcase( i==74 ); /* ANALYZE */
111543      testcase( i==75 ); /* PRAGMA */
111544      testcase( i==76 ); /* ABORT */
111545      testcase( i==77 ); /* VALUES */
111546      testcase( i==78 ); /* VIRTUAL */
111547      testcase( i==79 ); /* LIMIT */
111548      testcase( i==80 ); /* WHEN */
111549      testcase( i==81 ); /* WHERE */
111550      testcase( i==82 ); /* RENAME */
111551      testcase( i==83 ); /* AFTER */
111552      testcase( i==84 ); /* REPLACE */
111553      testcase( i==85 ); /* AND */
111554      testcase( i==86 ); /* DEFAULT */
111555      testcase( i==87 ); /* AUTOINCREMENT */
111556      testcase( i==88 ); /* TO */
111557      testcase( i==89 ); /* IN */
111558      testcase( i==90 ); /* CAST */
111559      testcase( i==91 ); /* COLUMN */
111560      testcase( i==92 ); /* COMMIT */
111561      testcase( i==93 ); /* CONFLICT */
111562      testcase( i==94 ); /* CROSS */
111563      testcase( i==95 ); /* CURRENT_TIMESTAMP */
111564      testcase( i==96 ); /* CURRENT_TIME */
111565      testcase( i==97 ); /* PRIMARY */
111566      testcase( i==98 ); /* DEFERRED */
111567      testcase( i==99 ); /* DISTINCT */
111568      testcase( i==100 ); /* IS */
111569      testcase( i==101 ); /* DROP */
111570      testcase( i==102 ); /* FAIL */
111571      testcase( i==103 ); /* FROM */
111572      testcase( i==104 ); /* FULL */
111573      testcase( i==105 ); /* GLOB */
111574      testcase( i==106 ); /* BY */
111575      testcase( i==107 ); /* IF */
111576      testcase( i==108 ); /* ISNULL */
111577      testcase( i==109 ); /* ORDER */
111578      testcase( i==110 ); /* RESTRICT */
111579      testcase( i==111 ); /* OUTER */
111580      testcase( i==112 ); /* RIGHT */
111581      testcase( i==113 ); /* ROLLBACK */
111582      testcase( i==114 ); /* ROW */
111583      testcase( i==115 ); /* UNION */
111584      testcase( i==116 ); /* USING */
111585      testcase( i==117 ); /* VACUUM */
111586      testcase( i==118 ); /* VIEW */
111587      testcase( i==119 ); /* INITIALLY */
111588      testcase( i==120 ); /* ALL */
111589      return aCode[i];
111590    }
111591  }
111592  return TK_ID;
111593}
111594SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
111595  return keywordCode((char*)z, n);
111596}
111597#define SQLITE_N_KEYWORD 121
111598
111599/************** End of keywordhash.h *****************************************/
111600/************** Continuing where we left off in tokenize.c *******************/
111601
111602
111603/*
111604** If X is a character that can be used in an identifier then
111605** IdChar(X) will be true.  Otherwise it is false.
111606**
111607** For ASCII, any character with the high-order bit set is
111608** allowed in an identifier.  For 7-bit characters,
111609** sqlite3IsIdChar[X] must be 1.
111610**
111611** For EBCDIC, the rules are more complex but have the same
111612** end result.
111613**
111614** Ticket #1066.  the SQL standard does not allow '$' in the
111615** middle of identfiers.  But many SQL implementations do.
111616** SQLite will allow '$' in identifiers for compatibility.
111617** But the feature is undocumented.
111618*/
111619#ifdef SQLITE_ASCII
111620#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
111621#endif
111622#ifdef SQLITE_EBCDIC
111623SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
111624/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
111625    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
111626    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
111627    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
111628    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
111629    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
111630    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
111631    1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
111632    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
111633    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
111634    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
111635    0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
111636    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
111637};
111638#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
111639#endif
111640
111641
111642/*
111643** Return the length of the token that begins at z[0].
111644** Store the token type in *tokenType before returning.
111645*/
111646SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
111647  int i, c;
111648  switch( *z ){
111649    case ' ': case '\t': case '\n': case '\f': case '\r': {
111650      testcase( z[0]==' ' );
111651      testcase( z[0]=='\t' );
111652      testcase( z[0]=='\n' );
111653      testcase( z[0]=='\f' );
111654      testcase( z[0]=='\r' );
111655      for(i=1; sqlite3Isspace(z[i]); i++){}
111656      *tokenType = TK_SPACE;
111657      return i;
111658    }
111659    case '-': {
111660      if( z[1]=='-' ){
111661        /* IMP: R-50417-27976 -- syntax diagram for comments */
111662        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
111663        *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111664        return i;
111665      }
111666      *tokenType = TK_MINUS;
111667      return 1;
111668    }
111669    case '(': {
111670      *tokenType = TK_LP;
111671      return 1;
111672    }
111673    case ')': {
111674      *tokenType = TK_RP;
111675      return 1;
111676    }
111677    case ';': {
111678      *tokenType = TK_SEMI;
111679      return 1;
111680    }
111681    case '+': {
111682      *tokenType = TK_PLUS;
111683      return 1;
111684    }
111685    case '*': {
111686      *tokenType = TK_STAR;
111687      return 1;
111688    }
111689    case '/': {
111690      if( z[1]!='*' || z[2]==0 ){
111691        *tokenType = TK_SLASH;
111692        return 1;
111693      }
111694      /* IMP: R-50417-27976 -- syntax diagram for comments */
111695      for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
111696      if( c ) i++;
111697      *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
111698      return i;
111699    }
111700    case '%': {
111701      *tokenType = TK_REM;
111702      return 1;
111703    }
111704    case '=': {
111705      *tokenType = TK_EQ;
111706      return 1 + (z[1]=='=');
111707    }
111708    case '<': {
111709      if( (c=z[1])=='=' ){
111710        *tokenType = TK_LE;
111711        return 2;
111712      }else if( c=='>' ){
111713        *tokenType = TK_NE;
111714        return 2;
111715      }else if( c=='<' ){
111716        *tokenType = TK_LSHIFT;
111717        return 2;
111718      }else{
111719        *tokenType = TK_LT;
111720        return 1;
111721      }
111722    }
111723    case '>': {
111724      if( (c=z[1])=='=' ){
111725        *tokenType = TK_GE;
111726        return 2;
111727      }else if( c=='>' ){
111728        *tokenType = TK_RSHIFT;
111729        return 2;
111730      }else{
111731        *tokenType = TK_GT;
111732        return 1;
111733      }
111734    }
111735    case '!': {
111736      if( z[1]!='=' ){
111737        *tokenType = TK_ILLEGAL;
111738        return 2;
111739      }else{
111740        *tokenType = TK_NE;
111741        return 2;
111742      }
111743    }
111744    case '|': {
111745      if( z[1]!='|' ){
111746        *tokenType = TK_BITOR;
111747        return 1;
111748      }else{
111749        *tokenType = TK_CONCAT;
111750        return 2;
111751      }
111752    }
111753    case ',': {
111754      *tokenType = TK_COMMA;
111755      return 1;
111756    }
111757    case '&': {
111758      *tokenType = TK_BITAND;
111759      return 1;
111760    }
111761    case '~': {
111762      *tokenType = TK_BITNOT;
111763      return 1;
111764    }
111765    case '`':
111766    case '\'':
111767    case '"': {
111768      int delim = z[0];
111769      testcase( delim=='`' );
111770      testcase( delim=='\'' );
111771      testcase( delim=='"' );
111772      for(i=1; (c=z[i])!=0; i++){
111773        if( c==delim ){
111774          if( z[i+1]==delim ){
111775            i++;
111776          }else{
111777            break;
111778          }
111779        }
111780      }
111781      if( c=='\'' ){
111782        *tokenType = TK_STRING;
111783        return i+1;
111784      }else if( c!=0 ){
111785        *tokenType = TK_ID;
111786        return i+1;
111787      }else{
111788        *tokenType = TK_ILLEGAL;
111789        return i;
111790      }
111791    }
111792    case '.': {
111793#ifndef SQLITE_OMIT_FLOATING_POINT
111794      if( !sqlite3Isdigit(z[1]) )
111795#endif
111796      {
111797        *tokenType = TK_DOT;
111798        return 1;
111799      }
111800      /* If the next character is a digit, this is a floating point
111801      ** number that begins with ".".  Fall thru into the next case */
111802    }
111803    case '0': case '1': case '2': case '3': case '4':
111804    case '5': case '6': case '7': case '8': case '9': {
111805      testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
111806      testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
111807      testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
111808      testcase( z[0]=='9' );
111809      *tokenType = TK_INTEGER;
111810      for(i=0; sqlite3Isdigit(z[i]); i++){}
111811#ifndef SQLITE_OMIT_FLOATING_POINT
111812      if( z[i]=='.' ){
111813        i++;
111814        while( sqlite3Isdigit(z[i]) ){ i++; }
111815        *tokenType = TK_FLOAT;
111816      }
111817      if( (z[i]=='e' || z[i]=='E') &&
111818           ( sqlite3Isdigit(z[i+1])
111819            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
111820           )
111821      ){
111822        i += 2;
111823        while( sqlite3Isdigit(z[i]) ){ i++; }
111824        *tokenType = TK_FLOAT;
111825      }
111826#endif
111827      while( IdChar(z[i]) ){
111828        *tokenType = TK_ILLEGAL;
111829        i++;
111830      }
111831      return i;
111832    }
111833    case '[': {
111834      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
111835      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
111836      return i;
111837    }
111838    case '?': {
111839      *tokenType = TK_VARIABLE;
111840      for(i=1; sqlite3Isdigit(z[i]); i++){}
111841      return i;
111842    }
111843    case '#': {
111844      for(i=1; sqlite3Isdigit(z[i]); i++){}
111845      if( i>1 ){
111846        /* Parameters of the form #NNN (where NNN is a number) are used
111847        ** internally by sqlite3NestedParse.  */
111848        *tokenType = TK_REGISTER;
111849        return i;
111850      }
111851      /* Fall through into the next case if the '#' is not followed by
111852      ** a digit. Try to match #AAAA where AAAA is a parameter name. */
111853    }
111854#ifndef SQLITE_OMIT_TCL_VARIABLE
111855    case '$':
111856#endif
111857    case '@':  /* For compatibility with MS SQL Server */
111858    case ':': {
111859      int n = 0;
111860      testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
111861      *tokenType = TK_VARIABLE;
111862      for(i=1; (c=z[i])!=0; i++){
111863        if( IdChar(c) ){
111864          n++;
111865#ifndef SQLITE_OMIT_TCL_VARIABLE
111866        }else if( c=='(' && n>0 ){
111867          do{
111868            i++;
111869          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
111870          if( c==')' ){
111871            i++;
111872          }else{
111873            *tokenType = TK_ILLEGAL;
111874          }
111875          break;
111876        }else if( c==':' && z[i+1]==':' ){
111877          i++;
111878#endif
111879        }else{
111880          break;
111881        }
111882      }
111883      if( n==0 ) *tokenType = TK_ILLEGAL;
111884      return i;
111885    }
111886#ifndef SQLITE_OMIT_BLOB_LITERAL
111887    case 'x': case 'X': {
111888      testcase( z[0]=='x' ); testcase( z[0]=='X' );
111889      if( z[1]=='\'' ){
111890        *tokenType = TK_BLOB;
111891        for(i=2; sqlite3Isxdigit(z[i]); i++){}
111892        if( z[i]!='\'' || i%2 ){
111893          *tokenType = TK_ILLEGAL;
111894          while( z[i] && z[i]!='\'' ){ i++; }
111895        }
111896        if( z[i] ) i++;
111897        return i;
111898      }
111899      /* Otherwise fall through to the next case */
111900    }
111901#endif
111902    default: {
111903      if( !IdChar(*z) ){
111904        break;
111905      }
111906      for(i=1; IdChar(z[i]); i++){}
111907      *tokenType = keywordCode((char*)z, i);
111908      return i;
111909    }
111910  }
111911  *tokenType = TK_ILLEGAL;
111912  return 1;
111913}
111914
111915/*
111916** Run the parser on the given SQL string.  The parser structure is
111917** passed in.  An SQLITE_ status code is returned.  If an error occurs
111918** then an and attempt is made to write an error message into
111919** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
111920** error message.
111921*/
111922SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
111923  int nErr = 0;                   /* Number of errors encountered */
111924  int i;                          /* Loop counter */
111925  void *pEngine;                  /* The LEMON-generated LALR(1) parser */
111926  int tokenType;                  /* type of the next token */
111927  int lastTokenParsed = -1;       /* type of the previous token */
111928  u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
111929  sqlite3 *db = pParse->db;       /* The database connection */
111930  int mxSqlLen;                   /* Max length of an SQL string */
111931
111932
111933  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
111934  if( db->activeVdbeCnt==0 ){
111935    db->u1.isInterrupted = 0;
111936  }
111937  pParse->rc = SQLITE_OK;
111938  pParse->zTail = zSql;
111939  i = 0;
111940  assert( pzErrMsg!=0 );
111941  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
111942  if( pEngine==0 ){
111943    db->mallocFailed = 1;
111944    return SQLITE_NOMEM;
111945  }
111946  assert( pParse->pNewTable==0 );
111947  assert( pParse->pNewTrigger==0 );
111948  assert( pParse->nVar==0 );
111949  assert( pParse->nzVar==0 );
111950  assert( pParse->azVar==0 );
111951  enableLookaside = db->lookaside.bEnabled;
111952  if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
111953  while( !db->mallocFailed && zSql[i]!=0 ){
111954    assert( i>=0 );
111955    pParse->sLastToken.z = &zSql[i];
111956    pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
111957    i += pParse->sLastToken.n;
111958    if( i>mxSqlLen ){
111959      pParse->rc = SQLITE_TOOBIG;
111960      break;
111961    }
111962    switch( tokenType ){
111963      case TK_SPACE: {
111964        if( db->u1.isInterrupted ){
111965          sqlite3ErrorMsg(pParse, "interrupt");
111966          pParse->rc = SQLITE_INTERRUPT;
111967          goto abort_parse;
111968        }
111969        break;
111970      }
111971      case TK_ILLEGAL: {
111972        sqlite3DbFree(db, *pzErrMsg);
111973        *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
111974                        &pParse->sLastToken);
111975        nErr++;
111976        goto abort_parse;
111977      }
111978      case TK_SEMI: {
111979        pParse->zTail = &zSql[i];
111980        /* Fall thru into the default case */
111981      }
111982      default: {
111983        sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
111984        lastTokenParsed = tokenType;
111985        if( pParse->rc!=SQLITE_OK ){
111986          goto abort_parse;
111987        }
111988        break;
111989      }
111990    }
111991  }
111992abort_parse:
111993  if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
111994    if( lastTokenParsed!=TK_SEMI ){
111995      sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
111996      pParse->zTail = &zSql[i];
111997    }
111998    sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
111999  }
112000#ifdef YYTRACKMAXSTACKDEPTH
112001  sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
112002      sqlite3ParserStackPeak(pEngine)
112003  );
112004#endif /* YYDEBUG */
112005  sqlite3ParserFree(pEngine, sqlite3_free);
112006  db->lookaside.bEnabled = enableLookaside;
112007  if( db->mallocFailed ){
112008    pParse->rc = SQLITE_NOMEM;
112009  }
112010  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
112011    sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
112012  }
112013  assert( pzErrMsg!=0 );
112014  if( pParse->zErrMsg ){
112015    *pzErrMsg = pParse->zErrMsg;
112016    sqlite3_log(pParse->rc, "%s", *pzErrMsg);
112017    pParse->zErrMsg = 0;
112018    nErr++;
112019  }
112020  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
112021    sqlite3VdbeDelete(pParse->pVdbe);
112022    pParse->pVdbe = 0;
112023  }
112024#ifndef SQLITE_OMIT_SHARED_CACHE
112025  if( pParse->nested==0 ){
112026    sqlite3DbFree(db, pParse->aTableLock);
112027    pParse->aTableLock = 0;
112028    pParse->nTableLock = 0;
112029  }
112030#endif
112031#ifndef SQLITE_OMIT_VIRTUALTABLE
112032  sqlite3_free(pParse->apVtabLock);
112033#endif
112034
112035  if( !IN_DECLARE_VTAB ){
112036    /* If the pParse->declareVtab flag is set, do not delete any table
112037    ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
112038    ** will take responsibility for freeing the Table structure.
112039    */
112040    sqlite3DeleteTable(db, pParse->pNewTable);
112041  }
112042
112043  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
112044  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
112045  sqlite3DbFree(db, pParse->azVar);
112046  sqlite3DbFree(db, pParse->aAlias);
112047  while( pParse->pAinc ){
112048    AutoincInfo *p = pParse->pAinc;
112049    pParse->pAinc = p->pNext;
112050    sqlite3DbFree(db, p);
112051  }
112052  while( pParse->pZombieTab ){
112053    Table *p = pParse->pZombieTab;
112054    pParse->pZombieTab = p->pNextZombie;
112055    sqlite3DeleteTable(db, p);
112056  }
112057  if( nErr>0 && pParse->rc==SQLITE_OK ){
112058    pParse->rc = SQLITE_ERROR;
112059  }
112060  return nErr;
112061}
112062
112063/************** End of tokenize.c ********************************************/
112064/************** Begin file complete.c ****************************************/
112065/*
112066** 2001 September 15
112067**
112068** The author disclaims copyright to this source code.  In place of
112069** a legal notice, here is a blessing:
112070**
112071**    May you do good and not evil.
112072**    May you find forgiveness for yourself and forgive others.
112073**    May you share freely, never taking more than you give.
112074**
112075*************************************************************************
112076** An tokenizer for SQL
112077**
112078** This file contains C code that implements the sqlite3_complete() API.
112079** This code used to be part of the tokenizer.c source file.  But by
112080** separating it out, the code will be automatically omitted from
112081** static links that do not use it.
112082*/
112083#ifndef SQLITE_OMIT_COMPLETE
112084
112085/*
112086** This is defined in tokenize.c.  We just have to import the definition.
112087*/
112088#ifndef SQLITE_AMALGAMATION
112089#ifdef SQLITE_ASCII
112090#define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
112091#endif
112092#ifdef SQLITE_EBCDIC
112093SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
112094#define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
112095#endif
112096#endif /* SQLITE_AMALGAMATION */
112097
112098
112099/*
112100** Token types used by the sqlite3_complete() routine.  See the header
112101** comments on that procedure for additional information.
112102*/
112103#define tkSEMI    0
112104#define tkWS      1
112105#define tkOTHER   2
112106#ifndef SQLITE_OMIT_TRIGGER
112107#define tkEXPLAIN 3
112108#define tkCREATE  4
112109#define tkTEMP    5
112110#define tkTRIGGER 6
112111#define tkEND     7
112112#endif
112113
112114/*
112115** Return TRUE if the given SQL string ends in a semicolon.
112116**
112117** Special handling is require for CREATE TRIGGER statements.
112118** Whenever the CREATE TRIGGER keywords are seen, the statement
112119** must end with ";END;".
112120**
112121** This implementation uses a state machine with 8 states:
112122**
112123**   (0) INVALID   We have not yet seen a non-whitespace character.
112124**
112125**   (1) START     At the beginning or end of an SQL statement.  This routine
112126**                 returns 1 if it ends in the START state and 0 if it ends
112127**                 in any other state.
112128**
112129**   (2) NORMAL    We are in the middle of statement which ends with a single
112130**                 semicolon.
112131**
112132**   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of
112133**                 a statement.
112134**
112135**   (4) CREATE    The keyword CREATE has been seen at the beginning of a
112136**                 statement, possibly preceeded by EXPLAIN and/or followed by
112137**                 TEMP or TEMPORARY
112138**
112139**   (5) TRIGGER   We are in the middle of a trigger definition that must be
112140**                 ended by a semicolon, the keyword END, and another semicolon.
112141**
112142**   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
112143**                 the end of a trigger definition.
112144**
112145**   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
112146**                 of a trigger difinition.
112147**
112148** Transitions between states above are determined by tokens extracted
112149** from the input.  The following tokens are significant:
112150**
112151**   (0) tkSEMI      A semicolon.
112152**   (1) tkWS        Whitespace.
112153**   (2) tkOTHER     Any other SQL token.
112154**   (3) tkEXPLAIN   The "explain" keyword.
112155**   (4) tkCREATE    The "create" keyword.
112156**   (5) tkTEMP      The "temp" or "temporary" keyword.
112157**   (6) tkTRIGGER   The "trigger" keyword.
112158**   (7) tkEND       The "end" keyword.
112159**
112160** Whitespace never causes a state transition and is always ignored.
112161** This means that a SQL string of all whitespace is invalid.
112162**
112163** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
112164** to recognize the end of a trigger can be omitted.  All we have to do
112165** is look for a semicolon that is not part of an string or comment.
112166*/
112167SQLITE_API int sqlite3_complete(const char *zSql){
112168  u8 state = 0;   /* Current state, using numbers defined in header comment */
112169  u8 token;       /* Value of the next token */
112170
112171#ifndef SQLITE_OMIT_TRIGGER
112172  /* A complex statement machine used to detect the end of a CREATE TRIGGER
112173  ** statement.  This is the normal case.
112174  */
112175  static const u8 trans[8][8] = {
112176                     /* Token:                                                */
112177     /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
112178     /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
112179     /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
112180     /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
112181     /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
112182     /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
112183     /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
112184     /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
112185     /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
112186  };
112187#else
112188  /* If triggers are not supported by this compile then the statement machine
112189  ** used to detect the end of a statement is much simplier
112190  */
112191  static const u8 trans[3][3] = {
112192                     /* Token:           */
112193     /* State:       **  SEMI  WS  OTHER */
112194     /* 0 INVALID: */ {    1,  0,     2, },
112195     /* 1   START: */ {    1,  1,     2, },
112196     /* 2  NORMAL: */ {    1,  2,     2, },
112197  };
112198#endif /* SQLITE_OMIT_TRIGGER */
112199
112200  while( *zSql ){
112201    switch( *zSql ){
112202      case ';': {  /* A semicolon */
112203        token = tkSEMI;
112204        break;
112205      }
112206      case ' ':
112207      case '\r':
112208      case '\t':
112209      case '\n':
112210      case '\f': {  /* White space is ignored */
112211        token = tkWS;
112212        break;
112213      }
112214      case '/': {   /* C-style comments */
112215        if( zSql[1]!='*' ){
112216          token = tkOTHER;
112217          break;
112218        }
112219        zSql += 2;
112220        while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
112221        if( zSql[0]==0 ) return 0;
112222        zSql++;
112223        token = tkWS;
112224        break;
112225      }
112226      case '-': {   /* SQL-style comments from "--" to end of line */
112227        if( zSql[1]!='-' ){
112228          token = tkOTHER;
112229          break;
112230        }
112231        while( *zSql && *zSql!='\n' ){ zSql++; }
112232        if( *zSql==0 ) return state==1;
112233        token = tkWS;
112234        break;
112235      }
112236      case '[': {   /* Microsoft-style identifiers in [...] */
112237        zSql++;
112238        while( *zSql && *zSql!=']' ){ zSql++; }
112239        if( *zSql==0 ) return 0;
112240        token = tkOTHER;
112241        break;
112242      }
112243      case '`':     /* Grave-accent quoted symbols used by MySQL */
112244      case '"':     /* single- and double-quoted strings */
112245      case '\'': {
112246        int c = *zSql;
112247        zSql++;
112248        while( *zSql && *zSql!=c ){ zSql++; }
112249        if( *zSql==0 ) return 0;
112250        token = tkOTHER;
112251        break;
112252      }
112253      default: {
112254#ifdef SQLITE_EBCDIC
112255        unsigned char c;
112256#endif
112257        if( IdChar((u8)*zSql) ){
112258          /* Keywords and unquoted identifiers */
112259          int nId;
112260          for(nId=1; IdChar(zSql[nId]); nId++){}
112261#ifdef SQLITE_OMIT_TRIGGER
112262          token = tkOTHER;
112263#else
112264          switch( *zSql ){
112265            case 'c': case 'C': {
112266              if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
112267                token = tkCREATE;
112268              }else{
112269                token = tkOTHER;
112270              }
112271              break;
112272            }
112273            case 't': case 'T': {
112274              if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
112275                token = tkTRIGGER;
112276              }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
112277                token = tkTEMP;
112278              }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
112279                token = tkTEMP;
112280              }else{
112281                token = tkOTHER;
112282              }
112283              break;
112284            }
112285            case 'e':  case 'E': {
112286              if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
112287                token = tkEND;
112288              }else
112289#ifndef SQLITE_OMIT_EXPLAIN
112290              if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
112291                token = tkEXPLAIN;
112292              }else
112293#endif
112294              {
112295                token = tkOTHER;
112296              }
112297              break;
112298            }
112299            default: {
112300              token = tkOTHER;
112301              break;
112302            }
112303          }
112304#endif /* SQLITE_OMIT_TRIGGER */
112305          zSql += nId-1;
112306        }else{
112307          /* Operators and special symbols */
112308          token = tkOTHER;
112309        }
112310        break;
112311      }
112312    }
112313    state = trans[state][token];
112314    zSql++;
112315  }
112316  return state==1;
112317}
112318
112319#ifndef SQLITE_OMIT_UTF16
112320/*
112321** This routine is the same as the sqlite3_complete() routine described
112322** above, except that the parameter is required to be UTF-16 encoded, not
112323** UTF-8.
112324*/
112325SQLITE_API int sqlite3_complete16(const void *zSql){
112326  sqlite3_value *pVal;
112327  char const *zSql8;
112328  int rc = SQLITE_NOMEM;
112329
112330#ifndef SQLITE_OMIT_AUTOINIT
112331  rc = sqlite3_initialize();
112332  if( rc ) return rc;
112333#endif
112334  pVal = sqlite3ValueNew(0);
112335  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
112336  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
112337  if( zSql8 ){
112338    rc = sqlite3_complete(zSql8);
112339  }else{
112340    rc = SQLITE_NOMEM;
112341  }
112342  sqlite3ValueFree(pVal);
112343  return sqlite3ApiExit(0, rc);
112344}
112345#endif /* SQLITE_OMIT_UTF16 */
112346#endif /* SQLITE_OMIT_COMPLETE */
112347
112348/************** End of complete.c ********************************************/
112349/************** Begin file main.c ********************************************/
112350/*
112351** 2001 September 15
112352**
112353** The author disclaims copyright to this source code.  In place of
112354** a legal notice, here is a blessing:
112355**
112356**    May you do good and not evil.
112357**    May you find forgiveness for yourself and forgive others.
112358**    May you share freely, never taking more than you give.
112359**
112360*************************************************************************
112361** Main file for the SQLite library.  The routines in this file
112362** implement the programmer interface to the library.  Routines in
112363** other files are for internal use by SQLite and should not be
112364** accessed by users of the library.
112365*/
112366
112367#ifdef SQLITE_ENABLE_FTS3
112368/************** Include fts3.h in the middle of main.c ***********************/
112369/************** Begin file fts3.h ********************************************/
112370/*
112371** 2006 Oct 10
112372**
112373** The author disclaims copyright to this source code.  In place of
112374** a legal notice, here is a blessing:
112375**
112376**    May you do good and not evil.
112377**    May you find forgiveness for yourself and forgive others.
112378**    May you share freely, never taking more than you give.
112379**
112380******************************************************************************
112381**
112382** This header file is used by programs that want to link against the
112383** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
112384*/
112385
112386#if 0
112387extern "C" {
112388#endif  /* __cplusplus */
112389
112390SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
112391
112392#if 0
112393}  /* extern "C" */
112394#endif  /* __cplusplus */
112395
112396/************** End of fts3.h ************************************************/
112397/************** Continuing where we left off in main.c ***********************/
112398#endif
112399#ifdef SQLITE_ENABLE_RTREE
112400/************** Include rtree.h in the middle of main.c **********************/
112401/************** Begin file rtree.h *******************************************/
112402/*
112403** 2008 May 26
112404**
112405** The author disclaims copyright to this source code.  In place of
112406** a legal notice, here is a blessing:
112407**
112408**    May you do good and not evil.
112409**    May you find forgiveness for yourself and forgive others.
112410**    May you share freely, never taking more than you give.
112411**
112412******************************************************************************
112413**
112414** This header file is used by programs that want to link against the
112415** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
112416*/
112417
112418#if 0
112419extern "C" {
112420#endif  /* __cplusplus */
112421
112422SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
112423
112424#if 0
112425}  /* extern "C" */
112426#endif  /* __cplusplus */
112427
112428/************** End of rtree.h ***********************************************/
112429/************** Continuing where we left off in main.c ***********************/
112430#endif
112431#ifdef SQLITE_ENABLE_ICU
112432/************** Include sqliteicu.h in the middle of main.c ******************/
112433/************** Begin file sqliteicu.h ***************************************/
112434/*
112435** 2008 May 26
112436**
112437** The author disclaims copyright to this source code.  In place of
112438** a legal notice, here is a blessing:
112439**
112440**    May you do good and not evil.
112441**    May you find forgiveness for yourself and forgive others.
112442**    May you share freely, never taking more than you give.
112443**
112444******************************************************************************
112445**
112446** This header file is used by programs that want to link against the
112447** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
112448*/
112449
112450#if 0
112451extern "C" {
112452#endif  /* __cplusplus */
112453
112454SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
112455
112456#if 0
112457}  /* extern "C" */
112458#endif  /* __cplusplus */
112459
112460
112461/************** End of sqliteicu.h *******************************************/
112462/************** Continuing where we left off in main.c ***********************/
112463#endif
112464
112465#ifndef SQLITE_AMALGAMATION
112466/* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
112467** contains the text of SQLITE_VERSION macro.
112468*/
112469SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
112470#endif
112471
112472/* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
112473** a pointer to the to the sqlite3_version[] string constant.
112474*/
112475SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
112476
112477/* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
112478** pointer to a string constant whose value is the same as the
112479** SQLITE_SOURCE_ID C preprocessor macro.
112480*/
112481SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
112482
112483/* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
112484** returns an integer equal to SQLITE_VERSION_NUMBER.
112485*/
112486SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
112487
112488/* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
112489** zero if and only if SQLite was compiled with mutexing code omitted due to
112490** the SQLITE_THREADSAFE compile-time option being set to 0.
112491*/
112492SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
112493
112494#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
112495/*
112496** If the following function pointer is not NULL and if
112497** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
112498** I/O active are written using this function.  These messages
112499** are intended for debugging activity only.
112500*/
112501SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
112502#endif
112503
112504/*
112505** If the following global variable points to a string which is the
112506** name of a directory, then that directory will be used to store
112507** temporary files.
112508**
112509** See also the "PRAGMA temp_store_directory" SQL command.
112510*/
112511SQLITE_API char *sqlite3_temp_directory = 0;
112512
112513/*
112514** Initialize SQLite.
112515**
112516** This routine must be called to initialize the memory allocation,
112517** VFS, and mutex subsystems prior to doing any serious work with
112518** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
112519** this routine will be called automatically by key routines such as
112520** sqlite3_open().
112521**
112522** This routine is a no-op except on its very first call for the process,
112523** or for the first call after a call to sqlite3_shutdown.
112524**
112525** The first thread to call this routine runs the initialization to
112526** completion.  If subsequent threads call this routine before the first
112527** thread has finished the initialization process, then the subsequent
112528** threads must block until the first thread finishes with the initialization.
112529**
112530** The first thread might call this routine recursively.  Recursive
112531** calls to this routine should not block, of course.  Otherwise the
112532** initialization process would never complete.
112533**
112534** Let X be the first thread to enter this routine.  Let Y be some other
112535** thread.  Then while the initial invocation of this routine by X is
112536** incomplete, it is required that:
112537**
112538**    *  Calls to this routine from Y must block until the outer-most
112539**       call by X completes.
112540**
112541**    *  Recursive calls to this routine from thread X return immediately
112542**       without blocking.
112543*/
112544SQLITE_API int sqlite3_initialize(void){
112545  MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
112546  int rc;                                      /* Result code */
112547
112548#ifdef SQLITE_OMIT_WSD
112549  rc = sqlite3_wsd_init(4096, 24);
112550  if( rc!=SQLITE_OK ){
112551    return rc;
112552  }
112553#endif
112554
112555  /* If SQLite is already completely initialized, then this call
112556  ** to sqlite3_initialize() should be a no-op.  But the initialization
112557  ** must be complete.  So isInit must not be set until the very end
112558  ** of this routine.
112559  */
112560  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
112561
112562  /* Make sure the mutex subsystem is initialized.  If unable to
112563  ** initialize the mutex subsystem, return early with the error.
112564  ** If the system is so sick that we are unable to allocate a mutex,
112565  ** there is not much SQLite is going to be able to do.
112566  **
112567  ** The mutex subsystem must take care of serializing its own
112568  ** initialization.
112569  */
112570  rc = sqlite3MutexInit();
112571  if( rc ) return rc;
112572
112573  /* Initialize the malloc() system and the recursive pInitMutex mutex.
112574  ** This operation is protected by the STATIC_MASTER mutex.  Note that
112575  ** MutexAlloc() is called for a static mutex prior to initializing the
112576  ** malloc subsystem - this implies that the allocation of a static
112577  ** mutex must not require support from the malloc subsystem.
112578  */
112579  MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
112580  sqlite3_mutex_enter(pMaster);
112581  sqlite3GlobalConfig.isMutexInit = 1;
112582  if( !sqlite3GlobalConfig.isMallocInit ){
112583    rc = sqlite3MallocInit();
112584  }
112585  if( rc==SQLITE_OK ){
112586    sqlite3GlobalConfig.isMallocInit = 1;
112587    if( !sqlite3GlobalConfig.pInitMutex ){
112588      sqlite3GlobalConfig.pInitMutex =
112589           sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
112590      if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
112591        rc = SQLITE_NOMEM;
112592      }
112593    }
112594  }
112595  if( rc==SQLITE_OK ){
112596    sqlite3GlobalConfig.nRefInitMutex++;
112597  }
112598  sqlite3_mutex_leave(pMaster);
112599
112600  /* If rc is not SQLITE_OK at this point, then either the malloc
112601  ** subsystem could not be initialized or the system failed to allocate
112602  ** the pInitMutex mutex. Return an error in either case.  */
112603  if( rc!=SQLITE_OK ){
112604    return rc;
112605  }
112606
112607  /* Do the rest of the initialization under the recursive mutex so
112608  ** that we will be able to handle recursive calls into
112609  ** sqlite3_initialize().  The recursive calls normally come through
112610  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
112611  ** recursive calls might also be possible.
112612  **
112613  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
112614  ** to the xInit method, so the xInit method need not be threadsafe.
112615  **
112616  ** The following mutex is what serializes access to the appdef pcache xInit
112617  ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
112618  ** call to sqlite3PcacheInitialize().
112619  */
112620  sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
112621  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
112622    FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
112623    sqlite3GlobalConfig.inProgress = 1;
112624    memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
112625    sqlite3RegisterGlobalFunctions();
112626    if( sqlite3GlobalConfig.isPCacheInit==0 ){
112627      rc = sqlite3PcacheInitialize();
112628    }
112629    if( rc==SQLITE_OK ){
112630      sqlite3GlobalConfig.isPCacheInit = 1;
112631      rc = sqlite3OsInit();
112632    }
112633    if( rc==SQLITE_OK ){
112634      sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
112635          sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
112636      sqlite3GlobalConfig.isInit = 1;
112637    }
112638    sqlite3GlobalConfig.inProgress = 0;
112639  }
112640  sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
112641
112642  /* Go back under the static mutex and clean up the recursive
112643  ** mutex to prevent a resource leak.
112644  */
112645  sqlite3_mutex_enter(pMaster);
112646  sqlite3GlobalConfig.nRefInitMutex--;
112647  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
112648    assert( sqlite3GlobalConfig.nRefInitMutex==0 );
112649    sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
112650    sqlite3GlobalConfig.pInitMutex = 0;
112651  }
112652  sqlite3_mutex_leave(pMaster);
112653
112654  /* The following is just a sanity check to make sure SQLite has
112655  ** been compiled correctly.  It is important to run this code, but
112656  ** we don't want to run it too often and soak up CPU cycles for no
112657  ** reason.  So we run it once during initialization.
112658  */
112659#ifndef NDEBUG
112660#ifndef SQLITE_OMIT_FLOATING_POINT
112661  /* This section of code's only "output" is via assert() statements. */
112662  if ( rc==SQLITE_OK ){
112663    u64 x = (((u64)1)<<63)-1;
112664    double y;
112665    assert(sizeof(x)==8);
112666    assert(sizeof(x)==sizeof(y));
112667    memcpy(&y, &x, 8);
112668    assert( sqlite3IsNaN(y) );
112669  }
112670#endif
112671#endif
112672
112673  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
112674  ** compile-time option.
112675  */
112676#ifdef SQLITE_EXTRA_INIT
112677  if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
112678    int SQLITE_EXTRA_INIT(const char*);
112679    rc = SQLITE_EXTRA_INIT(0);
112680  }
112681#endif
112682
112683  return rc;
112684}
112685
112686/*
112687** Undo the effects of sqlite3_initialize().  Must not be called while
112688** there are outstanding database connections or memory allocations or
112689** while any part of SQLite is otherwise in use in any thread.  This
112690** routine is not threadsafe.  But it is safe to invoke this routine
112691** on when SQLite is already shut down.  If SQLite is already shut down
112692** when this routine is invoked, then this routine is a harmless no-op.
112693*/
112694SQLITE_API int sqlite3_shutdown(void){
112695  if( sqlite3GlobalConfig.isInit ){
112696#ifdef SQLITE_EXTRA_SHUTDOWN
112697    void SQLITE_EXTRA_SHUTDOWN(void);
112698    SQLITE_EXTRA_SHUTDOWN();
112699#endif
112700    sqlite3_os_end();
112701    sqlite3_reset_auto_extension();
112702    sqlite3GlobalConfig.isInit = 0;
112703  }
112704  if( sqlite3GlobalConfig.isPCacheInit ){
112705    sqlite3PcacheShutdown();
112706    sqlite3GlobalConfig.isPCacheInit = 0;
112707  }
112708  if( sqlite3GlobalConfig.isMallocInit ){
112709    sqlite3MallocEnd();
112710    sqlite3GlobalConfig.isMallocInit = 0;
112711  }
112712  if( sqlite3GlobalConfig.isMutexInit ){
112713    sqlite3MutexEnd();
112714    sqlite3GlobalConfig.isMutexInit = 0;
112715  }
112716
112717  return SQLITE_OK;
112718}
112719
112720/*
112721** This API allows applications to modify the global configuration of
112722** the SQLite library at run-time.
112723**
112724** This routine should only be called when there are no outstanding
112725** database connections or memory allocations.  This routine is not
112726** threadsafe.  Failure to heed these warnings can lead to unpredictable
112727** behavior.
112728*/
112729SQLITE_API int sqlite3_config(int op, ...){
112730  va_list ap;
112731  int rc = SQLITE_OK;
112732
112733  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
112734  ** the SQLite library is in use. */
112735  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
112736
112737  va_start(ap, op);
112738  switch( op ){
112739
112740    /* Mutex configuration options are only available in a threadsafe
112741    ** compile.
112742    */
112743#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
112744    case SQLITE_CONFIG_SINGLETHREAD: {
112745      /* Disable all mutexing */
112746      sqlite3GlobalConfig.bCoreMutex = 0;
112747      sqlite3GlobalConfig.bFullMutex = 0;
112748      break;
112749    }
112750    case SQLITE_CONFIG_MULTITHREAD: {
112751      /* Disable mutexing of database connections */
112752      /* Enable mutexing of core data structures */
112753      sqlite3GlobalConfig.bCoreMutex = 1;
112754      sqlite3GlobalConfig.bFullMutex = 0;
112755      break;
112756    }
112757    case SQLITE_CONFIG_SERIALIZED: {
112758      /* Enable all mutexing */
112759      sqlite3GlobalConfig.bCoreMutex = 1;
112760      sqlite3GlobalConfig.bFullMutex = 1;
112761      break;
112762    }
112763    case SQLITE_CONFIG_MUTEX: {
112764      /* Specify an alternative mutex implementation */
112765      sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
112766      break;
112767    }
112768    case SQLITE_CONFIG_GETMUTEX: {
112769      /* Retrieve the current mutex implementation */
112770      *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
112771      break;
112772    }
112773#endif
112774
112775
112776    case SQLITE_CONFIG_MALLOC: {
112777      /* Specify an alternative malloc implementation */
112778      sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
112779      break;
112780    }
112781    case SQLITE_CONFIG_GETMALLOC: {
112782      /* Retrieve the current malloc() implementation */
112783      if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
112784      *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
112785      break;
112786    }
112787    case SQLITE_CONFIG_MEMSTATUS: {
112788      /* Enable or disable the malloc status collection */
112789      sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
112790      break;
112791    }
112792    case SQLITE_CONFIG_SCRATCH: {
112793      /* Designate a buffer for scratch memory space */
112794      sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
112795      sqlite3GlobalConfig.szScratch = va_arg(ap, int);
112796      sqlite3GlobalConfig.nScratch = va_arg(ap, int);
112797      break;
112798    }
112799    case SQLITE_CONFIG_PAGECACHE: {
112800      /* Designate a buffer for page cache memory space */
112801      sqlite3GlobalConfig.pPage = va_arg(ap, void*);
112802      sqlite3GlobalConfig.szPage = va_arg(ap, int);
112803      sqlite3GlobalConfig.nPage = va_arg(ap, int);
112804      break;
112805    }
112806
112807    case SQLITE_CONFIG_PCACHE: {
112808      /* no-op */
112809      break;
112810    }
112811    case SQLITE_CONFIG_GETPCACHE: {
112812      /* now an error */
112813      rc = SQLITE_ERROR;
112814      break;
112815    }
112816
112817    case SQLITE_CONFIG_PCACHE2: {
112818      /* Specify an alternative page cache implementation */
112819      sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
112820      break;
112821    }
112822    case SQLITE_CONFIG_GETPCACHE2: {
112823      if( sqlite3GlobalConfig.pcache2.xInit==0 ){
112824        sqlite3PCacheSetDefault();
112825      }
112826      *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
112827      break;
112828    }
112829
112830#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
112831    case SQLITE_CONFIG_HEAP: {
112832      /* Designate a buffer for heap memory space */
112833      sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
112834      sqlite3GlobalConfig.nHeap = va_arg(ap, int);
112835      sqlite3GlobalConfig.mnReq = va_arg(ap, int);
112836
112837      if( sqlite3GlobalConfig.mnReq<1 ){
112838        sqlite3GlobalConfig.mnReq = 1;
112839      }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
112840        /* cap min request size at 2^12 */
112841        sqlite3GlobalConfig.mnReq = (1<<12);
112842      }
112843
112844      if( sqlite3GlobalConfig.pHeap==0 ){
112845        /* If the heap pointer is NULL, then restore the malloc implementation
112846        ** back to NULL pointers too.  This will cause the malloc to go
112847        ** back to its default implementation when sqlite3_initialize() is
112848        ** run.
112849        */
112850        memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
112851      }else{
112852        /* The heap pointer is not NULL, then install one of the
112853        ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
112854        ** ENABLE_MEMSYS5 is defined, return an error.
112855        */
112856#ifdef SQLITE_ENABLE_MEMSYS3
112857        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
112858#endif
112859#ifdef SQLITE_ENABLE_MEMSYS5
112860        sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
112861#endif
112862      }
112863      break;
112864    }
112865#endif
112866
112867    case SQLITE_CONFIG_LOOKASIDE: {
112868      sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
112869      sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
112870      break;
112871    }
112872
112873    /* Record a pointer to the logger funcction and its first argument.
112874    ** The default is NULL.  Logging is disabled if the function pointer is
112875    ** NULL.
112876    */
112877    case SQLITE_CONFIG_LOG: {
112878      /* MSVC is picky about pulling func ptrs from va lists.
112879      ** http://support.microsoft.com/kb/47961
112880      ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
112881      */
112882      typedef void(*LOGFUNC_t)(void*,int,const char*);
112883      sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
112884      sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
112885      break;
112886    }
112887
112888    case SQLITE_CONFIG_URI: {
112889      sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
112890      break;
112891    }
112892
112893    default: {
112894      rc = SQLITE_ERROR;
112895      break;
112896    }
112897  }
112898  va_end(ap);
112899  return rc;
112900}
112901
112902/*
112903** Set up the lookaside buffers for a database connection.
112904** Return SQLITE_OK on success.
112905** If lookaside is already active, return SQLITE_BUSY.
112906**
112907** The sz parameter is the number of bytes in each lookaside slot.
112908** The cnt parameter is the number of slots.  If pStart is NULL the
112909** space for the lookaside memory is obtained from sqlite3_malloc().
112910** If pStart is not NULL then it is sz*cnt bytes of memory to use for
112911** the lookaside memory.
112912*/
112913static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
112914  void *pStart;
112915  if( db->lookaside.nOut ){
112916    return SQLITE_BUSY;
112917  }
112918  /* Free any existing lookaside buffer for this handle before
112919  ** allocating a new one so we don't have to have space for
112920  ** both at the same time.
112921  */
112922  if( db->lookaside.bMalloced ){
112923    sqlite3_free(db->lookaside.pStart);
112924  }
112925  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
112926  ** than a pointer to be useful.
112927  */
112928  sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
112929  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
112930  if( cnt<0 ) cnt = 0;
112931  if( sz==0 || cnt==0 ){
112932    sz = 0;
112933    pStart = 0;
112934  }else if( pBuf==0 ){
112935    sqlite3BeginBenignMalloc();
112936    pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
112937    sqlite3EndBenignMalloc();
112938    if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
112939  }else{
112940    pStart = pBuf;
112941  }
112942  db->lookaside.pStart = pStart;
112943  db->lookaside.pFree = 0;
112944  db->lookaside.sz = (u16)sz;
112945  if( pStart ){
112946    int i;
112947    LookasideSlot *p;
112948    assert( sz > (int)sizeof(LookasideSlot*) );
112949    p = (LookasideSlot*)pStart;
112950    for(i=cnt-1; i>=0; i--){
112951      p->pNext = db->lookaside.pFree;
112952      db->lookaside.pFree = p;
112953      p = (LookasideSlot*)&((u8*)p)[sz];
112954    }
112955    db->lookaside.pEnd = p;
112956    db->lookaside.bEnabled = 1;
112957    db->lookaside.bMalloced = pBuf==0 ?1:0;
112958  }else{
112959    db->lookaside.pEnd = 0;
112960    db->lookaside.bEnabled = 0;
112961    db->lookaside.bMalloced = 0;
112962  }
112963  return SQLITE_OK;
112964}
112965
112966/*
112967** Return the mutex associated with a database connection.
112968*/
112969SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
112970  return db->mutex;
112971}
112972
112973/*
112974** Free up as much memory as we can from the given database
112975** connection.
112976*/
112977SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
112978  int i;
112979  sqlite3_mutex_enter(db->mutex);
112980  sqlite3BtreeEnterAll(db);
112981  for(i=0; i<db->nDb; i++){
112982    Btree *pBt = db->aDb[i].pBt;
112983    if( pBt ){
112984      Pager *pPager = sqlite3BtreePager(pBt);
112985      sqlite3PagerShrink(pPager);
112986    }
112987  }
112988  sqlite3BtreeLeaveAll(db);
112989  sqlite3_mutex_leave(db->mutex);
112990  return SQLITE_OK;
112991}
112992
112993/*
112994** Configuration settings for an individual database connection
112995*/
112996SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
112997  va_list ap;
112998  int rc;
112999  va_start(ap, op);
113000  switch( op ){
113001    case SQLITE_DBCONFIG_LOOKASIDE: {
113002      void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
113003      int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
113004      int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
113005      rc = setupLookaside(db, pBuf, sz, cnt);
113006      break;
113007    }
113008    default: {
113009      static const struct {
113010        int op;      /* The opcode */
113011        u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
113012      } aFlagOp[] = {
113013        { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
113014        { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
113015      };
113016      unsigned int i;
113017      rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
113018      for(i=0; i<ArraySize(aFlagOp); i++){
113019        if( aFlagOp[i].op==op ){
113020          int onoff = va_arg(ap, int);
113021          int *pRes = va_arg(ap, int*);
113022          int oldFlags = db->flags;
113023          if( onoff>0 ){
113024            db->flags |= aFlagOp[i].mask;
113025          }else if( onoff==0 ){
113026            db->flags &= ~aFlagOp[i].mask;
113027          }
113028          if( oldFlags!=db->flags ){
113029            sqlite3ExpirePreparedStatements(db);
113030          }
113031          if( pRes ){
113032            *pRes = (db->flags & aFlagOp[i].mask)!=0;
113033          }
113034          rc = SQLITE_OK;
113035          break;
113036        }
113037      }
113038      break;
113039    }
113040  }
113041  va_end(ap);
113042  return rc;
113043}
113044
113045
113046/*
113047** Return true if the buffer z[0..n-1] contains all spaces.
113048*/
113049static int allSpaces(const char *z, int n){
113050  while( n>0 && z[n-1]==' ' ){ n--; }
113051  return n==0;
113052}
113053
113054/*
113055** This is the default collating function named "BINARY" which is always
113056** available.
113057**
113058** If the padFlag argument is not NULL then space padding at the end
113059** of strings is ignored.  This implements the RTRIM collation.
113060*/
113061static int binCollFunc(
113062  void *padFlag,
113063  int nKey1, const void *pKey1,
113064  int nKey2, const void *pKey2
113065){
113066  int rc, n;
113067  n = nKey1<nKey2 ? nKey1 : nKey2;
113068  rc = memcmp(pKey1, pKey2, n);
113069  if( rc==0 ){
113070    if( padFlag
113071     && allSpaces(((char*)pKey1)+n, nKey1-n)
113072     && allSpaces(((char*)pKey2)+n, nKey2-n)
113073    ){
113074      /* Leave rc unchanged at 0 */
113075    }else{
113076      rc = nKey1 - nKey2;
113077    }
113078  }
113079  return rc;
113080}
113081
113082/*
113083** Another built-in collating sequence: NOCASE.
113084**
113085** This collating sequence is intended to be used for "case independant
113086** comparison". SQLite's knowledge of upper and lower case equivalents
113087** extends only to the 26 characters used in the English language.
113088**
113089** At the moment there is only a UTF-8 implementation.
113090*/
113091static int nocaseCollatingFunc(
113092  void *NotUsed,
113093  int nKey1, const void *pKey1,
113094  int nKey2, const void *pKey2
113095){
113096  int r = sqlite3StrNICmp(
113097      (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
113098  UNUSED_PARAMETER(NotUsed);
113099  if( 0==r ){
113100    r = nKey1-nKey2;
113101  }
113102  return r;
113103}
113104
113105/*
113106** Return the ROWID of the most recent insert
113107*/
113108SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
113109  return db->lastRowid;
113110}
113111
113112/*
113113** Return the number of changes in the most recent call to sqlite3_exec().
113114*/
113115SQLITE_API int sqlite3_changes(sqlite3 *db){
113116  return db->nChange;
113117}
113118
113119/*
113120** Return the number of changes since the database handle was opened.
113121*/
113122SQLITE_API int sqlite3_total_changes(sqlite3 *db){
113123  return db->nTotalChange;
113124}
113125
113126/*
113127** Close all open savepoints. This function only manipulates fields of the
113128** database handle object, it does not close any savepoints that may be open
113129** at the b-tree/pager level.
113130*/
113131SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
113132  while( db->pSavepoint ){
113133    Savepoint *pTmp = db->pSavepoint;
113134    db->pSavepoint = pTmp->pNext;
113135    sqlite3DbFree(db, pTmp);
113136  }
113137  db->nSavepoint = 0;
113138  db->nStatement = 0;
113139  db->isTransactionSavepoint = 0;
113140}
113141
113142/*
113143** Invoke the destructor function associated with FuncDef p, if any. Except,
113144** if this is not the last copy of the function, do not invoke it. Multiple
113145** copies of a single function are created when create_function() is called
113146** with SQLITE_ANY as the encoding.
113147*/
113148static void functionDestroy(sqlite3 *db, FuncDef *p){
113149  FuncDestructor *pDestructor = p->pDestructor;
113150  if( pDestructor ){
113151    pDestructor->nRef--;
113152    if( pDestructor->nRef==0 ){
113153      pDestructor->xDestroy(pDestructor->pUserData);
113154      sqlite3DbFree(db, pDestructor);
113155    }
113156  }
113157}
113158
113159/*
113160** Close an existing SQLite database
113161*/
113162SQLITE_API int sqlite3_close(sqlite3 *db){
113163  HashElem *i;                    /* Hash table iterator */
113164  int j;
113165
113166  if( !db ){
113167    return SQLITE_OK;
113168  }
113169  if( !sqlite3SafetyCheckSickOrOk(db) ){
113170    return SQLITE_MISUSE_BKPT;
113171  }
113172  sqlite3_mutex_enter(db->mutex);
113173
113174  /* Force xDestroy calls on all virtual tables */
113175  sqlite3ResetInternalSchema(db, -1);
113176
113177  /* If a transaction is open, the ResetInternalSchema() call above
113178  ** will not have called the xDisconnect() method on any virtual
113179  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
113180  ** call will do so. We need to do this before the check for active
113181  ** SQL statements below, as the v-table implementation may be storing
113182  ** some prepared statements internally.
113183  */
113184  sqlite3VtabRollback(db);
113185
113186  /* If there are any outstanding VMs, return SQLITE_BUSY. */
113187  if( db->pVdbe ){
113188    sqlite3Error(db, SQLITE_BUSY,
113189        "unable to close due to unfinalised statements");
113190    sqlite3_mutex_leave(db->mutex);
113191    return SQLITE_BUSY;
113192  }
113193  assert( sqlite3SafetyCheckSickOrOk(db) );
113194
113195  for(j=0; j<db->nDb; j++){
113196    Btree *pBt = db->aDb[j].pBt;
113197    if( pBt && sqlite3BtreeIsInBackup(pBt) ){
113198      sqlite3Error(db, SQLITE_BUSY,
113199          "unable to close due to unfinished backup operation");
113200      sqlite3_mutex_leave(db->mutex);
113201      return SQLITE_BUSY;
113202    }
113203  }
113204
113205  /* Free any outstanding Savepoint structures. */
113206  sqlite3CloseSavepoints(db);
113207
113208  for(j=0; j<db->nDb; j++){
113209    struct Db *pDb = &db->aDb[j];
113210    if( pDb->pBt ){
113211      sqlite3BtreeClose(pDb->pBt);
113212      pDb->pBt = 0;
113213      if( j!=1 ){
113214        pDb->pSchema = 0;
113215      }
113216    }
113217  }
113218  sqlite3ResetInternalSchema(db, -1);
113219
113220  /* Tell the code in notify.c that the connection no longer holds any
113221  ** locks and does not require any further unlock-notify callbacks.
113222  */
113223  sqlite3ConnectionClosed(db);
113224
113225  assert( db->nDb<=2 );
113226  assert( db->aDb==db->aDbStatic );
113227  for(j=0; j<ArraySize(db->aFunc.a); j++){
113228    FuncDef *pNext, *pHash, *p;
113229    for(p=db->aFunc.a[j]; p; p=pHash){
113230      pHash = p->pHash;
113231      while( p ){
113232        functionDestroy(db, p);
113233        pNext = p->pNext;
113234        sqlite3DbFree(db, p);
113235        p = pNext;
113236      }
113237    }
113238  }
113239  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
113240    CollSeq *pColl = (CollSeq *)sqliteHashData(i);
113241    /* Invoke any destructors registered for collation sequence user data. */
113242    for(j=0; j<3; j++){
113243      if( pColl[j].xDel ){
113244        pColl[j].xDel(pColl[j].pUser);
113245      }
113246    }
113247    sqlite3DbFree(db, pColl);
113248  }
113249  sqlite3HashClear(&db->aCollSeq);
113250#ifndef SQLITE_OMIT_VIRTUALTABLE
113251  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
113252    Module *pMod = (Module *)sqliteHashData(i);
113253    if( pMod->xDestroy ){
113254      pMod->xDestroy(pMod->pAux);
113255    }
113256    sqlite3DbFree(db, pMod);
113257  }
113258  sqlite3HashClear(&db->aModule);
113259#endif
113260
113261  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
113262  if( db->pErr ){
113263    sqlite3ValueFree(db->pErr);
113264  }
113265  sqlite3CloseExtensions(db);
113266
113267  db->magic = SQLITE_MAGIC_ERROR;
113268
113269  /* The temp-database schema is allocated differently from the other schema
113270  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
113271  ** So it needs to be freed here. Todo: Why not roll the temp schema into
113272  ** the same sqliteMalloc() as the one that allocates the database
113273  ** structure?
113274  */
113275  sqlite3DbFree(db, db->aDb[1].pSchema);
113276  sqlite3_mutex_leave(db->mutex);
113277  db->magic = SQLITE_MAGIC_CLOSED;
113278  sqlite3_mutex_free(db->mutex);
113279  assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
113280  if( db->lookaside.bMalloced ){
113281    sqlite3_free(db->lookaside.pStart);
113282  }
113283  sqlite3_free(db);
113284  return SQLITE_OK;
113285}
113286
113287/*
113288** Rollback all database files.  If tripCode is not SQLITE_OK, then
113289** any open cursors are invalidated ("tripped" - as in "tripping a circuit
113290** breaker") and made to return tripCode if there are any further
113291** attempts to use that cursor.
113292*/
113293SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
113294  int i;
113295  int inTrans = 0;
113296  assert( sqlite3_mutex_held(db->mutex) );
113297  sqlite3BeginBenignMalloc();
113298  for(i=0; i<db->nDb; i++){
113299    Btree *p = db->aDb[i].pBt;
113300    if( p ){
113301      if( sqlite3BtreeIsInTrans(p) ){
113302        inTrans = 1;
113303      }
113304      sqlite3BtreeRollback(p, tripCode);
113305      db->aDb[i].inTrans = 0;
113306    }
113307  }
113308  sqlite3VtabRollback(db);
113309  sqlite3EndBenignMalloc();
113310
113311  if( db->flags&SQLITE_InternChanges ){
113312    sqlite3ExpirePreparedStatements(db);
113313    sqlite3ResetInternalSchema(db, -1);
113314  }
113315
113316  /* Any deferred constraint violations have now been resolved. */
113317  db->nDeferredCons = 0;
113318
113319  /* If one has been configured, invoke the rollback-hook callback */
113320  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
113321    db->xRollbackCallback(db->pRollbackArg);
113322  }
113323}
113324
113325/*
113326** Return a static string that describes the kind of error specified in the
113327** argument.
113328*/
113329SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
113330  static const char* const aMsg[] = {
113331    /* SQLITE_OK          */ "not an error",
113332    /* SQLITE_ERROR       */ "SQL logic error or missing database",
113333    /* SQLITE_INTERNAL    */ 0,
113334    /* SQLITE_PERM        */ "access permission denied",
113335    /* SQLITE_ABORT       */ "callback requested query abort",
113336    /* SQLITE_BUSY        */ "database is locked",
113337    /* SQLITE_LOCKED      */ "database table is locked",
113338    /* SQLITE_NOMEM       */ "out of memory",
113339    /* SQLITE_READONLY    */ "attempt to write a readonly database",
113340    /* SQLITE_INTERRUPT   */ "interrupted",
113341    /* SQLITE_IOERR       */ "disk I/O error",
113342    /* SQLITE_CORRUPT     */ "database disk image is malformed",
113343    /* SQLITE_NOTFOUND    */ "unknown operation",
113344    /* SQLITE_FULL        */ "database or disk is full",
113345    /* SQLITE_CANTOPEN    */ "unable to open database file",
113346    /* SQLITE_PROTOCOL    */ "locking protocol",
113347    /* SQLITE_EMPTY       */ "table contains no data",
113348    /* SQLITE_SCHEMA      */ "database schema has changed",
113349    /* SQLITE_TOOBIG      */ "string or blob too big",
113350    /* SQLITE_CONSTRAINT  */ "constraint failed",
113351    /* SQLITE_MISMATCH    */ "datatype mismatch",
113352    /* SQLITE_MISUSE      */ "library routine called out of sequence",
113353    /* SQLITE_NOLFS       */ "large file support is disabled",
113354    /* SQLITE_AUTH        */ "authorization denied",
113355    /* SQLITE_FORMAT      */ "auxiliary database format error",
113356    /* SQLITE_RANGE       */ "bind or column index out of range",
113357    /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
113358  };
113359  const char *zErr = "unknown error";
113360  switch( rc ){
113361    case SQLITE_ABORT_ROLLBACK: {
113362      zErr = "abort due to ROLLBACK";
113363      break;
113364    }
113365    default: {
113366      rc &= 0xff;
113367      if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
113368        zErr = aMsg[rc];
113369      }
113370      break;
113371    }
113372  }
113373  return zErr;
113374}
113375
113376/*
113377** This routine implements a busy callback that sleeps and tries
113378** again until a timeout value is reached.  The timeout value is
113379** an integer number of milliseconds passed in as the first
113380** argument.
113381*/
113382static int sqliteDefaultBusyCallback(
113383 void *ptr,               /* Database connection */
113384 int count                /* Number of times table has been busy */
113385){
113386#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
113387  static const u8 delays[] =
113388     { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
113389  static const u8 totals[] =
113390     { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
113391# define NDELAY ArraySize(delays)
113392  sqlite3 *db = (sqlite3 *)ptr;
113393  int timeout = db->busyTimeout;
113394  int delay, prior;
113395
113396  assert( count>=0 );
113397  if( count < NDELAY ){
113398    delay = delays[count];
113399    prior = totals[count];
113400  }else{
113401    delay = delays[NDELAY-1];
113402    prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
113403  }
113404  if( prior + delay > timeout ){
113405    delay = timeout - prior;
113406    if( delay<=0 ) return 0;
113407  }
113408  sqlite3OsSleep(db->pVfs, delay*1000);
113409  return 1;
113410#else
113411  sqlite3 *db = (sqlite3 *)ptr;
113412  int timeout = ((sqlite3 *)ptr)->busyTimeout;
113413  if( (count+1)*1000 > timeout ){
113414    return 0;
113415  }
113416  sqlite3OsSleep(db->pVfs, 1000000);
113417  return 1;
113418#endif
113419}
113420
113421/*
113422** Invoke the given busy handler.
113423**
113424** This routine is called when an operation failed with a lock.
113425** If this routine returns non-zero, the lock is retried.  If it
113426** returns 0, the operation aborts with an SQLITE_BUSY error.
113427*/
113428SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
113429  int rc;
113430  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
113431  rc = p->xFunc(p->pArg, p->nBusy);
113432  if( rc==0 ){
113433    p->nBusy = -1;
113434  }else{
113435    p->nBusy++;
113436  }
113437  return rc;
113438}
113439
113440/*
113441** This routine sets the busy callback for an Sqlite database to the
113442** given callback function with the given argument.
113443*/
113444SQLITE_API int sqlite3_busy_handler(
113445  sqlite3 *db,
113446  int (*xBusy)(void*,int),
113447  void *pArg
113448){
113449  sqlite3_mutex_enter(db->mutex);
113450  db->busyHandler.xFunc = xBusy;
113451  db->busyHandler.pArg = pArg;
113452  db->busyHandler.nBusy = 0;
113453  sqlite3_mutex_leave(db->mutex);
113454  return SQLITE_OK;
113455}
113456
113457#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
113458/*
113459** This routine sets the progress callback for an Sqlite database to the
113460** given callback function with the given argument. The progress callback will
113461** be invoked every nOps opcodes.
113462*/
113463SQLITE_API void sqlite3_progress_handler(
113464  sqlite3 *db,
113465  int nOps,
113466  int (*xProgress)(void*),
113467  void *pArg
113468){
113469  sqlite3_mutex_enter(db->mutex);
113470  if( nOps>0 ){
113471    db->xProgress = xProgress;
113472    db->nProgressOps = nOps;
113473    db->pProgressArg = pArg;
113474  }else{
113475    db->xProgress = 0;
113476    db->nProgressOps = 0;
113477    db->pProgressArg = 0;
113478  }
113479  sqlite3_mutex_leave(db->mutex);
113480}
113481#endif
113482
113483
113484/*
113485** This routine installs a default busy handler that waits for the
113486** specified number of milliseconds before returning 0.
113487*/
113488SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
113489  if( ms>0 ){
113490    db->busyTimeout = ms;
113491    sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
113492  }else{
113493    sqlite3_busy_handler(db, 0, 0);
113494  }
113495  return SQLITE_OK;
113496}
113497
113498/*
113499** Cause any pending operation to stop at its earliest opportunity.
113500*/
113501SQLITE_API void sqlite3_interrupt(sqlite3 *db){
113502  db->u1.isInterrupted = 1;
113503}
113504
113505
113506/*
113507** This function is exactly the same as sqlite3_create_function(), except
113508** that it is designed to be called by internal code. The difference is
113509** that if a malloc() fails in sqlite3_create_function(), an error code
113510** is returned and the mallocFailed flag cleared.
113511*/
113512SQLITE_PRIVATE int sqlite3CreateFunc(
113513  sqlite3 *db,
113514  const char *zFunctionName,
113515  int nArg,
113516  int enc,
113517  void *pUserData,
113518  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
113519  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
113520  void (*xFinal)(sqlite3_context*),
113521  FuncDestructor *pDestructor
113522){
113523  FuncDef *p;
113524  int nName;
113525
113526  assert( sqlite3_mutex_held(db->mutex) );
113527  if( zFunctionName==0 ||
113528      (xFunc && (xFinal || xStep)) ||
113529      (!xFunc && (xFinal && !xStep)) ||
113530      (!xFunc && (!xFinal && xStep)) ||
113531      (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
113532      (255<(nName = sqlite3Strlen30( zFunctionName))) ){
113533    return SQLITE_MISUSE_BKPT;
113534  }
113535
113536#ifndef SQLITE_OMIT_UTF16
113537  /* If SQLITE_UTF16 is specified as the encoding type, transform this
113538  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
113539  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
113540  **
113541  ** If SQLITE_ANY is specified, add three versions of the function
113542  ** to the hash table.
113543  */
113544  if( enc==SQLITE_UTF16 ){
113545    enc = SQLITE_UTF16NATIVE;
113546  }else if( enc==SQLITE_ANY ){
113547    int rc;
113548    rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
113549         pUserData, xFunc, xStep, xFinal, pDestructor);
113550    if( rc==SQLITE_OK ){
113551      rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
113552          pUserData, xFunc, xStep, xFinal, pDestructor);
113553    }
113554    if( rc!=SQLITE_OK ){
113555      return rc;
113556    }
113557    enc = SQLITE_UTF16BE;
113558  }
113559#else
113560  enc = SQLITE_UTF8;
113561#endif
113562
113563  /* Check if an existing function is being overridden or deleted. If so,
113564  ** and there are active VMs, then return SQLITE_BUSY. If a function
113565  ** is being overridden/deleted but there are no active VMs, allow the
113566  ** operation to continue but invalidate all precompiled statements.
113567  */
113568  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
113569  if( p && p->iPrefEnc==enc && p->nArg==nArg ){
113570    if( db->activeVdbeCnt ){
113571      sqlite3Error(db, SQLITE_BUSY,
113572        "unable to delete/modify user-function due to active statements");
113573      assert( !db->mallocFailed );
113574      return SQLITE_BUSY;
113575    }else{
113576      sqlite3ExpirePreparedStatements(db);
113577    }
113578  }
113579
113580  p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
113581  assert(p || db->mallocFailed);
113582  if( !p ){
113583    return SQLITE_NOMEM;
113584  }
113585
113586  /* If an older version of the function with a configured destructor is
113587  ** being replaced invoke the destructor function here. */
113588  functionDestroy(db, p);
113589
113590  if( pDestructor ){
113591    pDestructor->nRef++;
113592  }
113593  p->pDestructor = pDestructor;
113594  p->flags = 0;
113595  p->xFunc = xFunc;
113596  p->xStep = xStep;
113597  p->xFinalize = xFinal;
113598  p->pUserData = pUserData;
113599  p->nArg = (u16)nArg;
113600  return SQLITE_OK;
113601}
113602
113603/*
113604** Create new user functions.
113605*/
113606SQLITE_API int sqlite3_create_function(
113607  sqlite3 *db,
113608  const char *zFunc,
113609  int nArg,
113610  int enc,
113611  void *p,
113612  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
113613  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
113614  void (*xFinal)(sqlite3_context*)
113615){
113616  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
113617                                    xFinal, 0);
113618}
113619
113620SQLITE_API int sqlite3_create_function_v2(
113621  sqlite3 *db,
113622  const char *zFunc,
113623  int nArg,
113624  int enc,
113625  void *p,
113626  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
113627  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
113628  void (*xFinal)(sqlite3_context*),
113629  void (*xDestroy)(void *)
113630){
113631  int rc = SQLITE_ERROR;
113632  FuncDestructor *pArg = 0;
113633  sqlite3_mutex_enter(db->mutex);
113634  if( xDestroy ){
113635    pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
113636    if( !pArg ){
113637      xDestroy(p);
113638      goto out;
113639    }
113640    pArg->xDestroy = xDestroy;
113641    pArg->pUserData = p;
113642  }
113643  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
113644  if( pArg && pArg->nRef==0 ){
113645    assert( rc!=SQLITE_OK );
113646    xDestroy(p);
113647    sqlite3DbFree(db, pArg);
113648  }
113649
113650 out:
113651  rc = sqlite3ApiExit(db, rc);
113652  sqlite3_mutex_leave(db->mutex);
113653  return rc;
113654}
113655
113656#ifndef SQLITE_OMIT_UTF16
113657SQLITE_API int sqlite3_create_function16(
113658  sqlite3 *db,
113659  const void *zFunctionName,
113660  int nArg,
113661  int eTextRep,
113662  void *p,
113663  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
113664  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
113665  void (*xFinal)(sqlite3_context*)
113666){
113667  int rc;
113668  char *zFunc8;
113669  sqlite3_mutex_enter(db->mutex);
113670  assert( !db->mallocFailed );
113671  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
113672  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
113673  sqlite3DbFree(db, zFunc8);
113674  rc = sqlite3ApiExit(db, rc);
113675  sqlite3_mutex_leave(db->mutex);
113676  return rc;
113677}
113678#endif
113679
113680
113681/*
113682** Declare that a function has been overloaded by a virtual table.
113683**
113684** If the function already exists as a regular global function, then
113685** this routine is a no-op.  If the function does not exist, then create
113686** a new one that always throws a run-time error.
113687**
113688** When virtual tables intend to provide an overloaded function, they
113689** should call this routine to make sure the global function exists.
113690** A global function must exist in order for name resolution to work
113691** properly.
113692*/
113693SQLITE_API int sqlite3_overload_function(
113694  sqlite3 *db,
113695  const char *zName,
113696  int nArg
113697){
113698  int nName = sqlite3Strlen30(zName);
113699  int rc = SQLITE_OK;
113700  sqlite3_mutex_enter(db->mutex);
113701  if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
113702    rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
113703                           0, sqlite3InvalidFunction, 0, 0, 0);
113704  }
113705  rc = sqlite3ApiExit(db, rc);
113706  sqlite3_mutex_leave(db->mutex);
113707  return rc;
113708}
113709
113710#ifndef SQLITE_OMIT_TRACE
113711/*
113712** Register a trace function.  The pArg from the previously registered trace
113713** is returned.
113714**
113715** A NULL trace function means that no tracing is executes.  A non-NULL
113716** trace is a pointer to a function that is invoked at the start of each
113717** SQL statement.
113718*/
113719SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
113720  void *pOld;
113721  sqlite3_mutex_enter(db->mutex);
113722  pOld = db->pTraceArg;
113723  db->xTrace = xTrace;
113724  db->pTraceArg = pArg;
113725  sqlite3_mutex_leave(db->mutex);
113726  return pOld;
113727}
113728/*
113729** Register a profile function.  The pArg from the previously registered
113730** profile function is returned.
113731**
113732** A NULL profile function means that no profiling is executes.  A non-NULL
113733** profile is a pointer to a function that is invoked at the conclusion of
113734** each SQL statement that is run.
113735*/
113736SQLITE_API void *sqlite3_profile(
113737  sqlite3 *db,
113738  void (*xProfile)(void*,const char*,sqlite_uint64),
113739  void *pArg
113740){
113741  void *pOld;
113742  sqlite3_mutex_enter(db->mutex);
113743  pOld = db->pProfileArg;
113744  db->xProfile = xProfile;
113745  db->pProfileArg = pArg;
113746  sqlite3_mutex_leave(db->mutex);
113747  return pOld;
113748}
113749#endif /* SQLITE_OMIT_TRACE */
113750
113751/*
113752** Register a function to be invoked when a transaction commits.
113753** If the invoked function returns non-zero, then the commit becomes a
113754** rollback.
113755*/
113756SQLITE_API void *sqlite3_commit_hook(
113757  sqlite3 *db,              /* Attach the hook to this database */
113758  int (*xCallback)(void*),  /* Function to invoke on each commit */
113759  void *pArg                /* Argument to the function */
113760){
113761  void *pOld;
113762  sqlite3_mutex_enter(db->mutex);
113763  pOld = db->pCommitArg;
113764  db->xCommitCallback = xCallback;
113765  db->pCommitArg = pArg;
113766  sqlite3_mutex_leave(db->mutex);
113767  return pOld;
113768}
113769
113770/*
113771** Register a callback to be invoked each time a row is updated,
113772** inserted or deleted using this database connection.
113773*/
113774SQLITE_API void *sqlite3_update_hook(
113775  sqlite3 *db,              /* Attach the hook to this database */
113776  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
113777  void *pArg                /* Argument to the function */
113778){
113779  void *pRet;
113780  sqlite3_mutex_enter(db->mutex);
113781  pRet = db->pUpdateArg;
113782  db->xUpdateCallback = xCallback;
113783  db->pUpdateArg = pArg;
113784  sqlite3_mutex_leave(db->mutex);
113785  return pRet;
113786}
113787
113788/*
113789** Register a callback to be invoked each time a transaction is rolled
113790** back by this database connection.
113791*/
113792SQLITE_API void *sqlite3_rollback_hook(
113793  sqlite3 *db,              /* Attach the hook to this database */
113794  void (*xCallback)(void*), /* Callback function */
113795  void *pArg                /* Argument to the function */
113796){
113797  void *pRet;
113798  sqlite3_mutex_enter(db->mutex);
113799  pRet = db->pRollbackArg;
113800  db->xRollbackCallback = xCallback;
113801  db->pRollbackArg = pArg;
113802  sqlite3_mutex_leave(db->mutex);
113803  return pRet;
113804}
113805
113806#ifndef SQLITE_OMIT_WAL
113807/*
113808** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
113809** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
113810** is greater than sqlite3.pWalArg cast to an integer (the value configured by
113811** wal_autocheckpoint()).
113812*/
113813SQLITE_PRIVATE int sqlite3WalDefaultHook(
113814  void *pClientData,     /* Argument */
113815  sqlite3 *db,           /* Connection */
113816  const char *zDb,       /* Database */
113817  int nFrame             /* Size of WAL */
113818){
113819  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
113820    sqlite3BeginBenignMalloc();
113821    sqlite3_wal_checkpoint(db, zDb);
113822    sqlite3EndBenignMalloc();
113823  }
113824  return SQLITE_OK;
113825}
113826#endif /* SQLITE_OMIT_WAL */
113827
113828/*
113829** Configure an sqlite3_wal_hook() callback to automatically checkpoint
113830** a database after committing a transaction if there are nFrame or
113831** more frames in the log file. Passing zero or a negative value as the
113832** nFrame parameter disables automatic checkpoints entirely.
113833**
113834** The callback registered by this function replaces any existing callback
113835** registered using sqlite3_wal_hook(). Likewise, registering a callback
113836** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
113837** configured by this function.
113838*/
113839SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
113840#ifdef SQLITE_OMIT_WAL
113841  UNUSED_PARAMETER(db);
113842  UNUSED_PARAMETER(nFrame);
113843#else
113844  if( nFrame>0 ){
113845    sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
113846  }else{
113847    sqlite3_wal_hook(db, 0, 0);
113848  }
113849#endif
113850  return SQLITE_OK;
113851}
113852
113853/*
113854** Register a callback to be invoked each time a transaction is written
113855** into the write-ahead-log by this database connection.
113856*/
113857SQLITE_API void *sqlite3_wal_hook(
113858  sqlite3 *db,                    /* Attach the hook to this db handle */
113859  int(*xCallback)(void *, sqlite3*, const char*, int),
113860  void *pArg                      /* First argument passed to xCallback() */
113861){
113862#ifndef SQLITE_OMIT_WAL
113863  void *pRet;
113864  sqlite3_mutex_enter(db->mutex);
113865  pRet = db->pWalArg;
113866  db->xWalCallback = xCallback;
113867  db->pWalArg = pArg;
113868  sqlite3_mutex_leave(db->mutex);
113869  return pRet;
113870#else
113871  return 0;
113872#endif
113873}
113874
113875/*
113876** Checkpoint database zDb.
113877*/
113878SQLITE_API int sqlite3_wal_checkpoint_v2(
113879  sqlite3 *db,                    /* Database handle */
113880  const char *zDb,                /* Name of attached database (or NULL) */
113881  int eMode,                      /* SQLITE_CHECKPOINT_* value */
113882  int *pnLog,                     /* OUT: Size of WAL log in frames */
113883  int *pnCkpt                     /* OUT: Total number of frames checkpointed */
113884){
113885#ifdef SQLITE_OMIT_WAL
113886  return SQLITE_OK;
113887#else
113888  int rc;                         /* Return code */
113889  int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
113890
113891  /* Initialize the output variables to -1 in case an error occurs. */
113892  if( pnLog ) *pnLog = -1;
113893  if( pnCkpt ) *pnCkpt = -1;
113894
113895  assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
113896  assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
113897  assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
113898  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
113899    return SQLITE_MISUSE;
113900  }
113901
113902  sqlite3_mutex_enter(db->mutex);
113903  if( zDb && zDb[0] ){
113904    iDb = sqlite3FindDbName(db, zDb);
113905  }
113906  if( iDb<0 ){
113907    rc = SQLITE_ERROR;
113908    sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
113909  }else{
113910    rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
113911    sqlite3Error(db, rc, 0);
113912  }
113913  rc = sqlite3ApiExit(db, rc);
113914  sqlite3_mutex_leave(db->mutex);
113915  return rc;
113916#endif
113917}
113918
113919
113920/*
113921** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
113922** to contains a zero-length string, all attached databases are
113923** checkpointed.
113924*/
113925SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
113926  return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
113927}
113928
113929#ifndef SQLITE_OMIT_WAL
113930/*
113931** Run a checkpoint on database iDb. This is a no-op if database iDb is
113932** not currently open in WAL mode.
113933**
113934** If a transaction is open on the database being checkpointed, this
113935** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
113936** an error occurs while running the checkpoint, an SQLite error code is
113937** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
113938**
113939** The mutex on database handle db should be held by the caller. The mutex
113940** associated with the specific b-tree being checkpointed is taken by
113941** this function while the checkpoint is running.
113942**
113943** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
113944** checkpointed. If an error is encountered it is returned immediately -
113945** no attempt is made to checkpoint any remaining databases.
113946**
113947** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
113948*/
113949SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
113950  int rc = SQLITE_OK;             /* Return code */
113951  int i;                          /* Used to iterate through attached dbs */
113952  int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
113953
113954  assert( sqlite3_mutex_held(db->mutex) );
113955  assert( !pnLog || *pnLog==-1 );
113956  assert( !pnCkpt || *pnCkpt==-1 );
113957
113958  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
113959    if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
113960      rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
113961      pnLog = 0;
113962      pnCkpt = 0;
113963      if( rc==SQLITE_BUSY ){
113964        bBusy = 1;
113965        rc = SQLITE_OK;
113966      }
113967    }
113968  }
113969
113970  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
113971}
113972#endif /* SQLITE_OMIT_WAL */
113973
113974/*
113975** This function returns true if main-memory should be used instead of
113976** a temporary file for transient pager files and statement journals.
113977** The value returned depends on the value of db->temp_store (runtime
113978** parameter) and the compile time value of SQLITE_TEMP_STORE. The
113979** following table describes the relationship between these two values
113980** and this functions return value.
113981**
113982**   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
113983**   -----------------     --------------     ------------------------------
113984**   0                     any                file      (return 0)
113985**   1                     1                  file      (return 0)
113986**   1                     2                  memory    (return 1)
113987**   1                     0                  file      (return 0)
113988**   2                     1                  file      (return 0)
113989**   2                     2                  memory    (return 1)
113990**   2                     0                  memory    (return 1)
113991**   3                     any                memory    (return 1)
113992*/
113993SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
113994#if SQLITE_TEMP_STORE==1
113995  return ( db->temp_store==2 );
113996#endif
113997#if SQLITE_TEMP_STORE==2
113998  return ( db->temp_store!=1 );
113999#endif
114000#if SQLITE_TEMP_STORE==3
114001  return 1;
114002#endif
114003#if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
114004  return 0;
114005#endif
114006}
114007
114008/*
114009** Return UTF-8 encoded English language explanation of the most recent
114010** error.
114011*/
114012SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
114013  const char *z;
114014  if( !db ){
114015    return sqlite3ErrStr(SQLITE_NOMEM);
114016  }
114017  if( !sqlite3SafetyCheckSickOrOk(db) ){
114018    return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
114019  }
114020  sqlite3_mutex_enter(db->mutex);
114021  if( db->mallocFailed ){
114022    z = sqlite3ErrStr(SQLITE_NOMEM);
114023  }else{
114024    z = (char*)sqlite3_value_text(db->pErr);
114025    assert( !db->mallocFailed );
114026    if( z==0 ){
114027      z = sqlite3ErrStr(db->errCode);
114028    }
114029  }
114030  sqlite3_mutex_leave(db->mutex);
114031  return z;
114032}
114033
114034#ifndef SQLITE_OMIT_UTF16
114035/*
114036** Return UTF-16 encoded English language explanation of the most recent
114037** error.
114038*/
114039SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
114040  static const u16 outOfMem[] = {
114041    'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
114042  };
114043  static const u16 misuse[] = {
114044    'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
114045    'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
114046    'c', 'a', 'l', 'l', 'e', 'd', ' ',
114047    'o', 'u', 't', ' ',
114048    'o', 'f', ' ',
114049    's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
114050  };
114051
114052  const void *z;
114053  if( !db ){
114054    return (void *)outOfMem;
114055  }
114056  if( !sqlite3SafetyCheckSickOrOk(db) ){
114057    return (void *)misuse;
114058  }
114059  sqlite3_mutex_enter(db->mutex);
114060  if( db->mallocFailed ){
114061    z = (void *)outOfMem;
114062  }else{
114063    z = sqlite3_value_text16(db->pErr);
114064    if( z==0 ){
114065      sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
114066           SQLITE_UTF8, SQLITE_STATIC);
114067      z = sqlite3_value_text16(db->pErr);
114068    }
114069    /* A malloc() may have failed within the call to sqlite3_value_text16()
114070    ** above. If this is the case, then the db->mallocFailed flag needs to
114071    ** be cleared before returning. Do this directly, instead of via
114072    ** sqlite3ApiExit(), to avoid setting the database handle error message.
114073    */
114074    db->mallocFailed = 0;
114075  }
114076  sqlite3_mutex_leave(db->mutex);
114077  return z;
114078}
114079#endif /* SQLITE_OMIT_UTF16 */
114080
114081/*
114082** Return the most recent error code generated by an SQLite routine. If NULL is
114083** passed to this function, we assume a malloc() failed during sqlite3_open().
114084*/
114085SQLITE_API int sqlite3_errcode(sqlite3 *db){
114086  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
114087    return SQLITE_MISUSE_BKPT;
114088  }
114089  if( !db || db->mallocFailed ){
114090    return SQLITE_NOMEM;
114091  }
114092  return db->errCode & db->errMask;
114093}
114094SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
114095  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
114096    return SQLITE_MISUSE_BKPT;
114097  }
114098  if( !db || db->mallocFailed ){
114099    return SQLITE_NOMEM;
114100  }
114101  return db->errCode;
114102}
114103
114104/*
114105** Create a new collating function for database "db".  The name is zName
114106** and the encoding is enc.
114107*/
114108static int createCollation(
114109  sqlite3* db,
114110  const char *zName,
114111  u8 enc,
114112  void* pCtx,
114113  int(*xCompare)(void*,int,const void*,int,const void*),
114114  void(*xDel)(void*)
114115){
114116  CollSeq *pColl;
114117  int enc2;
114118  int nName = sqlite3Strlen30(zName);
114119
114120  assert( sqlite3_mutex_held(db->mutex) );
114121
114122  /* If SQLITE_UTF16 is specified as the encoding type, transform this
114123  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
114124  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
114125  */
114126  enc2 = enc;
114127  testcase( enc2==SQLITE_UTF16 );
114128  testcase( enc2==SQLITE_UTF16_ALIGNED );
114129  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
114130    enc2 = SQLITE_UTF16NATIVE;
114131  }
114132  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
114133    return SQLITE_MISUSE_BKPT;
114134  }
114135
114136  /* Check if this call is removing or replacing an existing collation
114137  ** sequence. If so, and there are active VMs, return busy. If there
114138  ** are no active VMs, invalidate any pre-compiled statements.
114139  */
114140  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
114141  if( pColl && pColl->xCmp ){
114142    if( db->activeVdbeCnt ){
114143      sqlite3Error(db, SQLITE_BUSY,
114144        "unable to delete/modify collation sequence due to active statements");
114145      return SQLITE_BUSY;
114146    }
114147    sqlite3ExpirePreparedStatements(db);
114148
114149    /* If collation sequence pColl was created directly by a call to
114150    ** sqlite3_create_collation, and not generated by synthCollSeq(),
114151    ** then any copies made by synthCollSeq() need to be invalidated.
114152    ** Also, collation destructor - CollSeq.xDel() - function may need
114153    ** to be called.
114154    */
114155    if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
114156      CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
114157      int j;
114158      for(j=0; j<3; j++){
114159        CollSeq *p = &aColl[j];
114160        if( p->enc==pColl->enc ){
114161          if( p->xDel ){
114162            p->xDel(p->pUser);
114163          }
114164          p->xCmp = 0;
114165        }
114166      }
114167    }
114168  }
114169
114170  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
114171  if( pColl==0 ) return SQLITE_NOMEM;
114172  pColl->xCmp = xCompare;
114173  pColl->pUser = pCtx;
114174  pColl->xDel = xDel;
114175  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
114176  sqlite3Error(db, SQLITE_OK, 0);
114177  return SQLITE_OK;
114178}
114179
114180
114181/*
114182** This array defines hard upper bounds on limit values.  The
114183** initializer must be kept in sync with the SQLITE_LIMIT_*
114184** #defines in sqlite3.h.
114185*/
114186static const int aHardLimit[] = {
114187  SQLITE_MAX_LENGTH,
114188  SQLITE_MAX_SQL_LENGTH,
114189  SQLITE_MAX_COLUMN,
114190  SQLITE_MAX_EXPR_DEPTH,
114191  SQLITE_MAX_COMPOUND_SELECT,
114192  SQLITE_MAX_VDBE_OP,
114193  SQLITE_MAX_FUNCTION_ARG,
114194  SQLITE_MAX_ATTACHED,
114195  SQLITE_MAX_LIKE_PATTERN_LENGTH,
114196  SQLITE_MAX_VARIABLE_NUMBER,
114197  SQLITE_MAX_TRIGGER_DEPTH,
114198};
114199
114200/*
114201** Make sure the hard limits are set to reasonable values
114202*/
114203#if SQLITE_MAX_LENGTH<100
114204# error SQLITE_MAX_LENGTH must be at least 100
114205#endif
114206#if SQLITE_MAX_SQL_LENGTH<100
114207# error SQLITE_MAX_SQL_LENGTH must be at least 100
114208#endif
114209#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
114210# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
114211#endif
114212#if SQLITE_MAX_COMPOUND_SELECT<2
114213# error SQLITE_MAX_COMPOUND_SELECT must be at least 2
114214#endif
114215#if SQLITE_MAX_VDBE_OP<40
114216# error SQLITE_MAX_VDBE_OP must be at least 40
114217#endif
114218#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
114219# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
114220#endif
114221#if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
114222# error SQLITE_MAX_ATTACHED must be between 0 and 62
114223#endif
114224#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
114225# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
114226#endif
114227#if SQLITE_MAX_COLUMN>32767
114228# error SQLITE_MAX_COLUMN must not exceed 32767
114229#endif
114230#if SQLITE_MAX_TRIGGER_DEPTH<1
114231# error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
114232#endif
114233
114234
114235/*
114236** Change the value of a limit.  Report the old value.
114237** If an invalid limit index is supplied, report -1.
114238** Make no changes but still report the old value if the
114239** new limit is negative.
114240**
114241** A new lower limit does not shrink existing constructs.
114242** It merely prevents new constructs that exceed the limit
114243** from forming.
114244*/
114245SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
114246  int oldLimit;
114247
114248
114249  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
114250  ** there is a hard upper bound set at compile-time by a C preprocessor
114251  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
114252  ** "_MAX_".)
114253  */
114254  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
114255  assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
114256  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
114257  assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
114258  assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
114259  assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
114260  assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
114261  assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
114262  assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
114263                                               SQLITE_MAX_LIKE_PATTERN_LENGTH );
114264  assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
114265  assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
114266  assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
114267
114268
114269  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
114270    return -1;
114271  }
114272  oldLimit = db->aLimit[limitId];
114273  if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
114274    if( newLimit>aHardLimit[limitId] ){
114275      newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
114276    }
114277    db->aLimit[limitId] = newLimit;
114278  }
114279  return oldLimit;                     /* IMP: R-53341-35419 */
114280}
114281
114282/*
114283** This function is used to parse both URIs and non-URI filenames passed by the
114284** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
114285** URIs specified as part of ATTACH statements.
114286**
114287** The first argument to this function is the name of the VFS to use (or
114288** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
114289** query parameter. The second argument contains the URI (or non-URI filename)
114290** itself. When this function is called the *pFlags variable should contain
114291** the default flags to open the database handle with. The value stored in
114292** *pFlags may be updated before returning if the URI filename contains
114293** "cache=xxx" or "mode=xxx" query parameters.
114294**
114295** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
114296** the VFS that should be used to open the database file. *pzFile is set to
114297** point to a buffer containing the name of the file to open. It is the
114298** responsibility of the caller to eventually call sqlite3_free() to release
114299** this buffer.
114300**
114301** If an error occurs, then an SQLite error code is returned and *pzErrMsg
114302** may be set to point to a buffer containing an English language error
114303** message. It is the responsibility of the caller to eventually release
114304** this buffer by calling sqlite3_free().
114305*/
114306SQLITE_PRIVATE int sqlite3ParseUri(
114307  const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
114308  const char *zUri,               /* Nul-terminated URI to parse */
114309  unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
114310  sqlite3_vfs **ppVfs,            /* OUT: VFS to use */
114311  char **pzFile,                  /* OUT: Filename component of URI */
114312  char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
114313){
114314  int rc = SQLITE_OK;
114315  unsigned int flags = *pFlags;
114316  const char *zVfs = zDefaultVfs;
114317  char *zFile;
114318  char c;
114319  int nUri = sqlite3Strlen30(zUri);
114320
114321  assert( *pzErrMsg==0 );
114322
114323  if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
114324   && nUri>=5 && memcmp(zUri, "file:", 5)==0
114325  ){
114326    char *zOpt;
114327    int eState;                   /* Parser state when parsing URI */
114328    int iIn;                      /* Input character index */
114329    int iOut = 0;                 /* Output character index */
114330    int nByte = nUri+2;           /* Bytes of space to allocate */
114331
114332    /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
114333    ** method that there may be extra parameters following the file-name.  */
114334    flags |= SQLITE_OPEN_URI;
114335
114336    for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
114337    zFile = sqlite3_malloc(nByte);
114338    if( !zFile ) return SQLITE_NOMEM;
114339
114340    /* Discard the scheme and authority segments of the URI. */
114341    if( zUri[5]=='/' && zUri[6]=='/' ){
114342      iIn = 7;
114343      while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
114344
114345      if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
114346        *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
114347            iIn-7, &zUri[7]);
114348        rc = SQLITE_ERROR;
114349        goto parse_uri_out;
114350      }
114351    }else{
114352      iIn = 5;
114353    }
114354
114355    /* Copy the filename and any query parameters into the zFile buffer.
114356    ** Decode %HH escape codes along the way.
114357    **
114358    ** Within this loop, variable eState may be set to 0, 1 or 2, depending
114359    ** on the parsing context. As follows:
114360    **
114361    **   0: Parsing file-name.
114362    **   1: Parsing name section of a name=value query parameter.
114363    **   2: Parsing value section of a name=value query parameter.
114364    */
114365    eState = 0;
114366    while( (c = zUri[iIn])!=0 && c!='#' ){
114367      iIn++;
114368      if( c=='%'
114369       && sqlite3Isxdigit(zUri[iIn])
114370       && sqlite3Isxdigit(zUri[iIn+1])
114371      ){
114372        int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
114373        octet += sqlite3HexToInt(zUri[iIn++]);
114374
114375        assert( octet>=0 && octet<256 );
114376        if( octet==0 ){
114377          /* This branch is taken when "%00" appears within the URI. In this
114378          ** case we ignore all text in the remainder of the path, name or
114379          ** value currently being parsed. So ignore the current character
114380          ** and skip to the next "?", "=" or "&", as appropriate. */
114381          while( (c = zUri[iIn])!=0 && c!='#'
114382              && (eState!=0 || c!='?')
114383              && (eState!=1 || (c!='=' && c!='&'))
114384              && (eState!=2 || c!='&')
114385          ){
114386            iIn++;
114387          }
114388          continue;
114389        }
114390        c = octet;
114391      }else if( eState==1 && (c=='&' || c=='=') ){
114392        if( zFile[iOut-1]==0 ){
114393          /* An empty option name. Ignore this option altogether. */
114394          while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
114395          continue;
114396        }
114397        if( c=='&' ){
114398          zFile[iOut++] = '\0';
114399        }else{
114400          eState = 2;
114401        }
114402        c = 0;
114403      }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
114404        c = 0;
114405        eState = 1;
114406      }
114407      zFile[iOut++] = c;
114408    }
114409    if( eState==1 ) zFile[iOut++] = '\0';
114410    zFile[iOut++] = '\0';
114411    zFile[iOut++] = '\0';
114412
114413    /* Check if there were any options specified that should be interpreted
114414    ** here. Options that are interpreted here include "vfs" and those that
114415    ** correspond to flags that may be passed to the sqlite3_open_v2()
114416    ** method. */
114417    zOpt = &zFile[sqlite3Strlen30(zFile)+1];
114418    while( zOpt[0] ){
114419      int nOpt = sqlite3Strlen30(zOpt);
114420      char *zVal = &zOpt[nOpt+1];
114421      int nVal = sqlite3Strlen30(zVal);
114422
114423      if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
114424        zVfs = zVal;
114425      }else{
114426        struct OpenMode {
114427          const char *z;
114428          int mode;
114429        } *aMode = 0;
114430        char *zModeType = 0;
114431        int mask = 0;
114432        int limit = 0;
114433
114434        if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
114435          static struct OpenMode aCacheMode[] = {
114436            { "shared",  SQLITE_OPEN_SHAREDCACHE },
114437            { "private", SQLITE_OPEN_PRIVATECACHE },
114438            { 0, 0 }
114439          };
114440
114441          mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
114442          aMode = aCacheMode;
114443          limit = mask;
114444          zModeType = "cache";
114445        }
114446        if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
114447          static struct OpenMode aOpenMode[] = {
114448            { "ro",  SQLITE_OPEN_READONLY },
114449            { "rw",  SQLITE_OPEN_READWRITE },
114450            { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
114451            { 0, 0 }
114452          };
114453
114454          mask = SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
114455          aMode = aOpenMode;
114456          limit = mask & flags;
114457          zModeType = "access";
114458        }
114459
114460        if( aMode ){
114461          int i;
114462          int mode = 0;
114463          for(i=0; aMode[i].z; i++){
114464            const char *z = aMode[i].z;
114465            if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
114466              mode = aMode[i].mode;
114467              break;
114468            }
114469          }
114470          if( mode==0 ){
114471            *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
114472            rc = SQLITE_ERROR;
114473            goto parse_uri_out;
114474          }
114475          if( mode>limit ){
114476            *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
114477                                        zModeType, zVal);
114478            rc = SQLITE_PERM;
114479            goto parse_uri_out;
114480          }
114481          flags = (flags & ~mask) | mode;
114482        }
114483      }
114484
114485      zOpt = &zVal[nVal+1];
114486    }
114487
114488  }else{
114489    zFile = sqlite3_malloc(nUri+2);
114490    if( !zFile ) return SQLITE_NOMEM;
114491    memcpy(zFile, zUri, nUri);
114492    zFile[nUri] = '\0';
114493    zFile[nUri+1] = '\0';
114494  }
114495
114496  *ppVfs = sqlite3_vfs_find(zVfs);
114497  if( *ppVfs==0 ){
114498    *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
114499    rc = SQLITE_ERROR;
114500  }
114501 parse_uri_out:
114502  if( rc!=SQLITE_OK ){
114503    sqlite3_free(zFile);
114504    zFile = 0;
114505  }
114506  *pFlags = flags;
114507  *pzFile = zFile;
114508  return rc;
114509}
114510
114511
114512/*
114513** This routine does the work of opening a database on behalf of
114514** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
114515** is UTF-8 encoded.
114516*/
114517static int openDatabase(
114518  const char *zFilename, /* Database filename UTF-8 encoded */
114519  sqlite3 **ppDb,        /* OUT: Returned database handle */
114520  unsigned int flags,    /* Operational flags */
114521  const char *zVfs       /* Name of the VFS to use */
114522){
114523  sqlite3 *db;                    /* Store allocated handle here */
114524  int rc;                         /* Return code */
114525  int isThreadsafe;               /* True for threadsafe connections */
114526  char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
114527  char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
114528
114529  *ppDb = 0;
114530#ifndef SQLITE_OMIT_AUTOINIT
114531  rc = sqlite3_initialize();
114532  if( rc ) return rc;
114533#endif
114534
114535  /* Only allow sensible combinations of bits in the flags argument.
114536  ** Throw an error if any non-sense combination is used.  If we
114537  ** do not block illegal combinations here, it could trigger
114538  ** assert() statements in deeper layers.  Sensible combinations
114539  ** are:
114540  **
114541  **  1:  SQLITE_OPEN_READONLY
114542  **  2:  SQLITE_OPEN_READWRITE
114543  **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
114544  */
114545  assert( SQLITE_OPEN_READONLY  == 0x01 );
114546  assert( SQLITE_OPEN_READWRITE == 0x02 );
114547  assert( SQLITE_OPEN_CREATE    == 0x04 );
114548  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
114549  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
114550  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
114551  if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
114552
114553  if( sqlite3GlobalConfig.bCoreMutex==0 ){
114554    isThreadsafe = 0;
114555  }else if( flags & SQLITE_OPEN_NOMUTEX ){
114556    isThreadsafe = 0;
114557  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
114558    isThreadsafe = 1;
114559  }else{
114560    isThreadsafe = sqlite3GlobalConfig.bFullMutex;
114561  }
114562  if( flags & SQLITE_OPEN_PRIVATECACHE ){
114563    flags &= ~SQLITE_OPEN_SHAREDCACHE;
114564  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
114565    flags |= SQLITE_OPEN_SHAREDCACHE;
114566  }
114567
114568  /* Remove harmful bits from the flags parameter
114569  **
114570  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
114571  ** dealt with in the previous code block.  Besides these, the only
114572  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
114573  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
114574  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
114575  ** off all other flags.
114576  */
114577  flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
114578               SQLITE_OPEN_EXCLUSIVE |
114579               SQLITE_OPEN_MAIN_DB |
114580               SQLITE_OPEN_TEMP_DB |
114581               SQLITE_OPEN_TRANSIENT_DB |
114582               SQLITE_OPEN_MAIN_JOURNAL |
114583               SQLITE_OPEN_TEMP_JOURNAL |
114584               SQLITE_OPEN_SUBJOURNAL |
114585               SQLITE_OPEN_MASTER_JOURNAL |
114586               SQLITE_OPEN_NOMUTEX |
114587               SQLITE_OPEN_FULLMUTEX |
114588               SQLITE_OPEN_WAL
114589             );
114590
114591  /* Allocate the sqlite data structure */
114592  db = sqlite3MallocZero( sizeof(sqlite3) );
114593  if( db==0 ) goto opendb_out;
114594  if( isThreadsafe ){
114595    db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
114596    if( db->mutex==0 ){
114597      sqlite3_free(db);
114598      db = 0;
114599      goto opendb_out;
114600    }
114601  }
114602  sqlite3_mutex_enter(db->mutex);
114603  db->errMask = 0xff;
114604  db->nDb = 2;
114605  db->magic = SQLITE_MAGIC_BUSY;
114606  db->aDb = db->aDbStatic;
114607
114608  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
114609  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
114610  db->autoCommit = 1;
114611  db->nextAutovac = -1;
114612  db->nextPagesize = 0;
114613  db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
114614#if SQLITE_DEFAULT_FILE_FORMAT<4
114615                 | SQLITE_LegacyFileFmt
114616#endif
114617#ifdef SQLITE_ENABLE_LOAD_EXTENSION
114618                 | SQLITE_LoadExtension
114619#endif
114620#if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
114621                 | SQLITE_RecTriggers
114622#endif
114623#if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
114624                 | SQLITE_ForeignKeys
114625#endif
114626      ;
114627  sqlite3HashInit(&db->aCollSeq);
114628#ifndef SQLITE_OMIT_VIRTUALTABLE
114629  sqlite3HashInit(&db->aModule);
114630#endif
114631
114632  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
114633  ** and UTF-16, so add a version for each to avoid any unnecessary
114634  ** conversions. The only error that can occur here is a malloc() failure.
114635  */
114636  createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
114637  createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
114638  createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
114639  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
114640  if( db->mallocFailed ){
114641    goto opendb_out;
114642  }
114643  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
114644  assert( db->pDfltColl!=0 );
114645
114646  /* Also add a UTF-8 case-insensitive collation sequence. */
114647  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
114648
114649  /* Parse the filename/URI argument. */
114650  db->openFlags = flags;
114651  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
114652  if( rc!=SQLITE_OK ){
114653    if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
114654    sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
114655    sqlite3_free(zErrMsg);
114656    goto opendb_out;
114657  }
114658
114659  /* Open the backend database driver */
114660  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
114661                        flags | SQLITE_OPEN_MAIN_DB);
114662  if( rc!=SQLITE_OK ){
114663    if( rc==SQLITE_IOERR_NOMEM ){
114664      rc = SQLITE_NOMEM;
114665    }
114666    sqlite3Error(db, rc, 0);
114667    goto opendb_out;
114668  }
114669  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
114670  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
114671
114672
114673  /* The default safety_level for the main database is 'full'; for the temp
114674  ** database it is 'NONE'. This matches the pager layer defaults.
114675  */
114676  db->aDb[0].zName = "main";
114677  db->aDb[0].safety_level = 3;
114678  db->aDb[1].zName = "temp";
114679  db->aDb[1].safety_level = 1;
114680
114681  db->magic = SQLITE_MAGIC_OPEN;
114682  if( db->mallocFailed ){
114683    goto opendb_out;
114684  }
114685
114686  /* Register all built-in functions, but do not attempt to read the
114687  ** database schema yet. This is delayed until the first time the database
114688  ** is accessed.
114689  */
114690  sqlite3Error(db, SQLITE_OK, 0);
114691  sqlite3RegisterBuiltinFunctions(db);
114692
114693  /* Load automatic extensions - extensions that have been registered
114694  ** using the sqlite3_automatic_extension() API.
114695  */
114696  rc = sqlite3_errcode(db);
114697  if( rc==SQLITE_OK ){
114698    sqlite3AutoLoadExtensions(db);
114699    rc = sqlite3_errcode(db);
114700    if( rc!=SQLITE_OK ){
114701      goto opendb_out;
114702    }
114703  }
114704
114705#ifdef SQLITE_ENABLE_FTS1
114706  if( !db->mallocFailed ){
114707    extern int sqlite3Fts1Init(sqlite3*);
114708    rc = sqlite3Fts1Init(db);
114709  }
114710#endif
114711
114712#ifdef SQLITE_ENABLE_FTS2
114713  if( !db->mallocFailed && rc==SQLITE_OK ){
114714    extern int sqlite3Fts2Init(sqlite3*);
114715    rc = sqlite3Fts2Init(db);
114716  }
114717#endif
114718
114719#ifdef SQLITE_ENABLE_FTS3
114720  if( !db->mallocFailed && rc==SQLITE_OK ){
114721    rc = sqlite3Fts3Init(db);
114722  }
114723#endif
114724
114725#ifdef SQLITE_ENABLE_ICU
114726  if( !db->mallocFailed && rc==SQLITE_OK ){
114727    rc = sqlite3IcuInit(db);
114728  }
114729#endif
114730
114731#ifdef SQLITE_ENABLE_RTREE
114732  if( !db->mallocFailed && rc==SQLITE_OK){
114733    rc = sqlite3RtreeInit(db);
114734  }
114735#endif
114736
114737  sqlite3Error(db, rc, 0);
114738
114739  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
114740  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
114741  ** mode.  Doing nothing at all also makes NORMAL the default.
114742  */
114743#ifdef SQLITE_DEFAULT_LOCKING_MODE
114744  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
114745  sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
114746                          SQLITE_DEFAULT_LOCKING_MODE);
114747#endif
114748
114749  /* Enable the lookaside-malloc subsystem */
114750  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
114751                        sqlite3GlobalConfig.nLookaside);
114752
114753  sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
114754
114755opendb_out:
114756  sqlite3_free(zOpen);
114757  if( db ){
114758    assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
114759    sqlite3_mutex_leave(db->mutex);
114760  }
114761  rc = sqlite3_errcode(db);
114762  assert( db!=0 || rc==SQLITE_NOMEM );
114763  if( rc==SQLITE_NOMEM ){
114764    sqlite3_close(db);
114765    db = 0;
114766  }else if( rc!=SQLITE_OK ){
114767    db->magic = SQLITE_MAGIC_SICK;
114768  }
114769  *ppDb = db;
114770  return sqlite3ApiExit(0, rc);
114771}
114772
114773/*
114774** Open a new database handle.
114775*/
114776SQLITE_API int sqlite3_open(
114777  const char *zFilename,
114778  sqlite3 **ppDb
114779){
114780  return openDatabase(zFilename, ppDb,
114781                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
114782}
114783SQLITE_API int sqlite3_open_v2(
114784  const char *filename,   /* Database filename (UTF-8) */
114785  sqlite3 **ppDb,         /* OUT: SQLite db handle */
114786  int flags,              /* Flags */
114787  const char *zVfs        /* Name of VFS module to use */
114788){
114789  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
114790}
114791
114792#ifndef SQLITE_OMIT_UTF16
114793/*
114794** Open a new database handle.
114795*/
114796SQLITE_API int sqlite3_open16(
114797  const void *zFilename,
114798  sqlite3 **ppDb
114799){
114800  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
114801  sqlite3_value *pVal;
114802  int rc;
114803
114804  assert( zFilename );
114805  assert( ppDb );
114806  *ppDb = 0;
114807#ifndef SQLITE_OMIT_AUTOINIT
114808  rc = sqlite3_initialize();
114809  if( rc ) return rc;
114810#endif
114811  pVal = sqlite3ValueNew(0);
114812  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
114813  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
114814  if( zFilename8 ){
114815    rc = openDatabase(zFilename8, ppDb,
114816                      SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
114817    assert( *ppDb || rc==SQLITE_NOMEM );
114818    if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
114819      ENC(*ppDb) = SQLITE_UTF16NATIVE;
114820    }
114821  }else{
114822    rc = SQLITE_NOMEM;
114823  }
114824  sqlite3ValueFree(pVal);
114825
114826  return sqlite3ApiExit(0, rc);
114827}
114828#endif /* SQLITE_OMIT_UTF16 */
114829
114830/*
114831** Register a new collation sequence with the database handle db.
114832*/
114833SQLITE_API int sqlite3_create_collation(
114834  sqlite3* db,
114835  const char *zName,
114836  int enc,
114837  void* pCtx,
114838  int(*xCompare)(void*,int,const void*,int,const void*)
114839){
114840  int rc;
114841  sqlite3_mutex_enter(db->mutex);
114842  assert( !db->mallocFailed );
114843  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
114844  rc = sqlite3ApiExit(db, rc);
114845  sqlite3_mutex_leave(db->mutex);
114846  return rc;
114847}
114848
114849/*
114850** Register a new collation sequence with the database handle db.
114851*/
114852SQLITE_API int sqlite3_create_collation_v2(
114853  sqlite3* db,
114854  const char *zName,
114855  int enc,
114856  void* pCtx,
114857  int(*xCompare)(void*,int,const void*,int,const void*),
114858  void(*xDel)(void*)
114859){
114860  int rc;
114861  sqlite3_mutex_enter(db->mutex);
114862  assert( !db->mallocFailed );
114863  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
114864  rc = sqlite3ApiExit(db, rc);
114865  sqlite3_mutex_leave(db->mutex);
114866  return rc;
114867}
114868
114869#ifndef SQLITE_OMIT_UTF16
114870/*
114871** Register a new collation sequence with the database handle db.
114872*/
114873SQLITE_API int sqlite3_create_collation16(
114874  sqlite3* db,
114875  const void *zName,
114876  int enc,
114877  void* pCtx,
114878  int(*xCompare)(void*,int,const void*,int,const void*)
114879){
114880  int rc = SQLITE_OK;
114881  char *zName8;
114882  sqlite3_mutex_enter(db->mutex);
114883  assert( !db->mallocFailed );
114884  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
114885  if( zName8 ){
114886    rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
114887    sqlite3DbFree(db, zName8);
114888  }
114889  rc = sqlite3ApiExit(db, rc);
114890  sqlite3_mutex_leave(db->mutex);
114891  return rc;
114892}
114893#endif /* SQLITE_OMIT_UTF16 */
114894
114895/*
114896** Register a collation sequence factory callback with the database handle
114897** db. Replace any previously installed collation sequence factory.
114898*/
114899SQLITE_API int sqlite3_collation_needed(
114900  sqlite3 *db,
114901  void *pCollNeededArg,
114902  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
114903){
114904  sqlite3_mutex_enter(db->mutex);
114905  db->xCollNeeded = xCollNeeded;
114906  db->xCollNeeded16 = 0;
114907  db->pCollNeededArg = pCollNeededArg;
114908  sqlite3_mutex_leave(db->mutex);
114909  return SQLITE_OK;
114910}
114911
114912#ifndef SQLITE_OMIT_UTF16
114913/*
114914** Register a collation sequence factory callback with the database handle
114915** db. Replace any previously installed collation sequence factory.
114916*/
114917SQLITE_API int sqlite3_collation_needed16(
114918  sqlite3 *db,
114919  void *pCollNeededArg,
114920  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
114921){
114922  sqlite3_mutex_enter(db->mutex);
114923  db->xCollNeeded = 0;
114924  db->xCollNeeded16 = xCollNeeded16;
114925  db->pCollNeededArg = pCollNeededArg;
114926  sqlite3_mutex_leave(db->mutex);
114927  return SQLITE_OK;
114928}
114929#endif /* SQLITE_OMIT_UTF16 */
114930
114931#ifndef SQLITE_OMIT_DEPRECATED
114932/*
114933** This function is now an anachronism. It used to be used to recover from a
114934** malloc() failure, but SQLite now does this automatically.
114935*/
114936SQLITE_API int sqlite3_global_recover(void){
114937  return SQLITE_OK;
114938}
114939#endif
114940
114941/*
114942** Test to see whether or not the database connection is in autocommit
114943** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
114944** by default.  Autocommit is disabled by a BEGIN statement and reenabled
114945** by the next COMMIT or ROLLBACK.
114946**
114947******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
114948*/
114949SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
114950  return db->autoCommit;
114951}
114952
114953/*
114954** The following routines are subtitutes for constants SQLITE_CORRUPT,
114955** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
114956** constants.  They server two purposes:
114957**
114958**   1.  Serve as a convenient place to set a breakpoint in a debugger
114959**       to detect when version error conditions occurs.
114960**
114961**   2.  Invoke sqlite3_log() to provide the source code location where
114962**       a low-level error is first detected.
114963*/
114964SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
114965  testcase( sqlite3GlobalConfig.xLog!=0 );
114966  sqlite3_log(SQLITE_CORRUPT,
114967              "database corruption at line %d of [%.10s]",
114968              lineno, 20+sqlite3_sourceid());
114969  return SQLITE_CORRUPT;
114970}
114971SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
114972  testcase( sqlite3GlobalConfig.xLog!=0 );
114973  sqlite3_log(SQLITE_MISUSE,
114974              "misuse at line %d of [%.10s]",
114975              lineno, 20+sqlite3_sourceid());
114976  return SQLITE_MISUSE;
114977}
114978SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
114979  testcase( sqlite3GlobalConfig.xLog!=0 );
114980  sqlite3_log(SQLITE_CANTOPEN,
114981              "cannot open file at line %d of [%.10s]",
114982              lineno, 20+sqlite3_sourceid());
114983  return SQLITE_CANTOPEN;
114984}
114985
114986
114987#ifndef SQLITE_OMIT_DEPRECATED
114988/*
114989** This is a convenience routine that makes sure that all thread-specific
114990** data for this thread has been deallocated.
114991**
114992** SQLite no longer uses thread-specific data so this routine is now a
114993** no-op.  It is retained for historical compatibility.
114994*/
114995SQLITE_API void sqlite3_thread_cleanup(void){
114996}
114997#endif
114998
114999/*
115000** Return meta information about a specific column of a database table.
115001** See comment in sqlite3.h (sqlite.h.in) for details.
115002*/
115003#ifdef SQLITE_ENABLE_COLUMN_METADATA
115004SQLITE_API int sqlite3_table_column_metadata(
115005  sqlite3 *db,                /* Connection handle */
115006  const char *zDbName,        /* Database name or NULL */
115007  const char *zTableName,     /* Table name */
115008  const char *zColumnName,    /* Column name */
115009  char const **pzDataType,    /* OUTPUT: Declared data type */
115010  char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
115011  int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
115012  int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
115013  int *pAutoinc               /* OUTPUT: True if column is auto-increment */
115014){
115015  int rc;
115016  char *zErrMsg = 0;
115017  Table *pTab = 0;
115018  Column *pCol = 0;
115019  int iCol;
115020
115021  char const *zDataType = 0;
115022  char const *zCollSeq = 0;
115023  int notnull = 0;
115024  int primarykey = 0;
115025  int autoinc = 0;
115026
115027  /* Ensure the database schema has been loaded */
115028  sqlite3_mutex_enter(db->mutex);
115029  sqlite3BtreeEnterAll(db);
115030  rc = sqlite3Init(db, &zErrMsg);
115031  if( SQLITE_OK!=rc ){
115032    goto error_out;
115033  }
115034
115035  /* Locate the table in question */
115036  pTab = sqlite3FindTable(db, zTableName, zDbName);
115037  if( !pTab || pTab->pSelect ){
115038    pTab = 0;
115039    goto error_out;
115040  }
115041
115042  /* Find the column for which info is requested */
115043  if( sqlite3IsRowid(zColumnName) ){
115044    iCol = pTab->iPKey;
115045    if( iCol>=0 ){
115046      pCol = &pTab->aCol[iCol];
115047    }
115048  }else{
115049    for(iCol=0; iCol<pTab->nCol; iCol++){
115050      pCol = &pTab->aCol[iCol];
115051      if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
115052        break;
115053      }
115054    }
115055    if( iCol==pTab->nCol ){
115056      pTab = 0;
115057      goto error_out;
115058    }
115059  }
115060
115061  /* The following block stores the meta information that will be returned
115062  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
115063  ** and autoinc. At this point there are two possibilities:
115064  **
115065  **     1. The specified column name was rowid", "oid" or "_rowid_"
115066  **        and there is no explicitly declared IPK column.
115067  **
115068  **     2. The table is not a view and the column name identified an
115069  **        explicitly declared column. Copy meta information from *pCol.
115070  */
115071  if( pCol ){
115072    zDataType = pCol->zType;
115073    zCollSeq = pCol->zColl;
115074    notnull = pCol->notNull!=0;
115075    primarykey  = pCol->isPrimKey!=0;
115076    autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
115077  }else{
115078    zDataType = "INTEGER";
115079    primarykey = 1;
115080  }
115081  if( !zCollSeq ){
115082    zCollSeq = "BINARY";
115083  }
115084
115085error_out:
115086  sqlite3BtreeLeaveAll(db);
115087
115088  /* Whether the function call succeeded or failed, set the output parameters
115089  ** to whatever their local counterparts contain. If an error did occur,
115090  ** this has the effect of zeroing all output parameters.
115091  */
115092  if( pzDataType ) *pzDataType = zDataType;
115093  if( pzCollSeq ) *pzCollSeq = zCollSeq;
115094  if( pNotNull ) *pNotNull = notnull;
115095  if( pPrimaryKey ) *pPrimaryKey = primarykey;
115096  if( pAutoinc ) *pAutoinc = autoinc;
115097
115098  if( SQLITE_OK==rc && !pTab ){
115099    sqlite3DbFree(db, zErrMsg);
115100    zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
115101        zColumnName);
115102    rc = SQLITE_ERROR;
115103  }
115104  sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
115105  sqlite3DbFree(db, zErrMsg);
115106  rc = sqlite3ApiExit(db, rc);
115107  sqlite3_mutex_leave(db->mutex);
115108  return rc;
115109}
115110#endif
115111
115112/*
115113** Sleep for a little while.  Return the amount of time slept.
115114*/
115115SQLITE_API int sqlite3_sleep(int ms){
115116  sqlite3_vfs *pVfs;
115117  int rc;
115118  pVfs = sqlite3_vfs_find(0);
115119  if( pVfs==0 ) return 0;
115120
115121  /* This function works in milliseconds, but the underlying OsSleep()
115122  ** API uses microseconds. Hence the 1000's.
115123  */
115124  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
115125  return rc;
115126}
115127
115128/*
115129** Enable or disable the extended result codes.
115130*/
115131SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
115132  sqlite3_mutex_enter(db->mutex);
115133  db->errMask = onoff ? 0xffffffff : 0xff;
115134  sqlite3_mutex_leave(db->mutex);
115135  return SQLITE_OK;
115136}
115137
115138/*
115139** Invoke the xFileControl method on a particular database.
115140*/
115141SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
115142  int rc = SQLITE_ERROR;
115143  Btree *pBtree;
115144
115145  sqlite3_mutex_enter(db->mutex);
115146  pBtree = sqlite3DbNameToBtree(db, zDbName);
115147  if( pBtree ){
115148    Pager *pPager;
115149    sqlite3_file *fd;
115150    sqlite3BtreeEnter(pBtree);
115151    pPager = sqlite3BtreePager(pBtree);
115152    assert( pPager!=0 );
115153    fd = sqlite3PagerFile(pPager);
115154    assert( fd!=0 );
115155    if( op==SQLITE_FCNTL_FILE_POINTER ){
115156      *(sqlite3_file**)pArg = fd;
115157      rc = SQLITE_OK;
115158    }else if( fd->pMethods ){
115159      rc = sqlite3OsFileControl(fd, op, pArg);
115160    }else{
115161      rc = SQLITE_NOTFOUND;
115162    }
115163    sqlite3BtreeLeave(pBtree);
115164  }
115165  sqlite3_mutex_leave(db->mutex);
115166  return rc;
115167}
115168
115169/*
115170** Interface to the testing logic.
115171*/
115172SQLITE_API int sqlite3_test_control(int op, ...){
115173  int rc = 0;
115174#ifndef SQLITE_OMIT_BUILTIN_TEST
115175  va_list ap;
115176  va_start(ap, op);
115177  switch( op ){
115178
115179    /*
115180    ** Save the current state of the PRNG.
115181    */
115182    case SQLITE_TESTCTRL_PRNG_SAVE: {
115183      sqlite3PrngSaveState();
115184      break;
115185    }
115186
115187    /*
115188    ** Restore the state of the PRNG to the last state saved using
115189    ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
115190    ** this verb acts like PRNG_RESET.
115191    */
115192    case SQLITE_TESTCTRL_PRNG_RESTORE: {
115193      sqlite3PrngRestoreState();
115194      break;
115195    }
115196
115197    /*
115198    ** Reset the PRNG back to its uninitialized state.  The next call
115199    ** to sqlite3_randomness() will reseed the PRNG using a single call
115200    ** to the xRandomness method of the default VFS.
115201    */
115202    case SQLITE_TESTCTRL_PRNG_RESET: {
115203      sqlite3PrngResetState();
115204      break;
115205    }
115206
115207    /*
115208    **  sqlite3_test_control(BITVEC_TEST, size, program)
115209    **
115210    ** Run a test against a Bitvec object of size.  The program argument
115211    ** is an array of integers that defines the test.  Return -1 on a
115212    ** memory allocation error, 0 on success, or non-zero for an error.
115213    ** See the sqlite3BitvecBuiltinTest() for additional information.
115214    */
115215    case SQLITE_TESTCTRL_BITVEC_TEST: {
115216      int sz = va_arg(ap, int);
115217      int *aProg = va_arg(ap, int*);
115218      rc = sqlite3BitvecBuiltinTest(sz, aProg);
115219      break;
115220    }
115221
115222    /*
115223    **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
115224    **
115225    ** Register hooks to call to indicate which malloc() failures
115226    ** are benign.
115227    */
115228    case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
115229      typedef void (*void_function)(void);
115230      void_function xBenignBegin;
115231      void_function xBenignEnd;
115232      xBenignBegin = va_arg(ap, void_function);
115233      xBenignEnd = va_arg(ap, void_function);
115234      sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
115235      break;
115236    }
115237
115238    /*
115239    **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
115240    **
115241    ** Set the PENDING byte to the value in the argument, if X>0.
115242    ** Make no changes if X==0.  Return the value of the pending byte
115243    ** as it existing before this routine was called.
115244    **
115245    ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
115246    ** an incompatible database file format.  Changing the PENDING byte
115247    ** while any database connection is open results in undefined and
115248    ** dileterious behavior.
115249    */
115250    case SQLITE_TESTCTRL_PENDING_BYTE: {
115251      rc = PENDING_BYTE;
115252#ifndef SQLITE_OMIT_WSD
115253      {
115254        unsigned int newVal = va_arg(ap, unsigned int);
115255        if( newVal ) sqlite3PendingByte = newVal;
115256      }
115257#endif
115258      break;
115259    }
115260
115261    /*
115262    **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
115263    **
115264    ** This action provides a run-time test to see whether or not
115265    ** assert() was enabled at compile-time.  If X is true and assert()
115266    ** is enabled, then the return value is true.  If X is true and
115267    ** assert() is disabled, then the return value is zero.  If X is
115268    ** false and assert() is enabled, then the assertion fires and the
115269    ** process aborts.  If X is false and assert() is disabled, then the
115270    ** return value is zero.
115271    */
115272    case SQLITE_TESTCTRL_ASSERT: {
115273      volatile int x = 0;
115274      assert( (x = va_arg(ap,int))!=0 );
115275      rc = x;
115276      break;
115277    }
115278
115279
115280    /*
115281    **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
115282    **
115283    ** This action provides a run-time test to see how the ALWAYS and
115284    ** NEVER macros were defined at compile-time.
115285    **
115286    ** The return value is ALWAYS(X).
115287    **
115288    ** The recommended test is X==2.  If the return value is 2, that means
115289    ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
115290    ** default setting.  If the return value is 1, then ALWAYS() is either
115291    ** hard-coded to true or else it asserts if its argument is false.
115292    ** The first behavior (hard-coded to true) is the case if
115293    ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
115294    ** behavior (assert if the argument to ALWAYS() is false) is the case if
115295    ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
115296    **
115297    ** The run-time test procedure might look something like this:
115298    **
115299    **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
115300    **      // ALWAYS() and NEVER() are no-op pass-through macros
115301    **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
115302    **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
115303    **    }else{
115304    **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
115305    **    }
115306    */
115307    case SQLITE_TESTCTRL_ALWAYS: {
115308      int x = va_arg(ap,int);
115309      rc = ALWAYS(x);
115310      break;
115311    }
115312
115313    /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
115314    **
115315    ** Set the nReserve size to N for the main database on the database
115316    ** connection db.
115317    */
115318    case SQLITE_TESTCTRL_RESERVE: {
115319      sqlite3 *db = va_arg(ap, sqlite3*);
115320      int x = va_arg(ap,int);
115321      sqlite3_mutex_enter(db->mutex);
115322      sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
115323      sqlite3_mutex_leave(db->mutex);
115324      break;
115325    }
115326
115327    /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
115328    **
115329    ** Enable or disable various optimizations for testing purposes.  The
115330    ** argument N is a bitmask of optimizations to be disabled.  For normal
115331    ** operation N should be 0.  The idea is that a test program (like the
115332    ** SQL Logic Test or SLT test module) can run the same SQL multiple times
115333    ** with various optimizations disabled to verify that the same answer
115334    ** is obtained in every case.
115335    */
115336    case SQLITE_TESTCTRL_OPTIMIZATIONS: {
115337      sqlite3 *db = va_arg(ap, sqlite3*);
115338      int x = va_arg(ap,int);
115339      db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
115340      break;
115341    }
115342
115343#ifdef SQLITE_N_KEYWORD
115344    /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
115345    **
115346    ** If zWord is a keyword recognized by the parser, then return the
115347    ** number of keywords.  Or if zWord is not a keyword, return 0.
115348    **
115349    ** This test feature is only available in the amalgamation since
115350    ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
115351    ** is built using separate source files.
115352    */
115353    case SQLITE_TESTCTRL_ISKEYWORD: {
115354      const char *zWord = va_arg(ap, const char*);
115355      int n = sqlite3Strlen30(zWord);
115356      rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
115357      break;
115358    }
115359#endif
115360
115361    /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
115362    **
115363    ** Pass pFree into sqlite3ScratchFree().
115364    ** If sz>0 then allocate a scratch buffer into pNew.
115365    */
115366    case SQLITE_TESTCTRL_SCRATCHMALLOC: {
115367      void *pFree, **ppNew;
115368      int sz;
115369      sz = va_arg(ap, int);
115370      ppNew = va_arg(ap, void**);
115371      pFree = va_arg(ap, void*);
115372      if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
115373      sqlite3ScratchFree(pFree);
115374      break;
115375    }
115376
115377    /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
115378    **
115379    ** If parameter onoff is non-zero, configure the wrappers so that all
115380    ** subsequent calls to localtime() and variants fail. If onoff is zero,
115381    ** undo this setting.
115382    */
115383    case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
115384      sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
115385      break;
115386    }
115387
115388#if defined(SQLITE_ENABLE_TREE_EXPLAIN)
115389    /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
115390    **                        sqlite3_stmt*,const char**);
115391    **
115392    ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
115393    ** a string that describes the optimized parse tree.  This test-control
115394    ** returns a pointer to that string.
115395    */
115396    case SQLITE_TESTCTRL_EXPLAIN_STMT: {
115397      sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
115398      const char **pzRet = va_arg(ap, const char**);
115399      *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
115400      break;
115401    }
115402#endif
115403
115404  }
115405  va_end(ap);
115406#endif /* SQLITE_OMIT_BUILTIN_TEST */
115407  return rc;
115408}
115409
115410/*
115411** This is a utility routine, useful to VFS implementations, that checks
115412** to see if a database file was a URI that contained a specific query
115413** parameter, and if so obtains the value of the query parameter.
115414**
115415** The zFilename argument is the filename pointer passed into the xOpen()
115416** method of a VFS implementation.  The zParam argument is the name of the
115417** query parameter we seek.  This routine returns the value of the zParam
115418** parameter if it exists.  If the parameter does not exist, this routine
115419** returns a NULL pointer.
115420*/
115421SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
115422  if( zFilename==0 ) return 0;
115423  zFilename += sqlite3Strlen30(zFilename) + 1;
115424  while( zFilename[0] ){
115425    int x = strcmp(zFilename, zParam);
115426    zFilename += sqlite3Strlen30(zFilename) + 1;
115427    if( x==0 ) return zFilename;
115428    zFilename += sqlite3Strlen30(zFilename) + 1;
115429  }
115430  return 0;
115431}
115432
115433/*
115434** Return a boolean value for a query parameter.
115435*/
115436SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
115437  const char *z = sqlite3_uri_parameter(zFilename, zParam);
115438  bDflt = bDflt!=0;
115439  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
115440}
115441
115442/*
115443** Return a 64-bit integer value for a query parameter.
115444*/
115445SQLITE_API sqlite3_int64 sqlite3_uri_int64(
115446  const char *zFilename,    /* Filename as passed to xOpen */
115447  const char *zParam,       /* URI parameter sought */
115448  sqlite3_int64 bDflt       /* return if parameter is missing */
115449){
115450  const char *z = sqlite3_uri_parameter(zFilename, zParam);
115451  sqlite3_int64 v;
115452  if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
115453    bDflt = v;
115454  }
115455  return bDflt;
115456}
115457
115458/*
115459** Return the Btree pointer identified by zDbName.  Return NULL if not found.
115460*/
115461SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
115462  int i;
115463  for(i=0; i<db->nDb; i++){
115464    if( db->aDb[i].pBt
115465     && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
115466    ){
115467      return db->aDb[i].pBt;
115468    }
115469  }
115470  return 0;
115471}
115472
115473/*
115474** Return the filename of the database associated with a database
115475** connection.
115476*/
115477SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
115478  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
115479  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
115480}
115481
115482/*
115483** Return 1 if database is read-only or 0 if read/write.  Return -1 if
115484** no such database exists.
115485*/
115486SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
115487  Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
115488  return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
115489}
115490
115491/************** End of main.c ************************************************/
115492/************** Begin file notify.c ******************************************/
115493/*
115494** 2009 March 3
115495**
115496** The author disclaims copyright to this source code.  In place of
115497** a legal notice, here is a blessing:
115498**
115499**    May you do good and not evil.
115500**    May you find forgiveness for yourself and forgive others.
115501**    May you share freely, never taking more than you give.
115502**
115503*************************************************************************
115504**
115505** This file contains the implementation of the sqlite3_unlock_notify()
115506** API method and its associated functionality.
115507*/
115508
115509/* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
115510#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
115511
115512/*
115513** Public interfaces:
115514**
115515**   sqlite3ConnectionBlocked()
115516**   sqlite3ConnectionUnlocked()
115517**   sqlite3ConnectionClosed()
115518**   sqlite3_unlock_notify()
115519*/
115520
115521#define assertMutexHeld() \
115522  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
115523
115524/*
115525** Head of a linked list of all sqlite3 objects created by this process
115526** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
115527** is not NULL. This variable may only accessed while the STATIC_MASTER
115528** mutex is held.
115529*/
115530static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
115531
115532#ifndef NDEBUG
115533/*
115534** This function is a complex assert() that verifies the following
115535** properties of the blocked connections list:
115536**
115537**   1) Each entry in the list has a non-NULL value for either
115538**      pUnlockConnection or pBlockingConnection, or both.
115539**
115540**   2) All entries in the list that share a common value for
115541**      xUnlockNotify are grouped together.
115542**
115543**   3) If the argument db is not NULL, then none of the entries in the
115544**      blocked connections list have pUnlockConnection or pBlockingConnection
115545**      set to db. This is used when closing connection db.
115546*/
115547static void checkListProperties(sqlite3 *db){
115548  sqlite3 *p;
115549  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
115550    int seen = 0;
115551    sqlite3 *p2;
115552
115553    /* Verify property (1) */
115554    assert( p->pUnlockConnection || p->pBlockingConnection );
115555
115556    /* Verify property (2) */
115557    for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
115558      if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
115559      assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
115560      assert( db==0 || p->pUnlockConnection!=db );
115561      assert( db==0 || p->pBlockingConnection!=db );
115562    }
115563  }
115564}
115565#else
115566# define checkListProperties(x)
115567#endif
115568
115569/*
115570** Remove connection db from the blocked connections list. If connection
115571** db is not currently a part of the list, this function is a no-op.
115572*/
115573static void removeFromBlockedList(sqlite3 *db){
115574  sqlite3 **pp;
115575  assertMutexHeld();
115576  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
115577    if( *pp==db ){
115578      *pp = (*pp)->pNextBlocked;
115579      break;
115580    }
115581  }
115582}
115583
115584/*
115585** Add connection db to the blocked connections list. It is assumed
115586** that it is not already a part of the list.
115587*/
115588static void addToBlockedList(sqlite3 *db){
115589  sqlite3 **pp;
115590  assertMutexHeld();
115591  for(
115592    pp=&sqlite3BlockedList;
115593    *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
115594    pp=&(*pp)->pNextBlocked
115595  );
115596  db->pNextBlocked = *pp;
115597  *pp = db;
115598}
115599
115600/*
115601** Obtain the STATIC_MASTER mutex.
115602*/
115603static void enterMutex(void){
115604  sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
115605  checkListProperties(0);
115606}
115607
115608/*
115609** Release the STATIC_MASTER mutex.
115610*/
115611static void leaveMutex(void){
115612  assertMutexHeld();
115613  checkListProperties(0);
115614  sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
115615}
115616
115617/*
115618** Register an unlock-notify callback.
115619**
115620** This is called after connection "db" has attempted some operation
115621** but has received an SQLITE_LOCKED error because another connection
115622** (call it pOther) in the same process was busy using the same shared
115623** cache.  pOther is found by looking at db->pBlockingConnection.
115624**
115625** If there is no blocking connection, the callback is invoked immediately,
115626** before this routine returns.
115627**
115628** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
115629** a deadlock.
115630**
115631** Otherwise, make arrangements to invoke xNotify when pOther drops
115632** its locks.
115633**
115634** Each call to this routine overrides any prior callbacks registered
115635** on the same "db".  If xNotify==0 then any prior callbacks are immediately
115636** cancelled.
115637*/
115638SQLITE_API int sqlite3_unlock_notify(
115639  sqlite3 *db,
115640  void (*xNotify)(void **, int),
115641  void *pArg
115642){
115643  int rc = SQLITE_OK;
115644
115645  sqlite3_mutex_enter(db->mutex);
115646  enterMutex();
115647
115648  if( xNotify==0 ){
115649    removeFromBlockedList(db);
115650    db->pBlockingConnection = 0;
115651    db->pUnlockConnection = 0;
115652    db->xUnlockNotify = 0;
115653    db->pUnlockArg = 0;
115654  }else if( 0==db->pBlockingConnection ){
115655    /* The blocking transaction has been concluded. Or there never was a
115656    ** blocking transaction. In either case, invoke the notify callback
115657    ** immediately.
115658    */
115659    xNotify(&pArg, 1);
115660  }else{
115661    sqlite3 *p;
115662
115663    for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
115664    if( p ){
115665      rc = SQLITE_LOCKED;              /* Deadlock detected. */
115666    }else{
115667      db->pUnlockConnection = db->pBlockingConnection;
115668      db->xUnlockNotify = xNotify;
115669      db->pUnlockArg = pArg;
115670      removeFromBlockedList(db);
115671      addToBlockedList(db);
115672    }
115673  }
115674
115675  leaveMutex();
115676  assert( !db->mallocFailed );
115677  sqlite3Error(db, rc, (rc?"database is deadlocked":0));
115678  sqlite3_mutex_leave(db->mutex);
115679  return rc;
115680}
115681
115682/*
115683** This function is called while stepping or preparing a statement
115684** associated with connection db. The operation will return SQLITE_LOCKED
115685** to the user because it requires a lock that will not be available
115686** until connection pBlocker concludes its current transaction.
115687*/
115688SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
115689  enterMutex();
115690  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
115691    addToBlockedList(db);
115692  }
115693  db->pBlockingConnection = pBlocker;
115694  leaveMutex();
115695}
115696
115697/*
115698** This function is called when
115699** the transaction opened by database db has just finished. Locks held
115700** by database connection db have been released.
115701**
115702** This function loops through each entry in the blocked connections
115703** list and does the following:
115704**
115705**   1) If the sqlite3.pBlockingConnection member of a list entry is
115706**      set to db, then set pBlockingConnection=0.
115707**
115708**   2) If the sqlite3.pUnlockConnection member of a list entry is
115709**      set to db, then invoke the configured unlock-notify callback and
115710**      set pUnlockConnection=0.
115711**
115712**   3) If the two steps above mean that pBlockingConnection==0 and
115713**      pUnlockConnection==0, remove the entry from the blocked connections
115714**      list.
115715*/
115716SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
115717  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
115718  int nArg = 0;                            /* Number of entries in aArg[] */
115719  sqlite3 **pp;                            /* Iterator variable */
115720  void **aArg;               /* Arguments to the unlock callback */
115721  void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
115722  void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
115723
115724  aArg = aStatic;
115725  enterMutex();         /* Enter STATIC_MASTER mutex */
115726
115727  /* This loop runs once for each entry in the blocked-connections list. */
115728  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
115729    sqlite3 *p = *pp;
115730
115731    /* Step 1. */
115732    if( p->pBlockingConnection==db ){
115733      p->pBlockingConnection = 0;
115734    }
115735
115736    /* Step 2. */
115737    if( p->pUnlockConnection==db ){
115738      assert( p->xUnlockNotify );
115739      if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
115740        xUnlockNotify(aArg, nArg);
115741        nArg = 0;
115742      }
115743
115744      sqlite3BeginBenignMalloc();
115745      assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
115746      assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
115747      if( (!aDyn && nArg==(int)ArraySize(aStatic))
115748       || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
115749      ){
115750        /* The aArg[] array needs to grow. */
115751        void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
115752        if( pNew ){
115753          memcpy(pNew, aArg, nArg*sizeof(void *));
115754          sqlite3_free(aDyn);
115755          aDyn = aArg = pNew;
115756        }else{
115757          /* This occurs when the array of context pointers that need to
115758          ** be passed to the unlock-notify callback is larger than the
115759          ** aStatic[] array allocated on the stack and the attempt to
115760          ** allocate a larger array from the heap has failed.
115761          **
115762          ** This is a difficult situation to handle. Returning an error
115763          ** code to the caller is insufficient, as even if an error code
115764          ** is returned the transaction on connection db will still be
115765          ** closed and the unlock-notify callbacks on blocked connections
115766          ** will go unissued. This might cause the application to wait
115767          ** indefinitely for an unlock-notify callback that will never
115768          ** arrive.
115769          **
115770          ** Instead, invoke the unlock-notify callback with the context
115771          ** array already accumulated. We can then clear the array and
115772          ** begin accumulating any further context pointers without
115773          ** requiring any dynamic allocation. This is sub-optimal because
115774          ** it means that instead of one callback with a large array of
115775          ** context pointers the application will receive two or more
115776          ** callbacks with smaller arrays of context pointers, which will
115777          ** reduce the applications ability to prioritize multiple
115778          ** connections. But it is the best that can be done under the
115779          ** circumstances.
115780          */
115781          xUnlockNotify(aArg, nArg);
115782          nArg = 0;
115783        }
115784      }
115785      sqlite3EndBenignMalloc();
115786
115787      aArg[nArg++] = p->pUnlockArg;
115788      xUnlockNotify = p->xUnlockNotify;
115789      p->pUnlockConnection = 0;
115790      p->xUnlockNotify = 0;
115791      p->pUnlockArg = 0;
115792    }
115793
115794    /* Step 3. */
115795    if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
115796      /* Remove connection p from the blocked connections list. */
115797      *pp = p->pNextBlocked;
115798      p->pNextBlocked = 0;
115799    }else{
115800      pp = &p->pNextBlocked;
115801    }
115802  }
115803
115804  if( nArg!=0 ){
115805    xUnlockNotify(aArg, nArg);
115806  }
115807  sqlite3_free(aDyn);
115808  leaveMutex();         /* Leave STATIC_MASTER mutex */
115809}
115810
115811/*
115812** This is called when the database connection passed as an argument is
115813** being closed. The connection is removed from the blocked list.
115814*/
115815SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
115816  sqlite3ConnectionUnlocked(db);
115817  enterMutex();
115818  removeFromBlockedList(db);
115819  checkListProperties(db);
115820  leaveMutex();
115821}
115822#endif
115823
115824/************** End of notify.c **********************************************/
115825/************** Begin file fts3.c ********************************************/
115826/*
115827** 2006 Oct 10
115828**
115829** The author disclaims copyright to this source code.  In place of
115830** a legal notice, here is a blessing:
115831**
115832**    May you do good and not evil.
115833**    May you find forgiveness for yourself and forgive others.
115834**    May you share freely, never taking more than you give.
115835**
115836******************************************************************************
115837**
115838** This is an SQLite module implementing full-text search.
115839*/
115840
115841/*
115842** The code in this file is only compiled if:
115843**
115844**     * The FTS3 module is being built as an extension
115845**       (in which case SQLITE_CORE is not defined), or
115846**
115847**     * The FTS3 module is being built into the core of
115848**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
115849*/
115850
115851/* The full-text index is stored in a series of b+tree (-like)
115852** structures called segments which map terms to doclists.  The
115853** structures are like b+trees in layout, but are constructed from the
115854** bottom up in optimal fashion and are not updatable.  Since trees
115855** are built from the bottom up, things will be described from the
115856** bottom up.
115857**
115858**
115859**** Varints ****
115860** The basic unit of encoding is a variable-length integer called a
115861** varint.  We encode variable-length integers in little-endian order
115862** using seven bits * per byte as follows:
115863**
115864** KEY:
115865**         A = 0xxxxxxx    7 bits of data and one flag bit
115866**         B = 1xxxxxxx    7 bits of data and one flag bit
115867**
115868**  7 bits - A
115869** 14 bits - BA
115870** 21 bits - BBA
115871** and so on.
115872**
115873** This is similar in concept to how sqlite encodes "varints" but
115874** the encoding is not the same.  SQLite varints are big-endian
115875** are are limited to 9 bytes in length whereas FTS3 varints are
115876** little-endian and can be up to 10 bytes in length (in theory).
115877**
115878** Example encodings:
115879**
115880**     1:    0x01
115881**   127:    0x7f
115882**   128:    0x81 0x00
115883**
115884**
115885**** Document lists ****
115886** A doclist (document list) holds a docid-sorted list of hits for a
115887** given term.  Doclists hold docids and associated token positions.
115888** A docid is the unique integer identifier for a single document.
115889** A position is the index of a word within the document.  The first
115890** word of the document has a position of 0.
115891**
115892** FTS3 used to optionally store character offsets using a compile-time
115893** option.  But that functionality is no longer supported.
115894**
115895** A doclist is stored like this:
115896**
115897** array {
115898**   varint docid;
115899**   array {                (position list for column 0)
115900**     varint position;     (2 more than the delta from previous position)
115901**   }
115902**   array {
115903**     varint POS_COLUMN;   (marks start of position list for new column)
115904**     varint column;       (index of new column)
115905**     array {
115906**       varint position;   (2 more than the delta from previous position)
115907**     }
115908**   }
115909**   varint POS_END;        (marks end of positions for this document.
115910** }
115911**
115912** Here, array { X } means zero or more occurrences of X, adjacent in
115913** memory.  A "position" is an index of a token in the token stream
115914** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
115915** in the same logical place as the position element, and act as sentinals
115916** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
115917** The positions numbers are not stored literally but rather as two more
115918** than the difference from the prior position, or the just the position plus
115919** 2 for the first position.  Example:
115920**
115921**   label:       A B C D E  F  G H   I  J K
115922**   value:     123 5 9 1 1 14 35 0 234 72 0
115923**
115924** The 123 value is the first docid.  For column zero in this document
115925** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
115926** at D signals the start of a new column; the 1 at E indicates that the
115927** new column is column number 1.  There are two positions at 12 and 45
115928** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
115929** 234 at I is the next docid.  It has one position 72 (72-2) and then
115930** terminates with the 0 at K.
115931**
115932** A "position-list" is the list of positions for multiple columns for
115933** a single docid.  A "column-list" is the set of positions for a single
115934** column.  Hence, a position-list consists of one or more column-lists,
115935** a document record consists of a docid followed by a position-list and
115936** a doclist consists of one or more document records.
115937**
115938** A bare doclist omits the position information, becoming an
115939** array of varint-encoded docids.
115940**
115941**** Segment leaf nodes ****
115942** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
115943** nodes are written using LeafWriter, and read using LeafReader (to
115944** iterate through a single leaf node's data) and LeavesReader (to
115945** iterate through a segment's entire leaf layer).  Leaf nodes have
115946** the format:
115947**
115948** varint iHeight;             (height from leaf level, always 0)
115949** varint nTerm;               (length of first term)
115950** char pTerm[nTerm];          (content of first term)
115951** varint nDoclist;            (length of term's associated doclist)
115952** char pDoclist[nDoclist];    (content of doclist)
115953** array {
115954**                             (further terms are delta-encoded)
115955**   varint nPrefix;           (length of prefix shared with previous term)
115956**   varint nSuffix;           (length of unshared suffix)
115957**   char pTermSuffix[nSuffix];(unshared suffix of next term)
115958**   varint nDoclist;          (length of term's associated doclist)
115959**   char pDoclist[nDoclist];  (content of doclist)
115960** }
115961**
115962** Here, array { X } means zero or more occurrences of X, adjacent in
115963** memory.
115964**
115965** Leaf nodes are broken into blocks which are stored contiguously in
115966** the %_segments table in sorted order.  This means that when the end
115967** of a node is reached, the next term is in the node with the next
115968** greater node id.
115969**
115970** New data is spilled to a new leaf node when the current node
115971** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
115972** larger than STANDALONE_MIN (default 1024) is placed in a standalone
115973** node (a leaf node with a single term and doclist).  The goal of
115974** these settings is to pack together groups of small doclists while
115975** making it efficient to directly access large doclists.  The
115976** assumption is that large doclists represent terms which are more
115977** likely to be query targets.
115978**
115979** TODO(shess) It may be useful for blocking decisions to be more
115980** dynamic.  For instance, it may make more sense to have a 2.5k leaf
115981** node rather than splitting into 2k and .5k nodes.  My intuition is
115982** that this might extend through 2x or 4x the pagesize.
115983**
115984**
115985**** Segment interior nodes ****
115986** Segment interior nodes store blockids for subtree nodes and terms
115987** to describe what data is stored by the each subtree.  Interior
115988** nodes are written using InteriorWriter, and read using
115989** InteriorReader.  InteriorWriters are created as needed when
115990** SegmentWriter creates new leaf nodes, or when an interior node
115991** itself grows too big and must be split.  The format of interior
115992** nodes:
115993**
115994** varint iHeight;           (height from leaf level, always >0)
115995** varint iBlockid;          (block id of node's leftmost subtree)
115996** optional {
115997**   varint nTerm;           (length of first term)
115998**   char pTerm[nTerm];      (content of first term)
115999**   array {
116000**                                (further terms are delta-encoded)
116001**     varint nPrefix;            (length of shared prefix with previous term)
116002**     varint nSuffix;            (length of unshared suffix)
116003**     char pTermSuffix[nSuffix]; (unshared suffix of next term)
116004**   }
116005** }
116006**
116007** Here, optional { X } means an optional element, while array { X }
116008** means zero or more occurrences of X, adjacent in memory.
116009**
116010** An interior node encodes n terms separating n+1 subtrees.  The
116011** subtree blocks are contiguous, so only the first subtree's blockid
116012** is encoded.  The subtree at iBlockid will contain all terms less
116013** than the first term encoded (or all terms if no term is encoded).
116014** Otherwise, for terms greater than or equal to pTerm[i] but less
116015** than pTerm[i+1], the subtree for that term will be rooted at
116016** iBlockid+i.  Interior nodes only store enough term data to
116017** distinguish adjacent children (if the rightmost term of the left
116018** child is "something", and the leftmost term of the right child is
116019** "wicked", only "w" is stored).
116020**
116021** New data is spilled to a new interior node at the same height when
116022** the current node exceeds INTERIOR_MAX bytes (default 2048).
116023** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
116024** interior nodes and making the tree too skinny.  The interior nodes
116025** at a given height are naturally tracked by interior nodes at
116026** height+1, and so on.
116027**
116028**
116029**** Segment directory ****
116030** The segment directory in table %_segdir stores meta-information for
116031** merging and deleting segments, and also the root node of the
116032** segment's tree.
116033**
116034** The root node is the top node of the segment's tree after encoding
116035** the entire segment, restricted to ROOT_MAX bytes (default 1024).
116036** This could be either a leaf node or an interior node.  If the top
116037** node requires more than ROOT_MAX bytes, it is flushed to %_segments
116038** and a new root interior node is generated (which should always fit
116039** within ROOT_MAX because it only needs space for 2 varints, the
116040** height and the blockid of the previous root).
116041**
116042** The meta-information in the segment directory is:
116043**   level               - segment level (see below)
116044**   idx                 - index within level
116045**                       - (level,idx uniquely identify a segment)
116046**   start_block         - first leaf node
116047**   leaves_end_block    - last leaf node
116048**   end_block           - last block (including interior nodes)
116049**   root                - contents of root node
116050**
116051** If the root node is a leaf node, then start_block,
116052** leaves_end_block, and end_block are all 0.
116053**
116054**
116055**** Segment merging ****
116056** To amortize update costs, segments are grouped into levels and
116057** merged in batches.  Each increase in level represents exponentially
116058** more documents.
116059**
116060** New documents (actually, document updates) are tokenized and
116061** written individually (using LeafWriter) to a level 0 segment, with
116062** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
116063** level 0 segments are merged into a single level 1 segment.  Level 1
116064** is populated like level 0, and eventually MERGE_COUNT level 1
116065** segments are merged to a single level 2 segment (representing
116066** MERGE_COUNT^2 updates), and so on.
116067**
116068** A segment merge traverses all segments at a given level in
116069** parallel, performing a straightforward sorted merge.  Since segment
116070** leaf nodes are written in to the %_segments table in order, this
116071** merge traverses the underlying sqlite disk structures efficiently.
116072** After the merge, all segment blocks from the merged level are
116073** deleted.
116074**
116075** MERGE_COUNT controls how often we merge segments.  16 seems to be
116076** somewhat of a sweet spot for insertion performance.  32 and 64 show
116077** very similar performance numbers to 16 on insertion, though they're
116078** a tiny bit slower (perhaps due to more overhead in merge-time
116079** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
116080** 16, 2 about 66% slower than 16.
116081**
116082** At query time, high MERGE_COUNT increases the number of segments
116083** which need to be scanned and merged.  For instance, with 100k docs
116084** inserted:
116085**
116086**    MERGE_COUNT   segments
116087**       16           25
116088**        8           12
116089**        4           10
116090**        2            6
116091**
116092** This appears to have only a moderate impact on queries for very
116093** frequent terms (which are somewhat dominated by segment merge
116094** costs), and infrequent and non-existent terms still seem to be fast
116095** even with many segments.
116096**
116097** TODO(shess) That said, it would be nice to have a better query-side
116098** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
116099** optimizations to things like doclist merging will swing the sweet
116100** spot around.
116101**
116102**
116103**
116104**** Handling of deletions and updates ****
116105** Since we're using a segmented structure, with no docid-oriented
116106** index into the term index, we clearly cannot simply update the term
116107** index when a document is deleted or updated.  For deletions, we
116108** write an empty doclist (varint(docid) varint(POS_END)), for updates
116109** we simply write the new doclist.  Segment merges overwrite older
116110** data for a particular docid with newer data, so deletes or updates
116111** will eventually overtake the earlier data and knock it out.  The
116112** query logic likewise merges doclists so that newer data knocks out
116113** older data.
116114*/
116115
116116/************** Include fts3Int.h in the middle of fts3.c ********************/
116117/************** Begin file fts3Int.h *****************************************/
116118/*
116119** 2009 Nov 12
116120**
116121** The author disclaims copyright to this source code.  In place of
116122** a legal notice, here is a blessing:
116123**
116124**    May you do good and not evil.
116125**    May you find forgiveness for yourself and forgive others.
116126**    May you share freely, never taking more than you give.
116127**
116128******************************************************************************
116129**
116130*/
116131#ifndef _FTSINT_H
116132#define _FTSINT_H
116133
116134#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
116135# define NDEBUG 1
116136#endif
116137
116138/*
116139** FTS4 is really an extension for FTS3.  It is enabled using the
116140** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
116141** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
116142*/
116143#if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
116144# define SQLITE_ENABLE_FTS3
116145#endif
116146
116147#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116148
116149/* If not building as part of the core, include sqlite3ext.h. */
116150#ifndef SQLITE_CORE
116151SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
116152#endif
116153
116154/************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
116155/************** Begin file fts3_tokenizer.h **********************************/
116156/*
116157** 2006 July 10
116158**
116159** The author disclaims copyright to this source code.
116160**
116161*************************************************************************
116162** Defines the interface to tokenizers used by fulltext-search.  There
116163** are three basic components:
116164**
116165** sqlite3_tokenizer_module is a singleton defining the tokenizer
116166** interface functions.  This is essentially the class structure for
116167** tokenizers.
116168**
116169** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
116170** including customization information defined at creation time.
116171**
116172** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
116173** tokens from a particular input.
116174*/
116175#ifndef _FTS3_TOKENIZER_H_
116176#define _FTS3_TOKENIZER_H_
116177
116178/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
116179** If tokenizers are to be allowed to call sqlite3_*() functions, then
116180** we will need a way to register the API consistently.
116181*/
116182
116183/*
116184** Structures used by the tokenizer interface. When a new tokenizer
116185** implementation is registered, the caller provides a pointer to
116186** an sqlite3_tokenizer_module containing pointers to the callback
116187** functions that make up an implementation.
116188**
116189** When an fts3 table is created, it passes any arguments passed to
116190** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
116191** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
116192** implementation. The xCreate() function in turn returns an
116193** sqlite3_tokenizer structure representing the specific tokenizer to
116194** be used for the fts3 table (customized by the tokenizer clause arguments).
116195**
116196** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
116197** method is called. It returns an sqlite3_tokenizer_cursor object
116198** that may be used to tokenize a specific input buffer based on
116199** the tokenization rules supplied by a specific sqlite3_tokenizer
116200** object.
116201*/
116202typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
116203typedef struct sqlite3_tokenizer sqlite3_tokenizer;
116204typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
116205
116206struct sqlite3_tokenizer_module {
116207
116208  /*
116209  ** Structure version. Should always be set to 0 or 1.
116210  */
116211  int iVersion;
116212
116213  /*
116214  ** Create a new tokenizer. The values in the argv[] array are the
116215  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
116216  ** TABLE statement that created the fts3 table. For example, if
116217  ** the following SQL is executed:
116218  **
116219  **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
116220  **
116221  ** then argc is set to 2, and the argv[] array contains pointers
116222  ** to the strings "arg1" and "arg2".
116223  **
116224  ** This method should return either SQLITE_OK (0), or an SQLite error
116225  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
116226  ** to point at the newly created tokenizer structure. The generic
116227  ** sqlite3_tokenizer.pModule variable should not be initialised by
116228  ** this callback. The caller will do so.
116229  */
116230  int (*xCreate)(
116231    int argc,                           /* Size of argv array */
116232    const char *const*argv,             /* Tokenizer argument strings */
116233    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
116234  );
116235
116236  /*
116237  ** Destroy an existing tokenizer. The fts3 module calls this method
116238  ** exactly once for each successful call to xCreate().
116239  */
116240  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
116241
116242  /*
116243  ** Create a tokenizer cursor to tokenize an input buffer. The caller
116244  ** is responsible for ensuring that the input buffer remains valid
116245  ** until the cursor is closed (using the xClose() method).
116246  */
116247  int (*xOpen)(
116248    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
116249    const char *pInput, int nBytes,      /* Input buffer */
116250    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
116251  );
116252
116253  /*
116254  ** Destroy an existing tokenizer cursor. The fts3 module calls this
116255  ** method exactly once for each successful call to xOpen().
116256  */
116257  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
116258
116259  /*
116260  ** Retrieve the next token from the tokenizer cursor pCursor. This
116261  ** method should either return SQLITE_OK and set the values of the
116262  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
116263  ** the end of the buffer has been reached, or an SQLite error code.
116264  **
116265  ** *ppToken should be set to point at a buffer containing the
116266  ** normalized version of the token (i.e. after any case-folding and/or
116267  ** stemming has been performed). *pnBytes should be set to the length
116268  ** of this buffer in bytes. The input text that generated the token is
116269  ** identified by the byte offsets returned in *piStartOffset and
116270  ** *piEndOffset. *piStartOffset should be set to the index of the first
116271  ** byte of the token in the input buffer. *piEndOffset should be set
116272  ** to the index of the first byte just past the end of the token in
116273  ** the input buffer.
116274  **
116275  ** The buffer *ppToken is set to point at is managed by the tokenizer
116276  ** implementation. It is only required to be valid until the next call
116277  ** to xNext() or xClose().
116278  */
116279  /* TODO(shess) current implementation requires pInput to be
116280  ** nul-terminated.  This should either be fixed, or pInput/nBytes
116281  ** should be converted to zInput.
116282  */
116283  int (*xNext)(
116284    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
116285    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
116286    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
116287    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
116288    int *piPosition      /* OUT: Number of tokens returned before this one */
116289  );
116290
116291  /***********************************************************************
116292  ** Methods below this point are only available if iVersion>=1.
116293  */
116294
116295  /*
116296  ** Configure the language id of a tokenizer cursor.
116297  */
116298  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
116299};
116300
116301struct sqlite3_tokenizer {
116302  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
116303  /* Tokenizer implementations will typically add additional fields */
116304};
116305
116306struct sqlite3_tokenizer_cursor {
116307  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
116308  /* Tokenizer implementations will typically add additional fields */
116309};
116310
116311int fts3_global_term_cnt(int iTerm, int iCol);
116312int fts3_term_cnt(int iTerm, int iCol);
116313
116314
116315#endif /* _FTS3_TOKENIZER_H_ */
116316
116317/************** End of fts3_tokenizer.h **************************************/
116318/************** Continuing where we left off in fts3Int.h ********************/
116319/************** Include fts3_hash.h in the middle of fts3Int.h ***************/
116320/************** Begin file fts3_hash.h ***************************************/
116321/*
116322** 2001 September 22
116323**
116324** The author disclaims copyright to this source code.  In place of
116325** a legal notice, here is a blessing:
116326**
116327**    May you do good and not evil.
116328**    May you find forgiveness for yourself and forgive others.
116329**    May you share freely, never taking more than you give.
116330**
116331*************************************************************************
116332** This is the header file for the generic hash-table implemenation
116333** used in SQLite.  We've modified it slightly to serve as a standalone
116334** hash table implementation for the full-text indexing module.
116335**
116336*/
116337#ifndef _FTS3_HASH_H_
116338#define _FTS3_HASH_H_
116339
116340/* Forward declarations of structures. */
116341typedef struct Fts3Hash Fts3Hash;
116342typedef struct Fts3HashElem Fts3HashElem;
116343
116344/* A complete hash table is an instance of the following structure.
116345** The internals of this structure are intended to be opaque -- client
116346** code should not attempt to access or modify the fields of this structure
116347** directly.  Change this structure only by using the routines below.
116348** However, many of the "procedures" and "functions" for modifying and
116349** accessing this structure are really macros, so we can't really make
116350** this structure opaque.
116351*/
116352struct Fts3Hash {
116353  char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
116354  char copyKey;           /* True if copy of key made on insert */
116355  int count;              /* Number of entries in this table */
116356  Fts3HashElem *first;    /* The first element of the array */
116357  int htsize;             /* Number of buckets in the hash table */
116358  struct _fts3ht {        /* the hash table */
116359    int count;               /* Number of entries with this hash */
116360    Fts3HashElem *chain;     /* Pointer to first entry with this hash */
116361  } *ht;
116362};
116363
116364/* Each element in the hash table is an instance of the following
116365** structure.  All elements are stored on a single doubly-linked list.
116366**
116367** Again, this structure is intended to be opaque, but it can't really
116368** be opaque because it is used by macros.
116369*/
116370struct Fts3HashElem {
116371  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
116372  void *data;                /* Data associated with this element */
116373  void *pKey; int nKey;      /* Key associated with this element */
116374};
116375
116376/*
116377** There are 2 different modes of operation for a hash table:
116378**
116379**   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
116380**                           (including the null-terminator, if any).  Case
116381**                           is respected in comparisons.
116382**
116383**   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long.
116384**                           memcmp() is used to compare keys.
116385**
116386** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
116387*/
116388#define FTS3_HASH_STRING    1
116389#define FTS3_HASH_BINARY    2
116390
116391/*
116392** Access routines.  To delete, insert a NULL pointer.
116393*/
116394SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
116395SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
116396SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
116397SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
116398SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
116399
116400/*
116401** Shorthand for the functions above
116402*/
116403#define fts3HashInit     sqlite3Fts3HashInit
116404#define fts3HashInsert   sqlite3Fts3HashInsert
116405#define fts3HashFind     sqlite3Fts3HashFind
116406#define fts3HashClear    sqlite3Fts3HashClear
116407#define fts3HashFindElem sqlite3Fts3HashFindElem
116408
116409/*
116410** Macros for looping over all elements of a hash table.  The idiom is
116411** like this:
116412**
116413**   Fts3Hash h;
116414**   Fts3HashElem *p;
116415**   ...
116416**   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
116417**     SomeStructure *pData = fts3HashData(p);
116418**     // do something with pData
116419**   }
116420*/
116421#define fts3HashFirst(H)  ((H)->first)
116422#define fts3HashNext(E)   ((E)->next)
116423#define fts3HashData(E)   ((E)->data)
116424#define fts3HashKey(E)    ((E)->pKey)
116425#define fts3HashKeysize(E) ((E)->nKey)
116426
116427/*
116428** Number of entries in a hash table
116429*/
116430#define fts3HashCount(H)  ((H)->count)
116431
116432#endif /* _FTS3_HASH_H_ */
116433
116434/************** End of fts3_hash.h *******************************************/
116435/************** Continuing where we left off in fts3Int.h ********************/
116436
116437/*
116438** This constant controls how often segments are merged. Once there are
116439** FTS3_MERGE_COUNT segments of level N, they are merged into a single
116440** segment of level N+1.
116441*/
116442#define FTS3_MERGE_COUNT 16
116443
116444/*
116445** This is the maximum amount of data (in bytes) to store in the
116446** Fts3Table.pendingTerms hash table. Normally, the hash table is
116447** populated as documents are inserted/updated/deleted in a transaction
116448** and used to create a new segment when the transaction is committed.
116449** However if this limit is reached midway through a transaction, a new
116450** segment is created and the hash table cleared immediately.
116451*/
116452#define FTS3_MAX_PENDING_DATA (1*1024*1024)
116453
116454/*
116455** Macro to return the number of elements in an array. SQLite has a
116456** similar macro called ArraySize(). Use a different name to avoid
116457** a collision when building an amalgamation with built-in FTS3.
116458*/
116459#define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
116460
116461
116462#ifndef MIN
116463# define MIN(x,y) ((x)<(y)?(x):(y))
116464#endif
116465
116466/*
116467** Maximum length of a varint encoded integer. The varint format is different
116468** from that used by SQLite, so the maximum length is 10, not 9.
116469*/
116470#define FTS3_VARINT_MAX 10
116471
116472/*
116473** FTS4 virtual tables may maintain multiple indexes - one index of all terms
116474** in the document set and zero or more prefix indexes. All indexes are stored
116475** as one or more b+-trees in the %_segments and %_segdir tables.
116476**
116477** It is possible to determine which index a b+-tree belongs to based on the
116478** value stored in the "%_segdir.level" column. Given this value L, the index
116479** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
116480** level values between 0 and 1023 (inclusive) belong to index 0, all levels
116481** between 1024 and 2047 to index 1, and so on.
116482**
116483** It is considered impossible for an index to use more than 1024 levels. In
116484** theory though this may happen, but only after at least
116485** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
116486*/
116487#define FTS3_SEGDIR_MAXLEVEL      1024
116488#define FTS3_SEGDIR_MAXLEVEL_STR "1024"
116489
116490/*
116491** The testcase() macro is only used by the amalgamation.  If undefined,
116492** make it a no-op.
116493*/
116494#ifndef testcase
116495# define testcase(X)
116496#endif
116497
116498/*
116499** Terminator values for position-lists and column-lists.
116500*/
116501#define POS_COLUMN  (1)     /* Column-list terminator */
116502#define POS_END     (0)     /* Position-list terminator */
116503
116504/*
116505** This section provides definitions to allow the
116506** FTS3 extension to be compiled outside of the
116507** amalgamation.
116508*/
116509#ifndef SQLITE_AMALGAMATION
116510/*
116511** Macros indicating that conditional expressions are always true or
116512** false.
116513*/
116514#ifdef SQLITE_COVERAGE_TEST
116515# define ALWAYS(x) (1)
116516# define NEVER(X)  (0)
116517#else
116518# define ALWAYS(x) (x)
116519# define NEVER(X)  (x)
116520#endif
116521
116522/*
116523** Internal types used by SQLite.
116524*/
116525typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
116526typedef short int i16;            /* 2-byte (or larger) signed integer */
116527typedef unsigned int u32;         /* 4-byte unsigned integer */
116528typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
116529
116530/*
116531** Macro used to suppress compiler warnings for unused parameters.
116532*/
116533#define UNUSED_PARAMETER(x) (void)(x)
116534
116535/*
116536** Activate assert() only if SQLITE_TEST is enabled.
116537*/
116538#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
116539# define NDEBUG 1
116540#endif
116541
116542/*
116543** The TESTONLY macro is used to enclose variable declarations or
116544** other bits of code that are needed to support the arguments
116545** within testcase() and assert() macros.
116546*/
116547#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
116548# define TESTONLY(X)  X
116549#else
116550# define TESTONLY(X)
116551#endif
116552
116553#endif /* SQLITE_AMALGAMATION */
116554
116555#ifdef SQLITE_DEBUG
116556SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
116557# define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
116558#else
116559# define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
116560#endif
116561
116562typedef struct Fts3Table Fts3Table;
116563typedef struct Fts3Cursor Fts3Cursor;
116564typedef struct Fts3Expr Fts3Expr;
116565typedef struct Fts3Phrase Fts3Phrase;
116566typedef struct Fts3PhraseToken Fts3PhraseToken;
116567
116568typedef struct Fts3Doclist Fts3Doclist;
116569typedef struct Fts3SegFilter Fts3SegFilter;
116570typedef struct Fts3DeferredToken Fts3DeferredToken;
116571typedef struct Fts3SegReader Fts3SegReader;
116572typedef struct Fts3MultiSegReader Fts3MultiSegReader;
116573
116574/*
116575** A connection to a fulltext index is an instance of the following
116576** structure. The xCreate and xConnect methods create an instance
116577** of this structure and xDestroy and xDisconnect free that instance.
116578** All other methods receive a pointer to the structure as one of their
116579** arguments.
116580*/
116581struct Fts3Table {
116582  sqlite3_vtab base;              /* Base class used by SQLite core */
116583  sqlite3 *db;                    /* The database connection */
116584  const char *zDb;                /* logical database name */
116585  const char *zName;              /* virtual table name */
116586  int nColumn;                    /* number of named columns in virtual table */
116587  char **azColumn;                /* column names.  malloced */
116588  sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
116589  char *zContentTbl;              /* content=xxx option, or NULL */
116590  char *zLanguageid;              /* languageid=xxx option, or NULL */
116591
116592  /* Precompiled statements used by the implementation. Each of these
116593  ** statements is run and reset within a single virtual table API call.
116594  */
116595  sqlite3_stmt *aStmt[28];
116596
116597  char *zReadExprlist;
116598  char *zWriteExprlist;
116599
116600  int nNodeSize;                  /* Soft limit for node size */
116601  u8 bHasStat;                    /* True if %_stat table exists */
116602  u8 bHasDocsize;                 /* True if %_docsize table exists */
116603  u8 bDescIdx;                    /* True if doclists are in reverse order */
116604  int nPgsz;                      /* Page size for host database */
116605  char *zSegmentsTbl;             /* Name of %_segments table */
116606  sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
116607
116608  /* TODO: Fix the first paragraph of this comment.
116609  **
116610  ** The following array of hash tables is used to buffer pending index
116611  ** updates during transactions. Variable nPendingData estimates the memory
116612  ** size of the pending data, including hash table overhead, not including
116613  ** malloc overhead.  When nPendingData exceeds nMaxPendingData, the buffer
116614  ** is flushed automatically. Variable iPrevDocid is the docid of the most
116615  ** recently inserted record.
116616  **
116617  ** A single FTS4 table may have multiple full-text indexes. For each index
116618  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
116619  ** terms that appear in the document set. Each subsequent index in aIndex[]
116620  ** is an index of prefixes of a specific length.
116621  */
116622  int nIndex;                     /* Size of aIndex[] */
116623  struct Fts3Index {
116624    int nPrefix;                  /* Prefix length (0 for main terms index) */
116625    Fts3Hash hPending;            /* Pending terms table for this index */
116626  } *aIndex;
116627  int nMaxPendingData;            /* Max pending data before flush to disk */
116628  int nPendingData;               /* Current bytes of pending data */
116629  sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
116630  int iPrevLangid;                /* Langid of recently inserted document */
116631
116632#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
116633  /* State variables used for validating that the transaction control
116634  ** methods of the virtual table are called at appropriate times.  These
116635  ** values do not contribute to FTS functionality; they are used for
116636  ** verifying the operation of the SQLite core.
116637  */
116638  int inTransaction;     /* True after xBegin but before xCommit/xRollback */
116639  int mxSavepoint;       /* Largest valid xSavepoint integer */
116640#endif
116641};
116642
116643/*
116644** When the core wants to read from the virtual table, it creates a
116645** virtual table cursor (an instance of the following structure) using
116646** the xOpen method. Cursors are destroyed using the xClose method.
116647*/
116648struct Fts3Cursor {
116649  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
116650  i16 eSearch;                    /* Search strategy (see below) */
116651  u8 isEof;                       /* True if at End Of Results */
116652  u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
116653  sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
116654  Fts3Expr *pExpr;                /* Parsed MATCH query string */
116655  int iLangid;                    /* Language being queried for */
116656  int nPhrase;                    /* Number of matchable phrases in query */
116657  Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
116658  sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
116659  char *pNextId;                  /* Pointer into the body of aDoclist */
116660  char *aDoclist;                 /* List of docids for full-text queries */
116661  int nDoclist;                   /* Size of buffer at aDoclist */
116662  u8 bDesc;                       /* True to sort in descending order */
116663  int eEvalmode;                  /* An FTS3_EVAL_XX constant */
116664  int nRowAvg;                    /* Average size of database rows, in pages */
116665  sqlite3_int64 nDoc;             /* Documents in table */
116666
116667  int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
116668  u32 *aMatchinfo;                /* Information about most recent match */
116669  int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
116670  char *zMatchinfo;               /* Matchinfo specification */
116671};
116672
116673#define FTS3_EVAL_FILTER    0
116674#define FTS3_EVAL_NEXT      1
116675#define FTS3_EVAL_MATCHINFO 2
116676
116677/*
116678** The Fts3Cursor.eSearch member is always set to one of the following.
116679** Actualy, Fts3Cursor.eSearch can be greater than or equal to
116680** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
116681** of the column to be searched.  For example, in
116682**
116683**     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
116684**     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
116685**
116686** Because the LHS of the MATCH operator is 2nd column "b",
116687** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
116688** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1"
116689** indicating that all columns should be searched,
116690** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
116691*/
116692#define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
116693#define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
116694#define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
116695
116696
116697struct Fts3Doclist {
116698  char *aAll;                    /* Array containing doclist (or NULL) */
116699  int nAll;                      /* Size of a[] in bytes */
116700  char *pNextDocid;              /* Pointer to next docid */
116701
116702  sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
116703  int bFreeList;                 /* True if pList should be sqlite3_free()d */
116704  char *pList;                   /* Pointer to position list following iDocid */
116705  int nList;                     /* Length of position list */
116706};
116707
116708/*
116709** A "phrase" is a sequence of one or more tokens that must match in
116710** sequence.  A single token is the base case and the most common case.
116711** For a sequence of tokens contained in double-quotes (i.e. "one two three")
116712** nToken will be the number of tokens in the string.
116713*/
116714struct Fts3PhraseToken {
116715  char *z;                        /* Text of the token */
116716  int n;                          /* Number of bytes in buffer z */
116717  int isPrefix;                   /* True if token ends with a "*" character */
116718  int bFirst;                     /* True if token must appear at position 0 */
116719
116720  /* Variables above this point are populated when the expression is
116721  ** parsed (by code in fts3_expr.c). Below this point the variables are
116722  ** used when evaluating the expression. */
116723  Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
116724  Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
116725};
116726
116727struct Fts3Phrase {
116728  /* Cache of doclist for this phrase. */
116729  Fts3Doclist doclist;
116730  int bIncr;                 /* True if doclist is loaded incrementally */
116731  int iDoclistToken;
116732
116733  /* Variables below this point are populated by fts3_expr.c when parsing
116734  ** a MATCH expression. Everything above is part of the evaluation phase.
116735  */
116736  int nToken;                /* Number of tokens in the phrase */
116737  int iColumn;               /* Index of column this phrase must match */
116738  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
116739};
116740
116741/*
116742** A tree of these objects forms the RHS of a MATCH operator.
116743**
116744** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
116745** points to a malloced buffer, size nDoclist bytes, containing the results
116746** of this phrase query in FTS3 doclist format. As usual, the initial
116747** "Length" field found in doclists stored on disk is omitted from this
116748** buffer.
116749**
116750** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
116751** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
116752** where nCol is the number of columns in the queried FTS table. The array
116753** is populated as follows:
116754**
116755**   aMI[iCol*3 + 0] = Undefined
116756**   aMI[iCol*3 + 1] = Number of occurrences
116757**   aMI[iCol*3 + 2] = Number of rows containing at least one instance
116758**
116759** The aMI array is allocated using sqlite3_malloc(). It should be freed
116760** when the expression node is.
116761*/
116762struct Fts3Expr {
116763  int eType;                 /* One of the FTSQUERY_XXX values defined below */
116764  int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
116765  Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
116766  Fts3Expr *pLeft;           /* Left operand */
116767  Fts3Expr *pRight;          /* Right operand */
116768  Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
116769
116770  /* The following are used by the fts3_eval.c module. */
116771  sqlite3_int64 iDocid;      /* Current docid */
116772  u8 bEof;                   /* True this expression is at EOF already */
116773  u8 bStart;                 /* True if iDocid is valid */
116774  u8 bDeferred;              /* True if this expression is entirely deferred */
116775
116776  u32 *aMI;
116777};
116778
116779/*
116780** Candidate values for Fts3Query.eType. Note that the order of the first
116781** four values is in order of precedence when parsing expressions. For
116782** example, the following:
116783**
116784**   "a OR b AND c NOT d NEAR e"
116785**
116786** is equivalent to:
116787**
116788**   "a OR (b AND (c NOT (d NEAR e)))"
116789*/
116790#define FTSQUERY_NEAR   1
116791#define FTSQUERY_NOT    2
116792#define FTSQUERY_AND    3
116793#define FTSQUERY_OR     4
116794#define FTSQUERY_PHRASE 5
116795
116796
116797/* fts3_write.c */
116798SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
116799SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
116800SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
116801SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
116802SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
116803  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
116804SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
116805  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
116806SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
116807SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
116808SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
116809SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
116810
116811SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
116812SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
116813
116814SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
116815SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
116816SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
116817SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
116818SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
116819
116820/* Special values interpreted by sqlite3SegReaderCursor() */
116821#define FTS3_SEGCURSOR_PENDING        -1
116822#define FTS3_SEGCURSOR_ALL            -2
116823
116824SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
116825SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
116826SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
116827
116828SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
116829    int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
116830
116831/* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
116832#define FTS3_SEGMENT_REQUIRE_POS   0x00000001
116833#define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
116834#define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
116835#define FTS3_SEGMENT_PREFIX        0x00000008
116836#define FTS3_SEGMENT_SCAN          0x00000010
116837#define FTS3_SEGMENT_FIRST         0x00000020
116838
116839/* Type passed as 4th argument to SegmentReaderIterate() */
116840struct Fts3SegFilter {
116841  const char *zTerm;
116842  int nTerm;
116843  int iCol;
116844  int flags;
116845};
116846
116847struct Fts3MultiSegReader {
116848  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
116849  Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
116850  int nSegment;                   /* Size of apSegment array */
116851  int nAdvance;                   /* How many seg-readers to advance */
116852  Fts3SegFilter *pFilter;         /* Pointer to filter object */
116853  char *aBuffer;                  /* Buffer to merge doclists in */
116854  int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
116855
116856  int iColFilter;                 /* If >=0, filter for this column */
116857  int bRestart;
116858
116859  /* Used by fts3.c only. */
116860  int nCost;                      /* Cost of running iterator */
116861  int bLookup;                    /* True if a lookup of a single entry. */
116862
116863  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
116864  char *zTerm;                    /* Pointer to term buffer */
116865  int nTerm;                      /* Size of zTerm in bytes */
116866  char *aDoclist;                 /* Pointer to doclist buffer */
116867  int nDoclist;                   /* Size of aDoclist[] in bytes */
116868};
116869
116870/* fts3.c */
116871SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
116872SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
116873SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
116874SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
116875SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
116876SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
116877SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
116878SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
116879
116880/* fts3_tokenizer.c */
116881SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
116882SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
116883SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
116884    sqlite3_tokenizer **, char **
116885);
116886SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
116887
116888/* fts3_snippet.c */
116889SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
116890SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
116891  const char *, const char *, int, int
116892);
116893SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
116894
116895/* fts3_expr.c */
116896SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
116897  char **, int, int, int, const char *, int, Fts3Expr **
116898);
116899SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
116900#ifdef SQLITE_TEST
116901SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
116902SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
116903#endif
116904
116905SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
116906  sqlite3_tokenizer_cursor **
116907);
116908
116909/* fts3_aux.c */
116910SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
116911
116912SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
116913
116914SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
116915    Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
116916SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
116917    Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
116918SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol);
116919SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
116920SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
116921
116922SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
116923
116924#endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
116925#endif /* _FTSINT_H */
116926
116927/************** End of fts3Int.h *********************************************/
116928/************** Continuing where we left off in fts3.c ***********************/
116929#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
116930
116931#if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
116932# define SQLITE_CORE 1
116933#endif
116934
116935/* #include <assert.h> */
116936/* #include <stdlib.h> */
116937/* #include <stddef.h> */
116938/* #include <stdio.h> */
116939/* #include <string.h> */
116940/* #include <stdarg.h> */
116941
116942#ifndef SQLITE_CORE
116943  SQLITE_EXTENSION_INIT1
116944#endif
116945
116946static int fts3EvalNext(Fts3Cursor *pCsr);
116947static int fts3EvalStart(Fts3Cursor *pCsr);
116948static int fts3TermSegReaderCursor(
116949    Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
116950
116951/*
116952** Write a 64-bit variable-length integer to memory starting at p[0].
116953** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
116954** The number of bytes written is returned.
116955*/
116956SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
116957  unsigned char *q = (unsigned char *) p;
116958  sqlite_uint64 vu = v;
116959  do{
116960    *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
116961    vu >>= 7;
116962  }while( vu!=0 );
116963  q[-1] &= 0x7f;  /* turn off high bit in final byte */
116964  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
116965  return (int) (q - (unsigned char *)p);
116966}
116967
116968/*
116969** Read a 64-bit variable-length integer from memory starting at p[0].
116970** Return the number of bytes read, or 0 on error.
116971** The value is stored in *v.
116972*/
116973SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
116974  const unsigned char *q = (const unsigned char *) p;
116975  sqlite_uint64 x = 0, y = 1;
116976  while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
116977    x += y * (*q++ & 0x7f);
116978    y <<= 7;
116979  }
116980  x += y * (*q++);
116981  *v = (sqlite_int64) x;
116982  return (int) (q - (unsigned char *)p);
116983}
116984
116985/*
116986** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
116987** 32-bit integer before it is returned.
116988*/
116989SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
116990 sqlite_int64 i;
116991 int ret = sqlite3Fts3GetVarint(p, &i);
116992 *pi = (int) i;
116993 return ret;
116994}
116995
116996/*
116997** Return the number of bytes required to encode v as a varint
116998*/
116999SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
117000  int i = 0;
117001  do{
117002    i++;
117003    v >>= 7;
117004  }while( v!=0 );
117005  return i;
117006}
117007
117008/*
117009** Convert an SQL-style quoted string into a normal string by removing
117010** the quote characters.  The conversion is done in-place.  If the
117011** input does not begin with a quote character, then this routine
117012** is a no-op.
117013**
117014** Examples:
117015**
117016**     "abc"   becomes   abc
117017**     'xyz'   becomes   xyz
117018**     [pqr]   becomes   pqr
117019**     `mno`   becomes   mno
117020**
117021*/
117022SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
117023  char quote;                     /* Quote character (if any ) */
117024
117025  quote = z[0];
117026  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
117027    int iIn = 1;                  /* Index of next byte to read from input */
117028    int iOut = 0;                 /* Index of next byte to write to output */
117029
117030    /* If the first byte was a '[', then the close-quote character is a ']' */
117031    if( quote=='[' ) quote = ']';
117032
117033    while( ALWAYS(z[iIn]) ){
117034      if( z[iIn]==quote ){
117035        if( z[iIn+1]!=quote ) break;
117036        z[iOut++] = quote;
117037        iIn += 2;
117038      }else{
117039        z[iOut++] = z[iIn++];
117040      }
117041    }
117042    z[iOut] = '\0';
117043  }
117044}
117045
117046/*
117047** Read a single varint from the doclist at *pp and advance *pp to point
117048** to the first byte past the end of the varint.  Add the value of the varint
117049** to *pVal.
117050*/
117051static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
117052  sqlite3_int64 iVal;
117053  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
117054  *pVal += iVal;
117055}
117056
117057/*
117058** When this function is called, *pp points to the first byte following a
117059** varint that is part of a doclist (or position-list, or any other list
117060** of varints). This function moves *pp to point to the start of that varint,
117061** and sets *pVal by the varint value.
117062**
117063** Argument pStart points to the first byte of the doclist that the
117064** varint is part of.
117065*/
117066static void fts3GetReverseVarint(
117067  char **pp,
117068  char *pStart,
117069  sqlite3_int64 *pVal
117070){
117071  sqlite3_int64 iVal;
117072  char *p;
117073
117074  /* Pointer p now points at the first byte past the varint we are
117075  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
117076  ** clear on character p[-1]. */
117077  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
117078  p++;
117079  *pp = p;
117080
117081  sqlite3Fts3GetVarint(p, &iVal);
117082  *pVal = iVal;
117083}
117084
117085/*
117086** The xDisconnect() virtual table method.
117087*/
117088static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
117089  Fts3Table *p = (Fts3Table *)pVtab;
117090  int i;
117091
117092  assert( p->nPendingData==0 );
117093  assert( p->pSegments==0 );
117094
117095  /* Free any prepared statements held */
117096  for(i=0; i<SizeofArray(p->aStmt); i++){
117097    sqlite3_finalize(p->aStmt[i]);
117098  }
117099  sqlite3_free(p->zSegmentsTbl);
117100  sqlite3_free(p->zReadExprlist);
117101  sqlite3_free(p->zWriteExprlist);
117102  sqlite3_free(p->zContentTbl);
117103  sqlite3_free(p->zLanguageid);
117104
117105  /* Invoke the tokenizer destructor to free the tokenizer. */
117106  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
117107
117108  sqlite3_free(p);
117109  return SQLITE_OK;
117110}
117111
117112/*
117113** Construct one or more SQL statements from the format string given
117114** and then evaluate those statements. The success code is written
117115** into *pRc.
117116**
117117** If *pRc is initially non-zero then this routine is a no-op.
117118*/
117119static void fts3DbExec(
117120  int *pRc,              /* Success code */
117121  sqlite3 *db,           /* Database in which to run SQL */
117122  const char *zFormat,   /* Format string for SQL */
117123  ...                    /* Arguments to the format string */
117124){
117125  va_list ap;
117126  char *zSql;
117127  if( *pRc ) return;
117128  va_start(ap, zFormat);
117129  zSql = sqlite3_vmprintf(zFormat, ap);
117130  va_end(ap);
117131  if( zSql==0 ){
117132    *pRc = SQLITE_NOMEM;
117133  }else{
117134    *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
117135    sqlite3_free(zSql);
117136  }
117137}
117138
117139/*
117140** The xDestroy() virtual table method.
117141*/
117142static int fts3DestroyMethod(sqlite3_vtab *pVtab){
117143  Fts3Table *p = (Fts3Table *)pVtab;
117144  int rc = SQLITE_OK;              /* Return code */
117145  const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
117146  sqlite3 *db = p->db;             /* Database handle */
117147
117148  /* Drop the shadow tables */
117149  if( p->zContentTbl==0 ){
117150    fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
117151  }
117152  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
117153  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
117154  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
117155  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
117156
117157  /* If everything has worked, invoke fts3DisconnectMethod() to free the
117158  ** memory associated with the Fts3Table structure and return SQLITE_OK.
117159  ** Otherwise, return an SQLite error code.
117160  */
117161  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
117162}
117163
117164
117165/*
117166** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
117167** passed as the first argument. This is done as part of the xConnect()
117168** and xCreate() methods.
117169**
117170** If *pRc is non-zero when this function is called, it is a no-op.
117171** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
117172** before returning.
117173*/
117174static void fts3DeclareVtab(int *pRc, Fts3Table *p){
117175  if( *pRc==SQLITE_OK ){
117176    int i;                        /* Iterator variable */
117177    int rc;                       /* Return code */
117178    char *zSql;                   /* SQL statement passed to declare_vtab() */
117179    char *zCols;                  /* List of user defined columns */
117180    const char *zLanguageid;
117181
117182    zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
117183    sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
117184
117185    /* Create a list of user columns for the virtual table */
117186    zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
117187    for(i=1; zCols && i<p->nColumn; i++){
117188      zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
117189    }
117190
117191    /* Create the whole "CREATE TABLE" statement to pass to SQLite */
117192    zSql = sqlite3_mprintf(
117193        "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
117194        zCols, p->zName, zLanguageid
117195    );
117196    if( !zCols || !zSql ){
117197      rc = SQLITE_NOMEM;
117198    }else{
117199      rc = sqlite3_declare_vtab(p->db, zSql);
117200    }
117201
117202    sqlite3_free(zSql);
117203    sqlite3_free(zCols);
117204    *pRc = rc;
117205  }
117206}
117207
117208/*
117209** Create the backing store tables (%_content, %_segments and %_segdir)
117210** required by the FTS3 table passed as the only argument. This is done
117211** as part of the vtab xCreate() method.
117212**
117213** If the p->bHasDocsize boolean is true (indicating that this is an
117214** FTS4 table, not an FTS3 table) then also create the %_docsize and
117215** %_stat tables required by FTS4.
117216*/
117217static int fts3CreateTables(Fts3Table *p){
117218  int rc = SQLITE_OK;             /* Return code */
117219  int i;                          /* Iterator variable */
117220  sqlite3 *db = p->db;            /* The database connection */
117221
117222  if( p->zContentTbl==0 ){
117223    const char *zLanguageid = p->zLanguageid;
117224    char *zContentCols;           /* Columns of %_content table */
117225
117226    /* Create a list of user columns for the content table */
117227    zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
117228    for(i=0; zContentCols && i<p->nColumn; i++){
117229      char *z = p->azColumn[i];
117230      zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
117231    }
117232    if( zLanguageid && zContentCols ){
117233      zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
117234    }
117235    if( zContentCols==0 ) rc = SQLITE_NOMEM;
117236
117237    /* Create the content table */
117238    fts3DbExec(&rc, db,
117239       "CREATE TABLE %Q.'%q_content'(%s)",
117240       p->zDb, p->zName, zContentCols
117241    );
117242    sqlite3_free(zContentCols);
117243  }
117244
117245  /* Create other tables */
117246  fts3DbExec(&rc, db,
117247      "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
117248      p->zDb, p->zName
117249  );
117250  fts3DbExec(&rc, db,
117251      "CREATE TABLE %Q.'%q_segdir'("
117252        "level INTEGER,"
117253        "idx INTEGER,"
117254        "start_block INTEGER,"
117255        "leaves_end_block INTEGER,"
117256        "end_block INTEGER,"
117257        "root BLOB,"
117258        "PRIMARY KEY(level, idx)"
117259      ");",
117260      p->zDb, p->zName
117261  );
117262  if( p->bHasDocsize ){
117263    fts3DbExec(&rc, db,
117264        "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
117265        p->zDb, p->zName
117266    );
117267  }
117268  if( p->bHasStat ){
117269    fts3DbExec(&rc, db,
117270        "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
117271        p->zDb, p->zName
117272    );
117273  }
117274  return rc;
117275}
117276
117277/*
117278** Store the current database page-size in bytes in p->nPgsz.
117279**
117280** If *pRc is non-zero when this function is called, it is a no-op.
117281** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
117282** before returning.
117283*/
117284static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
117285  if( *pRc==SQLITE_OK ){
117286    int rc;                       /* Return code */
117287    char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
117288    sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
117289
117290    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
117291    if( !zSql ){
117292      rc = SQLITE_NOMEM;
117293    }else{
117294      rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
117295      if( rc==SQLITE_OK ){
117296        sqlite3_step(pStmt);
117297        p->nPgsz = sqlite3_column_int(pStmt, 0);
117298        rc = sqlite3_finalize(pStmt);
117299      }else if( rc==SQLITE_AUTH ){
117300        p->nPgsz = 1024;
117301        rc = SQLITE_OK;
117302      }
117303    }
117304    assert( p->nPgsz>0 || rc!=SQLITE_OK );
117305    sqlite3_free(zSql);
117306    *pRc = rc;
117307  }
117308}
117309
117310/*
117311** "Special" FTS4 arguments are column specifications of the following form:
117312**
117313**   <key> = <value>
117314**
117315** There may not be whitespace surrounding the "=" character. The <value>
117316** term may be quoted, but the <key> may not.
117317*/
117318static int fts3IsSpecialColumn(
117319  const char *z,
117320  int *pnKey,
117321  char **pzValue
117322){
117323  char *zValue;
117324  const char *zCsr = z;
117325
117326  while( *zCsr!='=' ){
117327    if( *zCsr=='\0' ) return 0;
117328    zCsr++;
117329  }
117330
117331  *pnKey = (int)(zCsr-z);
117332  zValue = sqlite3_mprintf("%s", &zCsr[1]);
117333  if( zValue ){
117334    sqlite3Fts3Dequote(zValue);
117335  }
117336  *pzValue = zValue;
117337  return 1;
117338}
117339
117340/*
117341** Append the output of a printf() style formatting to an existing string.
117342*/
117343static void fts3Appendf(
117344  int *pRc,                       /* IN/OUT: Error code */
117345  char **pz,                      /* IN/OUT: Pointer to string buffer */
117346  const char *zFormat,            /* Printf format string to append */
117347  ...                             /* Arguments for printf format string */
117348){
117349  if( *pRc==SQLITE_OK ){
117350    va_list ap;
117351    char *z;
117352    va_start(ap, zFormat);
117353    z = sqlite3_vmprintf(zFormat, ap);
117354    va_end(ap);
117355    if( z && *pz ){
117356      char *z2 = sqlite3_mprintf("%s%s", *pz, z);
117357      sqlite3_free(z);
117358      z = z2;
117359    }
117360    if( z==0 ) *pRc = SQLITE_NOMEM;
117361    sqlite3_free(*pz);
117362    *pz = z;
117363  }
117364}
117365
117366/*
117367** Return a copy of input string zInput enclosed in double-quotes (") and
117368** with all double quote characters escaped. For example:
117369**
117370**     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
117371**
117372** The pointer returned points to memory obtained from sqlite3_malloc(). It
117373** is the callers responsibility to call sqlite3_free() to release this
117374** memory.
117375*/
117376static char *fts3QuoteId(char const *zInput){
117377  int nRet;
117378  char *zRet;
117379  nRet = 2 + (int)strlen(zInput)*2 + 1;
117380  zRet = sqlite3_malloc(nRet);
117381  if( zRet ){
117382    int i;
117383    char *z = zRet;
117384    *(z++) = '"';
117385    for(i=0; zInput[i]; i++){
117386      if( zInput[i]=='"' ) *(z++) = '"';
117387      *(z++) = zInput[i];
117388    }
117389    *(z++) = '"';
117390    *(z++) = '\0';
117391  }
117392  return zRet;
117393}
117394
117395/*
117396** Return a list of comma separated SQL expressions and a FROM clause that
117397** could be used in a SELECT statement such as the following:
117398**
117399**     SELECT <list of expressions> FROM %_content AS x ...
117400**
117401** to return the docid, followed by each column of text data in order
117402** from left to write. If parameter zFunc is not NULL, then instead of
117403** being returned directly each column of text data is passed to an SQL
117404** function named zFunc first. For example, if zFunc is "unzip" and the
117405** table has the three user-defined columns "a", "b", and "c", the following
117406** string is returned:
117407**
117408**     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
117409**
117410** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
117411** is the responsibility of the caller to eventually free it.
117412**
117413** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
117414** a NULL pointer is returned). Otherwise, if an OOM error is encountered
117415** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
117416** no error occurs, *pRc is left unmodified.
117417*/
117418static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
117419  char *zRet = 0;
117420  char *zFree = 0;
117421  char *zFunction;
117422  int i;
117423
117424  if( p->zContentTbl==0 ){
117425    if( !zFunc ){
117426      zFunction = "";
117427    }else{
117428      zFree = zFunction = fts3QuoteId(zFunc);
117429    }
117430    fts3Appendf(pRc, &zRet, "docid");
117431    for(i=0; i<p->nColumn; i++){
117432      fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
117433    }
117434    if( p->zLanguageid ){
117435      fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
117436    }
117437    sqlite3_free(zFree);
117438  }else{
117439    fts3Appendf(pRc, &zRet, "rowid");
117440    for(i=0; i<p->nColumn; i++){
117441      fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
117442    }
117443    if( p->zLanguageid ){
117444      fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
117445    }
117446  }
117447  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
117448      p->zDb,
117449      (p->zContentTbl ? p->zContentTbl : p->zName),
117450      (p->zContentTbl ? "" : "_content")
117451  );
117452  return zRet;
117453}
117454
117455/*
117456** Return a list of N comma separated question marks, where N is the number
117457** of columns in the %_content table (one for the docid plus one for each
117458** user-defined text column).
117459**
117460** If argument zFunc is not NULL, then all but the first question mark
117461** is preceded by zFunc and an open bracket, and followed by a closed
117462** bracket. For example, if zFunc is "zip" and the FTS3 table has three
117463** user-defined text columns, the following string is returned:
117464**
117465**     "?, zip(?), zip(?), zip(?)"
117466**
117467** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
117468** is the responsibility of the caller to eventually free it.
117469**
117470** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
117471** a NULL pointer is returned). Otherwise, if an OOM error is encountered
117472** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
117473** no error occurs, *pRc is left unmodified.
117474*/
117475static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
117476  char *zRet = 0;
117477  char *zFree = 0;
117478  char *zFunction;
117479  int i;
117480
117481  if( !zFunc ){
117482    zFunction = "";
117483  }else{
117484    zFree = zFunction = fts3QuoteId(zFunc);
117485  }
117486  fts3Appendf(pRc, &zRet, "?");
117487  for(i=0; i<p->nColumn; i++){
117488    fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
117489  }
117490  if( p->zLanguageid ){
117491    fts3Appendf(pRc, &zRet, ", ?");
117492  }
117493  sqlite3_free(zFree);
117494  return zRet;
117495}
117496
117497/*
117498** This function interprets the string at (*pp) as a non-negative integer
117499** value. It reads the integer and sets *pnOut to the value read, then
117500** sets *pp to point to the byte immediately following the last byte of
117501** the integer value.
117502**
117503** Only decimal digits ('0'..'9') may be part of an integer value.
117504**
117505** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
117506** the output value undefined. Otherwise SQLITE_OK is returned.
117507**
117508** This function is used when parsing the "prefix=" FTS4 parameter.
117509*/
117510static int fts3GobbleInt(const char **pp, int *pnOut){
117511  const char *p;                  /* Iterator pointer */
117512  int nInt = 0;                   /* Output value */
117513
117514  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
117515    nInt = nInt * 10 + (p[0] - '0');
117516  }
117517  if( p==*pp ) return SQLITE_ERROR;
117518  *pnOut = nInt;
117519  *pp = p;
117520  return SQLITE_OK;
117521}
117522
117523/*
117524** This function is called to allocate an array of Fts3Index structures
117525** representing the indexes maintained by the current FTS table. FTS tables
117526** always maintain the main "terms" index, but may also maintain one or
117527** more "prefix" indexes, depending on the value of the "prefix=" parameter
117528** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
117529**
117530** Argument zParam is passed the value of the "prefix=" option if one was
117531** specified, or NULL otherwise.
117532**
117533** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
117534** the allocated array. *pnIndex is set to the number of elements in the
117535** array. If an error does occur, an SQLite error code is returned.
117536**
117537** Regardless of whether or not an error is returned, it is the responsibility
117538** of the caller to call sqlite3_free() on the output array to free it.
117539*/
117540static int fts3PrefixParameter(
117541  const char *zParam,             /* ABC in prefix=ABC parameter to parse */
117542  int *pnIndex,                   /* OUT: size of *apIndex[] array */
117543  struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
117544){
117545  struct Fts3Index *aIndex;       /* Allocated array */
117546  int nIndex = 1;                 /* Number of entries in array */
117547
117548  if( zParam && zParam[0] ){
117549    const char *p;
117550    nIndex++;
117551    for(p=zParam; *p; p++){
117552      if( *p==',' ) nIndex++;
117553    }
117554  }
117555
117556  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
117557  *apIndex = aIndex;
117558  *pnIndex = nIndex;
117559  if( !aIndex ){
117560    return SQLITE_NOMEM;
117561  }
117562
117563  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
117564  if( zParam ){
117565    const char *p = zParam;
117566    int i;
117567    for(i=1; i<nIndex; i++){
117568      int nPrefix;
117569      if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
117570      aIndex[i].nPrefix = nPrefix;
117571      p++;
117572    }
117573  }
117574
117575  return SQLITE_OK;
117576}
117577
117578/*
117579** This function is called when initializing an FTS4 table that uses the
117580** content=xxx option. It determines the number of and names of the columns
117581** of the new FTS4 table.
117582**
117583** The third argument passed to this function is the value passed to the
117584** config=xxx option (i.e. "xxx"). This function queries the database for
117585** a table of that name. If found, the output variables are populated
117586** as follows:
117587**
117588**   *pnCol:   Set to the number of columns table xxx has,
117589**
117590**   *pnStr:   Set to the total amount of space required to store a copy
117591**             of each columns name, including the nul-terminator.
117592**
117593**   *pazCol:  Set to point to an array of *pnCol strings. Each string is
117594**             the name of the corresponding column in table xxx. The array
117595**             and its contents are allocated using a single allocation. It
117596**             is the responsibility of the caller to free this allocation
117597**             by eventually passing the *pazCol value to sqlite3_free().
117598**
117599** If the table cannot be found, an error code is returned and the output
117600** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
117601** returned (and the output variables are undefined).
117602*/
117603static int fts3ContentColumns(
117604  sqlite3 *db,                    /* Database handle */
117605  const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
117606  const char *zTbl,               /* Name of content table */
117607  const char ***pazCol,           /* OUT: Malloc'd array of column names */
117608  int *pnCol,                     /* OUT: Size of array *pazCol */
117609  int *pnStr                      /* OUT: Bytes of string content */
117610){
117611  int rc = SQLITE_OK;             /* Return code */
117612  char *zSql;                     /* "SELECT *" statement on zTbl */
117613  sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
117614
117615  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
117616  if( !zSql ){
117617    rc = SQLITE_NOMEM;
117618  }else{
117619    rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
117620  }
117621  sqlite3_free(zSql);
117622
117623  if( rc==SQLITE_OK ){
117624    const char **azCol;           /* Output array */
117625    int nStr = 0;                 /* Size of all column names (incl. 0x00) */
117626    int nCol;                     /* Number of table columns */
117627    int i;                        /* Used to iterate through columns */
117628
117629    /* Loop through the returned columns. Set nStr to the number of bytes of
117630    ** space required to store a copy of each column name, including the
117631    ** nul-terminator byte.  */
117632    nCol = sqlite3_column_count(pStmt);
117633    for(i=0; i<nCol; i++){
117634      const char *zCol = sqlite3_column_name(pStmt, i);
117635      nStr += (int)strlen(zCol) + 1;
117636    }
117637
117638    /* Allocate and populate the array to return. */
117639    azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
117640    if( azCol==0 ){
117641      rc = SQLITE_NOMEM;
117642    }else{
117643      char *p = (char *)&azCol[nCol];
117644      for(i=0; i<nCol; i++){
117645        const char *zCol = sqlite3_column_name(pStmt, i);
117646        int n = (int)strlen(zCol)+1;
117647        memcpy(p, zCol, n);
117648        azCol[i] = p;
117649        p += n;
117650      }
117651    }
117652    sqlite3_finalize(pStmt);
117653
117654    /* Set the output variables. */
117655    *pnCol = nCol;
117656    *pnStr = nStr;
117657    *pazCol = azCol;
117658  }
117659
117660  return rc;
117661}
117662
117663/*
117664** This function is the implementation of both the xConnect and xCreate
117665** methods of the FTS3 virtual table.
117666**
117667** The argv[] array contains the following:
117668**
117669**   argv[0]   -> module name  ("fts3" or "fts4")
117670**   argv[1]   -> database name
117671**   argv[2]   -> table name
117672**   argv[...] -> "column name" and other module argument fields.
117673*/
117674static int fts3InitVtab(
117675  int isCreate,                   /* True for xCreate, false for xConnect */
117676  sqlite3 *db,                    /* The SQLite database connection */
117677  void *pAux,                     /* Hash table containing tokenizers */
117678  int argc,                       /* Number of elements in argv array */
117679  const char * const *argv,       /* xCreate/xConnect argument array */
117680  sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
117681  char **pzErr                    /* Write any error message here */
117682){
117683  Fts3Hash *pHash = (Fts3Hash *)pAux;
117684  Fts3Table *p = 0;               /* Pointer to allocated vtab */
117685  int rc = SQLITE_OK;             /* Return code */
117686  int i;                          /* Iterator variable */
117687  int nByte;                      /* Size of allocation used for *p */
117688  int iCol;                       /* Column index */
117689  int nString = 0;                /* Bytes required to hold all column names */
117690  int nCol = 0;                   /* Number of columns in the FTS table */
117691  char *zCsr;                     /* Space for holding column names */
117692  int nDb;                        /* Bytes required to hold database name */
117693  int nName;                      /* Bytes required to hold table name */
117694  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
117695  const char **aCol;              /* Array of column names */
117696  sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
117697
117698  int nIndex;                     /* Size of aIndex[] array */
117699  struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
117700
117701  /* The results of parsing supported FTS4 key=value options: */
117702  int bNoDocsize = 0;             /* True to omit %_docsize table */
117703  int bDescIdx = 0;               /* True to store descending indexes */
117704  char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
117705  char *zCompress = 0;            /* compress=? parameter (or NULL) */
117706  char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
117707  char *zContent = 0;             /* content=? parameter (or NULL) */
117708  char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
117709
117710  assert( strlen(argv[0])==4 );
117711  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
117712       || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
117713  );
117714
117715  nDb = (int)strlen(argv[1]) + 1;
117716  nName = (int)strlen(argv[2]) + 1;
117717
117718  aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
117719  if( !aCol ) return SQLITE_NOMEM;
117720  memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
117721
117722  /* Loop through all of the arguments passed by the user to the FTS3/4
117723  ** module (i.e. all the column names and special arguments). This loop
117724  ** does the following:
117725  **
117726  **   + Figures out the number of columns the FTSX table will have, and
117727  **     the number of bytes of space that must be allocated to store copies
117728  **     of the column names.
117729  **
117730  **   + If there is a tokenizer specification included in the arguments,
117731  **     initializes the tokenizer pTokenizer.
117732  */
117733  for(i=3; rc==SQLITE_OK && i<argc; i++){
117734    char const *z = argv[i];
117735    int nKey;
117736    char *zVal;
117737
117738    /* Check if this is a tokenizer specification */
117739    if( !pTokenizer
117740     && strlen(z)>8
117741     && 0==sqlite3_strnicmp(z, "tokenize", 8)
117742     && 0==sqlite3Fts3IsIdChar(z[8])
117743    ){
117744      rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
117745    }
117746
117747    /* Check if it is an FTS4 special argument. */
117748    else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
117749      struct Fts4Option {
117750        const char *zOpt;
117751        int nOpt;
117752      } aFts4Opt[] = {
117753        { "matchinfo",   9 },     /* 0 -> MATCHINFO */
117754        { "prefix",      6 },     /* 1 -> PREFIX */
117755        { "compress",    8 },     /* 2 -> COMPRESS */
117756        { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
117757        { "order",       5 },     /* 4 -> ORDER */
117758        { "content",     7 },     /* 5 -> CONTENT */
117759        { "languageid", 10 }      /* 6 -> LANGUAGEID */
117760      };
117761
117762      int iOpt;
117763      if( !zVal ){
117764        rc = SQLITE_NOMEM;
117765      }else{
117766        for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
117767          struct Fts4Option *pOp = &aFts4Opt[iOpt];
117768          if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
117769            break;
117770          }
117771        }
117772        if( iOpt==SizeofArray(aFts4Opt) ){
117773          *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
117774          rc = SQLITE_ERROR;
117775        }else{
117776          switch( iOpt ){
117777            case 0:               /* MATCHINFO */
117778              if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
117779                *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
117780                rc = SQLITE_ERROR;
117781              }
117782              bNoDocsize = 1;
117783              break;
117784
117785            case 1:               /* PREFIX */
117786              sqlite3_free(zPrefix);
117787              zPrefix = zVal;
117788              zVal = 0;
117789              break;
117790
117791            case 2:               /* COMPRESS */
117792              sqlite3_free(zCompress);
117793              zCompress = zVal;
117794              zVal = 0;
117795              break;
117796
117797            case 3:               /* UNCOMPRESS */
117798              sqlite3_free(zUncompress);
117799              zUncompress = zVal;
117800              zVal = 0;
117801              break;
117802
117803            case 4:               /* ORDER */
117804              if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
117805               && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
117806              ){
117807                *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
117808                rc = SQLITE_ERROR;
117809              }
117810              bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
117811              break;
117812
117813            case 5:              /* CONTENT */
117814              sqlite3_free(zContent);
117815              zContent = zVal;
117816              zVal = 0;
117817              break;
117818
117819            case 6:              /* LANGUAGEID */
117820              assert( iOpt==6 );
117821              sqlite3_free(zLanguageid);
117822              zLanguageid = zVal;
117823              zVal = 0;
117824              break;
117825          }
117826        }
117827        sqlite3_free(zVal);
117828      }
117829    }
117830
117831    /* Otherwise, the argument is a column name. */
117832    else {
117833      nString += (int)(strlen(z) + 1);
117834      aCol[nCol++] = z;
117835    }
117836  }
117837
117838  /* If a content=xxx option was specified, the following:
117839  **
117840  **   1. Ignore any compress= and uncompress= options.
117841  **
117842  **   2. If no column names were specified as part of the CREATE VIRTUAL
117843  **      TABLE statement, use all columns from the content table.
117844  */
117845  if( rc==SQLITE_OK && zContent ){
117846    sqlite3_free(zCompress);
117847    sqlite3_free(zUncompress);
117848    zCompress = 0;
117849    zUncompress = 0;
117850    if( nCol==0 ){
117851      sqlite3_free((void*)aCol);
117852      aCol = 0;
117853      rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
117854
117855      /* If a languageid= option was specified, remove the language id
117856      ** column from the aCol[] array. */
117857      if( rc==SQLITE_OK && zLanguageid ){
117858        int j;
117859        for(j=0; j<nCol; j++){
117860          if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
117861            int k;
117862            for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
117863            nCol--;
117864            break;
117865          }
117866        }
117867      }
117868    }
117869  }
117870  if( rc!=SQLITE_OK ) goto fts3_init_out;
117871
117872  if( nCol==0 ){
117873    assert( nString==0 );
117874    aCol[0] = "content";
117875    nString = 8;
117876    nCol = 1;
117877  }
117878
117879  if( pTokenizer==0 ){
117880    rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
117881    if( rc!=SQLITE_OK ) goto fts3_init_out;
117882  }
117883  assert( pTokenizer );
117884
117885  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
117886  if( rc==SQLITE_ERROR ){
117887    assert( zPrefix );
117888    *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
117889  }
117890  if( rc!=SQLITE_OK ) goto fts3_init_out;
117891
117892  /* Allocate and populate the Fts3Table structure. */
117893  nByte = sizeof(Fts3Table) +                  /* Fts3Table */
117894          nCol * sizeof(char *) +              /* azColumn */
117895          nIndex * sizeof(struct Fts3Index) +  /* aIndex */
117896          nName +                              /* zName */
117897          nDb +                                /* zDb */
117898          nString;                             /* Space for azColumn strings */
117899  p = (Fts3Table*)sqlite3_malloc(nByte);
117900  if( p==0 ){
117901    rc = SQLITE_NOMEM;
117902    goto fts3_init_out;
117903  }
117904  memset(p, 0, nByte);
117905  p->db = db;
117906  p->nColumn = nCol;
117907  p->nPendingData = 0;
117908  p->azColumn = (char **)&p[1];
117909  p->pTokenizer = pTokenizer;
117910  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
117911  p->bHasDocsize = (isFts4 && bNoDocsize==0);
117912  p->bHasStat = isFts4;
117913  p->bDescIdx = bDescIdx;
117914  p->zContentTbl = zContent;
117915  p->zLanguageid = zLanguageid;
117916  zContent = 0;
117917  zLanguageid = 0;
117918  TESTONLY( p->inTransaction = -1 );
117919  TESTONLY( p->mxSavepoint = -1 );
117920
117921  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
117922  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
117923  p->nIndex = nIndex;
117924  for(i=0; i<nIndex; i++){
117925    fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
117926  }
117927
117928  /* Fill in the zName and zDb fields of the vtab structure. */
117929  zCsr = (char *)&p->aIndex[nIndex];
117930  p->zName = zCsr;
117931  memcpy(zCsr, argv[2], nName);
117932  zCsr += nName;
117933  p->zDb = zCsr;
117934  memcpy(zCsr, argv[1], nDb);
117935  zCsr += nDb;
117936
117937  /* Fill in the azColumn array */
117938  for(iCol=0; iCol<nCol; iCol++){
117939    char *z;
117940    int n = 0;
117941    z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
117942    memcpy(zCsr, z, n);
117943    zCsr[n] = '\0';
117944    sqlite3Fts3Dequote(zCsr);
117945    p->azColumn[iCol] = zCsr;
117946    zCsr += n+1;
117947    assert( zCsr <= &((char *)p)[nByte] );
117948  }
117949
117950  if( (zCompress==0)!=(zUncompress==0) ){
117951    char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
117952    rc = SQLITE_ERROR;
117953    *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
117954  }
117955  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
117956  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
117957  if( rc!=SQLITE_OK ) goto fts3_init_out;
117958
117959  /* If this is an xCreate call, create the underlying tables in the
117960  ** database. TODO: For xConnect(), it could verify that said tables exist.
117961  */
117962  if( isCreate ){
117963    rc = fts3CreateTables(p);
117964  }
117965
117966  /* Figure out the page-size for the database. This is required in order to
117967  ** estimate the cost of loading large doclists from the database.  */
117968  fts3DatabasePageSize(&rc, p);
117969  p->nNodeSize = p->nPgsz-35;
117970
117971  /* Declare the table schema to SQLite. */
117972  fts3DeclareVtab(&rc, p);
117973
117974fts3_init_out:
117975  sqlite3_free(zPrefix);
117976  sqlite3_free(aIndex);
117977  sqlite3_free(zCompress);
117978  sqlite3_free(zUncompress);
117979  sqlite3_free(zContent);
117980  sqlite3_free(zLanguageid);
117981  sqlite3_free((void *)aCol);
117982  if( rc!=SQLITE_OK ){
117983    if( p ){
117984      fts3DisconnectMethod((sqlite3_vtab *)p);
117985    }else if( pTokenizer ){
117986      pTokenizer->pModule->xDestroy(pTokenizer);
117987    }
117988  }else{
117989    assert( p->pSegments==0 );
117990    *ppVTab = &p->base;
117991  }
117992  return rc;
117993}
117994
117995/*
117996** The xConnect() and xCreate() methods for the virtual table. All the
117997** work is done in function fts3InitVtab().
117998*/
117999static int fts3ConnectMethod(
118000  sqlite3 *db,                    /* Database connection */
118001  void *pAux,                     /* Pointer to tokenizer hash table */
118002  int argc,                       /* Number of elements in argv array */
118003  const char * const *argv,       /* xCreate/xConnect argument array */
118004  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
118005  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
118006){
118007  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
118008}
118009static int fts3CreateMethod(
118010  sqlite3 *db,                    /* Database connection */
118011  void *pAux,                     /* Pointer to tokenizer hash table */
118012  int argc,                       /* Number of elements in argv array */
118013  const char * const *argv,       /* xCreate/xConnect argument array */
118014  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
118015  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
118016){
118017  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
118018}
118019
118020/*
118021** Implementation of the xBestIndex method for FTS3 tables. There
118022** are three possible strategies, in order of preference:
118023**
118024**   1. Direct lookup by rowid or docid.
118025**   2. Full-text search using a MATCH operator on a non-docid column.
118026**   3. Linear scan of %_content table.
118027*/
118028static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
118029  Fts3Table *p = (Fts3Table *)pVTab;
118030  int i;                          /* Iterator variable */
118031  int iCons = -1;                 /* Index of constraint to use */
118032  int iLangidCons = -1;           /* Index of langid=x constraint, if present */
118033
118034  /* By default use a full table scan. This is an expensive option,
118035  ** so search through the constraints to see if a more efficient
118036  ** strategy is possible.
118037  */
118038  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
118039  pInfo->estimatedCost = 500000;
118040  for(i=0; i<pInfo->nConstraint; i++){
118041    struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
118042    if( pCons->usable==0 ) continue;
118043
118044    /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
118045    if( iCons<0
118046     && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
118047     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
118048    ){
118049      pInfo->idxNum = FTS3_DOCID_SEARCH;
118050      pInfo->estimatedCost = 1.0;
118051      iCons = i;
118052    }
118053
118054    /* A MATCH constraint. Use a full-text search.
118055    **
118056    ** If there is more than one MATCH constraint available, use the first
118057    ** one encountered. If there is both a MATCH constraint and a direct
118058    ** rowid/docid lookup, prefer the MATCH strategy. This is done even
118059    ** though the rowid/docid lookup is faster than a MATCH query, selecting
118060    ** it would lead to an "unable to use function MATCH in the requested
118061    ** context" error.
118062    */
118063    if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
118064     && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
118065    ){
118066      pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
118067      pInfo->estimatedCost = 2.0;
118068      iCons = i;
118069    }
118070
118071    /* Equality constraint on the langid column */
118072    if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
118073     && pCons->iColumn==p->nColumn + 2
118074    ){
118075      iLangidCons = i;
118076    }
118077  }
118078
118079  if( iCons>=0 ){
118080    pInfo->aConstraintUsage[iCons].argvIndex = 1;
118081    pInfo->aConstraintUsage[iCons].omit = 1;
118082  }
118083  if( iLangidCons>=0 ){
118084    pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
118085  }
118086
118087  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
118088  ** docid) order. Both ascending and descending are possible.
118089  */
118090  if( pInfo->nOrderBy==1 ){
118091    struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
118092    if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
118093      if( pOrder->desc ){
118094        pInfo->idxStr = "DESC";
118095      }else{
118096        pInfo->idxStr = "ASC";
118097      }
118098      pInfo->orderByConsumed = 1;
118099    }
118100  }
118101
118102  assert( p->pSegments==0 );
118103  return SQLITE_OK;
118104}
118105
118106/*
118107** Implementation of xOpen method.
118108*/
118109static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
118110  sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
118111
118112  UNUSED_PARAMETER(pVTab);
118113
118114  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
118115  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
118116  ** if the allocation fails, return SQLITE_NOMEM.
118117  */
118118  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
118119  if( !pCsr ){
118120    return SQLITE_NOMEM;
118121  }
118122  memset(pCsr, 0, sizeof(Fts3Cursor));
118123  return SQLITE_OK;
118124}
118125
118126/*
118127** Close the cursor.  For additional information see the documentation
118128** on the xClose method of the virtual table interface.
118129*/
118130static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
118131  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
118132  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
118133  sqlite3_finalize(pCsr->pStmt);
118134  sqlite3Fts3ExprFree(pCsr->pExpr);
118135  sqlite3Fts3FreeDeferredTokens(pCsr);
118136  sqlite3_free(pCsr->aDoclist);
118137  sqlite3_free(pCsr->aMatchinfo);
118138  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
118139  sqlite3_free(pCsr);
118140  return SQLITE_OK;
118141}
118142
118143/*
118144** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
118145** compose and prepare an SQL statement of the form:
118146**
118147**    "SELECT <columns> FROM %_content WHERE rowid = ?"
118148**
118149** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
118150** it. If an error occurs, return an SQLite error code.
118151**
118152** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
118153*/
118154static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
118155  int rc = SQLITE_OK;
118156  if( pCsr->pStmt==0 ){
118157    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
118158    char *zSql;
118159    zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
118160    if( !zSql ) return SQLITE_NOMEM;
118161    rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
118162    sqlite3_free(zSql);
118163  }
118164  *ppStmt = pCsr->pStmt;
118165  return rc;
118166}
118167
118168/*
118169** Position the pCsr->pStmt statement so that it is on the row
118170** of the %_content table that contains the last match.  Return
118171** SQLITE_OK on success.
118172*/
118173static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
118174  int rc = SQLITE_OK;
118175  if( pCsr->isRequireSeek ){
118176    sqlite3_stmt *pStmt = 0;
118177
118178    rc = fts3CursorSeekStmt(pCsr, &pStmt);
118179    if( rc==SQLITE_OK ){
118180      sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
118181      pCsr->isRequireSeek = 0;
118182      if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
118183        return SQLITE_OK;
118184      }else{
118185        rc = sqlite3_reset(pCsr->pStmt);
118186        if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
118187          /* If no row was found and no error has occured, then the %_content
118188          ** table is missing a row that is present in the full-text index.
118189          ** The data structures are corrupt.  */
118190          rc = FTS_CORRUPT_VTAB;
118191          pCsr->isEof = 1;
118192        }
118193      }
118194    }
118195  }
118196
118197  if( rc!=SQLITE_OK && pContext ){
118198    sqlite3_result_error_code(pContext, rc);
118199  }
118200  return rc;
118201}
118202
118203/*
118204** This function is used to process a single interior node when searching
118205** a b-tree for a term or term prefix. The node data is passed to this
118206** function via the zNode/nNode parameters. The term to search for is
118207** passed in zTerm/nTerm.
118208**
118209** If piFirst is not NULL, then this function sets *piFirst to the blockid
118210** of the child node that heads the sub-tree that may contain the term.
118211**
118212** If piLast is not NULL, then *piLast is set to the right-most child node
118213** that heads a sub-tree that may contain a term for which zTerm/nTerm is
118214** a prefix.
118215**
118216** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
118217*/
118218static int fts3ScanInteriorNode(
118219  const char *zTerm,              /* Term to select leaves for */
118220  int nTerm,                      /* Size of term zTerm in bytes */
118221  const char *zNode,              /* Buffer containing segment interior node */
118222  int nNode,                      /* Size of buffer at zNode */
118223  sqlite3_int64 *piFirst,         /* OUT: Selected child node */
118224  sqlite3_int64 *piLast           /* OUT: Selected child node */
118225){
118226  int rc = SQLITE_OK;             /* Return code */
118227  const char *zCsr = zNode;       /* Cursor to iterate through node */
118228  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
118229  char *zBuffer = 0;              /* Buffer to load terms into */
118230  int nAlloc = 0;                 /* Size of allocated buffer */
118231  int isFirstTerm = 1;            /* True when processing first term on page */
118232  sqlite3_int64 iChild;           /* Block id of child node to descend to */
118233
118234  /* Skip over the 'height' varint that occurs at the start of every
118235  ** interior node. Then load the blockid of the left-child of the b-tree
118236  ** node into variable iChild.
118237  **
118238  ** Even if the data structure on disk is corrupted, this (reading two
118239  ** varints from the buffer) does not risk an overread. If zNode is a
118240  ** root node, then the buffer comes from a SELECT statement. SQLite does
118241  ** not make this guarantee explicitly, but in practice there are always
118242  ** either more than 20 bytes of allocated space following the nNode bytes of
118243  ** contents, or two zero bytes. Or, if the node is read from the %_segments
118244  ** table, then there are always 20 bytes of zeroed padding following the
118245  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
118246  */
118247  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
118248  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
118249  if( zCsr>zEnd ){
118250    return FTS_CORRUPT_VTAB;
118251  }
118252
118253  while( zCsr<zEnd && (piFirst || piLast) ){
118254    int cmp;                      /* memcmp() result */
118255    int nSuffix;                  /* Size of term suffix */
118256    int nPrefix = 0;              /* Size of term prefix */
118257    int nBuffer;                  /* Total term size */
118258
118259    /* Load the next term on the node into zBuffer. Use realloc() to expand
118260    ** the size of zBuffer if required.  */
118261    if( !isFirstTerm ){
118262      zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
118263    }
118264    isFirstTerm = 0;
118265    zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
118266
118267    if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
118268      rc = FTS_CORRUPT_VTAB;
118269      goto finish_scan;
118270    }
118271    if( nPrefix+nSuffix>nAlloc ){
118272      char *zNew;
118273      nAlloc = (nPrefix+nSuffix) * 2;
118274      zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
118275      if( !zNew ){
118276        rc = SQLITE_NOMEM;
118277        goto finish_scan;
118278      }
118279      zBuffer = zNew;
118280    }
118281    assert( zBuffer );
118282    memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
118283    nBuffer = nPrefix + nSuffix;
118284    zCsr += nSuffix;
118285
118286    /* Compare the term we are searching for with the term just loaded from
118287    ** the interior node. If the specified term is greater than or equal
118288    ** to the term from the interior node, then all terms on the sub-tree
118289    ** headed by node iChild are smaller than zTerm. No need to search
118290    ** iChild.
118291    **
118292    ** If the interior node term is larger than the specified term, then
118293    ** the tree headed by iChild may contain the specified term.
118294    */
118295    cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
118296    if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
118297      *piFirst = iChild;
118298      piFirst = 0;
118299    }
118300
118301    if( piLast && cmp<0 ){
118302      *piLast = iChild;
118303      piLast = 0;
118304    }
118305
118306    iChild++;
118307  };
118308
118309  if( piFirst ) *piFirst = iChild;
118310  if( piLast ) *piLast = iChild;
118311
118312 finish_scan:
118313  sqlite3_free(zBuffer);
118314  return rc;
118315}
118316
118317
118318/*
118319** The buffer pointed to by argument zNode (size nNode bytes) contains an
118320** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
118321** contains a term. This function searches the sub-tree headed by the zNode
118322** node for the range of leaf nodes that may contain the specified term
118323** or terms for which the specified term is a prefix.
118324**
118325** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
118326** left-most leaf node in the tree that may contain the specified term.
118327** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
118328** right-most leaf node that may contain a term for which the specified
118329** term is a prefix.
118330**
118331** It is possible that the range of returned leaf nodes does not contain
118332** the specified term or any terms for which it is a prefix. However, if the
118333** segment does contain any such terms, they are stored within the identified
118334** range. Because this function only inspects interior segment nodes (and
118335** never loads leaf nodes into memory), it is not possible to be sure.
118336**
118337** If an error occurs, an error code other than SQLITE_OK is returned.
118338*/
118339static int fts3SelectLeaf(
118340  Fts3Table *p,                   /* Virtual table handle */
118341  const char *zTerm,              /* Term to select leaves for */
118342  int nTerm,                      /* Size of term zTerm in bytes */
118343  const char *zNode,              /* Buffer containing segment interior node */
118344  int nNode,                      /* Size of buffer at zNode */
118345  sqlite3_int64 *piLeaf,          /* Selected leaf node */
118346  sqlite3_int64 *piLeaf2          /* Selected leaf node */
118347){
118348  int rc;                         /* Return code */
118349  int iHeight;                    /* Height of this node in tree */
118350
118351  assert( piLeaf || piLeaf2 );
118352
118353  sqlite3Fts3GetVarint32(zNode, &iHeight);
118354  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
118355  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
118356
118357  if( rc==SQLITE_OK && iHeight>1 ){
118358    char *zBlob = 0;              /* Blob read from %_segments table */
118359    int nBlob;                    /* Size of zBlob in bytes */
118360
118361    if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
118362      rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
118363      if( rc==SQLITE_OK ){
118364        rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
118365      }
118366      sqlite3_free(zBlob);
118367      piLeaf = 0;
118368      zBlob = 0;
118369    }
118370
118371    if( rc==SQLITE_OK ){
118372      rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
118373    }
118374    if( rc==SQLITE_OK ){
118375      rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
118376    }
118377    sqlite3_free(zBlob);
118378  }
118379
118380  return rc;
118381}
118382
118383/*
118384** This function is used to create delta-encoded serialized lists of FTS3
118385** varints. Each call to this function appends a single varint to a list.
118386*/
118387static void fts3PutDeltaVarint(
118388  char **pp,                      /* IN/OUT: Output pointer */
118389  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
118390  sqlite3_int64 iVal              /* Write this value to the list */
118391){
118392  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
118393  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
118394  *piPrev = iVal;
118395}
118396
118397/*
118398** When this function is called, *ppPoslist is assumed to point to the
118399** start of a position-list. After it returns, *ppPoslist points to the
118400** first byte after the position-list.
118401**
118402** A position list is list of positions (delta encoded) and columns for
118403** a single document record of a doclist.  So, in other words, this
118404** routine advances *ppPoslist so that it points to the next docid in
118405** the doclist, or to the first byte past the end of the doclist.
118406**
118407** If pp is not NULL, then the contents of the position list are copied
118408** to *pp. *pp is set to point to the first byte past the last byte copied
118409** before this function returns.
118410*/
118411static void fts3PoslistCopy(char **pp, char **ppPoslist){
118412  char *pEnd = *ppPoslist;
118413  char c = 0;
118414
118415  /* The end of a position list is marked by a zero encoded as an FTS3
118416  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
118417  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
118418  ** of some other, multi-byte, value.
118419  **
118420  ** The following while-loop moves pEnd to point to the first byte that is not
118421  ** immediately preceded by a byte with the 0x80 bit set. Then increments
118422  ** pEnd once more so that it points to the byte immediately following the
118423  ** last byte in the position-list.
118424  */
118425  while( *pEnd | c ){
118426    c = *pEnd++ & 0x80;
118427    testcase( c!=0 && (*pEnd)==0 );
118428  }
118429  pEnd++;  /* Advance past the POS_END terminator byte */
118430
118431  if( pp ){
118432    int n = (int)(pEnd - *ppPoslist);
118433    char *p = *pp;
118434    memcpy(p, *ppPoslist, n);
118435    p += n;
118436    *pp = p;
118437  }
118438  *ppPoslist = pEnd;
118439}
118440
118441/*
118442** When this function is called, *ppPoslist is assumed to point to the
118443** start of a column-list. After it returns, *ppPoslist points to the
118444** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
118445**
118446** A column-list is list of delta-encoded positions for a single column
118447** within a single document within a doclist.
118448**
118449** The column-list is terminated either by a POS_COLUMN varint (1) or
118450** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
118451** the POS_COLUMN or POS_END that terminates the column-list.
118452**
118453** If pp is not NULL, then the contents of the column-list are copied
118454** to *pp. *pp is set to point to the first byte past the last byte copied
118455** before this function returns.  The POS_COLUMN or POS_END terminator
118456** is not copied into *pp.
118457*/
118458static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
118459  char *pEnd = *ppPoslist;
118460  char c = 0;
118461
118462  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
118463  ** not part of a multi-byte varint.
118464  */
118465  while( 0xFE & (*pEnd | c) ){
118466    c = *pEnd++ & 0x80;
118467    testcase( c!=0 && ((*pEnd)&0xfe)==0 );
118468  }
118469  if( pp ){
118470    int n = (int)(pEnd - *ppPoslist);
118471    char *p = *pp;
118472    memcpy(p, *ppPoslist, n);
118473    p += n;
118474    *pp = p;
118475  }
118476  *ppPoslist = pEnd;
118477}
118478
118479/*
118480** Value used to signify the end of an position-list. This is safe because
118481** it is not possible to have a document with 2^31 terms.
118482*/
118483#define POSITION_LIST_END 0x7fffffff
118484
118485/*
118486** This function is used to help parse position-lists. When this function is
118487** called, *pp may point to the start of the next varint in the position-list
118488** being parsed, or it may point to 1 byte past the end of the position-list
118489** (in which case **pp will be a terminator bytes POS_END (0) or
118490** (1)).
118491**
118492** If *pp points past the end of the current position-list, set *pi to
118493** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
118494** increment the current value of *pi by the value read, and set *pp to
118495** point to the next value before returning.
118496**
118497** Before calling this routine *pi must be initialized to the value of
118498** the previous position, or zero if we are reading the first position
118499** in the position-list.  Because positions are delta-encoded, the value
118500** of the previous position is needed in order to compute the value of
118501** the next position.
118502*/
118503static void fts3ReadNextPos(
118504  char **pp,                    /* IN/OUT: Pointer into position-list buffer */
118505  sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
118506){
118507  if( (**pp)&0xFE ){
118508    fts3GetDeltaVarint(pp, pi);
118509    *pi -= 2;
118510  }else{
118511    *pi = POSITION_LIST_END;
118512  }
118513}
118514
118515/*
118516** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
118517** the value of iCol encoded as a varint to *pp.   This will start a new
118518** column list.
118519**
118520** Set *pp to point to the byte just after the last byte written before
118521** returning (do not modify it if iCol==0). Return the total number of bytes
118522** written (0 if iCol==0).
118523*/
118524static int fts3PutColNumber(char **pp, int iCol){
118525  int n = 0;                      /* Number of bytes written */
118526  if( iCol ){
118527    char *p = *pp;                /* Output pointer */
118528    n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
118529    *p = 0x01;
118530    *pp = &p[n];
118531  }
118532  return n;
118533}
118534
118535/*
118536** Compute the union of two position lists.  The output written
118537** into *pp contains all positions of both *pp1 and *pp2 in sorted
118538** order and with any duplicates removed.  All pointers are
118539** updated appropriately.   The caller is responsible for insuring
118540** that there is enough space in *pp to hold the complete output.
118541*/
118542static void fts3PoslistMerge(
118543  char **pp,                      /* Output buffer */
118544  char **pp1,                     /* Left input list */
118545  char **pp2                      /* Right input list */
118546){
118547  char *p = *pp;
118548  char *p1 = *pp1;
118549  char *p2 = *pp2;
118550
118551  while( *p1 || *p2 ){
118552    int iCol1;         /* The current column index in pp1 */
118553    int iCol2;         /* The current column index in pp2 */
118554
118555    if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
118556    else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
118557    else iCol1 = 0;
118558
118559    if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
118560    else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
118561    else iCol2 = 0;
118562
118563    if( iCol1==iCol2 ){
118564      sqlite3_int64 i1 = 0;       /* Last position from pp1 */
118565      sqlite3_int64 i2 = 0;       /* Last position from pp2 */
118566      sqlite3_int64 iPrev = 0;
118567      int n = fts3PutColNumber(&p, iCol1);
118568      p1 += n;
118569      p2 += n;
118570
118571      /* At this point, both p1 and p2 point to the start of column-lists
118572      ** for the same column (the column with index iCol1 and iCol2).
118573      ** A column-list is a list of non-negative delta-encoded varints, each
118574      ** incremented by 2 before being stored. Each list is terminated by a
118575      ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
118576      ** and writes the results to buffer p. p is left pointing to the byte
118577      ** after the list written. No terminator (POS_END or POS_COLUMN) is
118578      ** written to the output.
118579      */
118580      fts3GetDeltaVarint(&p1, &i1);
118581      fts3GetDeltaVarint(&p2, &i2);
118582      do {
118583        fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
118584        iPrev -= 2;
118585        if( i1==i2 ){
118586          fts3ReadNextPos(&p1, &i1);
118587          fts3ReadNextPos(&p2, &i2);
118588        }else if( i1<i2 ){
118589          fts3ReadNextPos(&p1, &i1);
118590        }else{
118591          fts3ReadNextPos(&p2, &i2);
118592        }
118593      }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
118594    }else if( iCol1<iCol2 ){
118595      p1 += fts3PutColNumber(&p, iCol1);
118596      fts3ColumnlistCopy(&p, &p1);
118597    }else{
118598      p2 += fts3PutColNumber(&p, iCol2);
118599      fts3ColumnlistCopy(&p, &p2);
118600    }
118601  }
118602
118603  *p++ = POS_END;
118604  *pp = p;
118605  *pp1 = p1 + 1;
118606  *pp2 = p2 + 1;
118607}
118608
118609/*
118610** This function is used to merge two position lists into one. When it is
118611** called, *pp1 and *pp2 must both point to position lists. A position-list is
118612** the part of a doclist that follows each document id. For example, if a row
118613** contains:
118614**
118615**     'a b c'|'x y z'|'a b b a'
118616**
118617** Then the position list for this row for token 'b' would consist of:
118618**
118619**     0x02 0x01 0x02 0x03 0x03 0x00
118620**
118621** When this function returns, both *pp1 and *pp2 are left pointing to the
118622** byte following the 0x00 terminator of their respective position lists.
118623**
118624** If isSaveLeft is 0, an entry is added to the output position list for
118625** each position in *pp2 for which there exists one or more positions in
118626** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
118627** when the *pp1 token appears before the *pp2 token, but not more than nToken
118628** slots before it.
118629**
118630** e.g. nToken==1 searches for adjacent positions.
118631*/
118632static int fts3PoslistPhraseMerge(
118633  char **pp,                      /* IN/OUT: Preallocated output buffer */
118634  int nToken,                     /* Maximum difference in token positions */
118635  int isSaveLeft,                 /* Save the left position */
118636  int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
118637  char **pp1,                     /* IN/OUT: Left input list */
118638  char **pp2                      /* IN/OUT: Right input list */
118639){
118640  char *p = *pp;
118641  char *p1 = *pp1;
118642  char *p2 = *pp2;
118643  int iCol1 = 0;
118644  int iCol2 = 0;
118645
118646  /* Never set both isSaveLeft and isExact for the same invocation. */
118647  assert( isSaveLeft==0 || isExact==0 );
118648
118649  assert( p!=0 && *p1!=0 && *p2!=0 );
118650  if( *p1==POS_COLUMN ){
118651    p1++;
118652    p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
118653  }
118654  if( *p2==POS_COLUMN ){
118655    p2++;
118656    p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
118657  }
118658
118659  while( 1 ){
118660    if( iCol1==iCol2 ){
118661      char *pSave = p;
118662      sqlite3_int64 iPrev = 0;
118663      sqlite3_int64 iPos1 = 0;
118664      sqlite3_int64 iPos2 = 0;
118665
118666      if( iCol1 ){
118667        *p++ = POS_COLUMN;
118668        p += sqlite3Fts3PutVarint(p, iCol1);
118669      }
118670
118671      assert( *p1!=POS_END && *p1!=POS_COLUMN );
118672      assert( *p2!=POS_END && *p2!=POS_COLUMN );
118673      fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118674      fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118675
118676      while( 1 ){
118677        if( iPos2==iPos1+nToken
118678         || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
118679        ){
118680          sqlite3_int64 iSave;
118681          iSave = isSaveLeft ? iPos1 : iPos2;
118682          fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
118683          pSave = 0;
118684          assert( p );
118685        }
118686        if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
118687          if( (*p2&0xFE)==0 ) break;
118688          fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
118689        }else{
118690          if( (*p1&0xFE)==0 ) break;
118691          fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
118692        }
118693      }
118694
118695      if( pSave ){
118696        assert( pp && p );
118697        p = pSave;
118698      }
118699
118700      fts3ColumnlistCopy(0, &p1);
118701      fts3ColumnlistCopy(0, &p2);
118702      assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
118703      if( 0==*p1 || 0==*p2 ) break;
118704
118705      p1++;
118706      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
118707      p2++;
118708      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
118709    }
118710
118711    /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
118712    ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
118713    ** end of the position list, or the 0x01 that precedes the next
118714    ** column-number in the position list.
118715    */
118716    else if( iCol1<iCol2 ){
118717      fts3ColumnlistCopy(0, &p1);
118718      if( 0==*p1 ) break;
118719      p1++;
118720      p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
118721    }else{
118722      fts3ColumnlistCopy(0, &p2);
118723      if( 0==*p2 ) break;
118724      p2++;
118725      p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
118726    }
118727  }
118728
118729  fts3PoslistCopy(0, &p2);
118730  fts3PoslistCopy(0, &p1);
118731  *pp1 = p1;
118732  *pp2 = p2;
118733  if( *pp==p ){
118734    return 0;
118735  }
118736  *p++ = 0x00;
118737  *pp = p;
118738  return 1;
118739}
118740
118741/*
118742** Merge two position-lists as required by the NEAR operator. The argument
118743** position lists correspond to the left and right phrases of an expression
118744** like:
118745**
118746**     "phrase 1" NEAR "phrase number 2"
118747**
118748** Position list *pp1 corresponds to the left-hand side of the NEAR
118749** expression and *pp2 to the right. As usual, the indexes in the position
118750** lists are the offsets of the last token in each phrase (tokens "1" and "2"
118751** in the example above).
118752**
118753** The output position list - written to *pp - is a copy of *pp2 with those
118754** entries that are not sufficiently NEAR entries in *pp1 removed.
118755*/
118756static int fts3PoslistNearMerge(
118757  char **pp,                      /* Output buffer */
118758  char *aTmp,                     /* Temporary buffer space */
118759  int nRight,                     /* Maximum difference in token positions */
118760  int nLeft,                      /* Maximum difference in token positions */
118761  char **pp1,                     /* IN/OUT: Left input list */
118762  char **pp2                      /* IN/OUT: Right input list */
118763){
118764  char *p1 = *pp1;
118765  char *p2 = *pp2;
118766
118767  char *pTmp1 = aTmp;
118768  char *pTmp2;
118769  char *aTmp2;
118770  int res = 1;
118771
118772  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
118773  aTmp2 = pTmp2 = pTmp1;
118774  *pp1 = p1;
118775  *pp2 = p2;
118776  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
118777  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
118778    fts3PoslistMerge(pp, &aTmp, &aTmp2);
118779  }else if( pTmp1!=aTmp ){
118780    fts3PoslistCopy(pp, &aTmp);
118781  }else if( pTmp2!=aTmp2 ){
118782    fts3PoslistCopy(pp, &aTmp2);
118783  }else{
118784    res = 0;
118785  }
118786
118787  return res;
118788}
118789
118790/*
118791** An instance of this function is used to merge together the (potentially
118792** large number of) doclists for each term that matches a prefix query.
118793** See function fts3TermSelectMerge() for details.
118794*/
118795typedef struct TermSelect TermSelect;
118796struct TermSelect {
118797  char *aaOutput[16];             /* Malloc'd output buffers */
118798  int anOutput[16];               /* Size each output buffer in bytes */
118799};
118800
118801/*
118802** This function is used to read a single varint from a buffer. Parameter
118803** pEnd points 1 byte past the end of the buffer. When this function is
118804** called, if *pp points to pEnd or greater, then the end of the buffer
118805** has been reached. In this case *pp is set to 0 and the function returns.
118806**
118807** If *pp does not point to or past pEnd, then a single varint is read
118808** from *pp. *pp is then set to point 1 byte past the end of the read varint.
118809**
118810** If bDescIdx is false, the value read is added to *pVal before returning.
118811** If it is true, the value read is subtracted from *pVal before this
118812** function returns.
118813*/
118814static void fts3GetDeltaVarint3(
118815  char **pp,                      /* IN/OUT: Point to read varint from */
118816  char *pEnd,                     /* End of buffer */
118817  int bDescIdx,                   /* True if docids are descending */
118818  sqlite3_int64 *pVal             /* IN/OUT: Integer value */
118819){
118820  if( *pp>=pEnd ){
118821    *pp = 0;
118822  }else{
118823    sqlite3_int64 iVal;
118824    *pp += sqlite3Fts3GetVarint(*pp, &iVal);
118825    if( bDescIdx ){
118826      *pVal -= iVal;
118827    }else{
118828      *pVal += iVal;
118829    }
118830  }
118831}
118832
118833/*
118834** This function is used to write a single varint to a buffer. The varint
118835** is written to *pp. Before returning, *pp is set to point 1 byte past the
118836** end of the value written.
118837**
118838** If *pbFirst is zero when this function is called, the value written to
118839** the buffer is that of parameter iVal.
118840**
118841** If *pbFirst is non-zero when this function is called, then the value
118842** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
118843** (if bDescIdx is non-zero).
118844**
118845** Before returning, this function always sets *pbFirst to 1 and *piPrev
118846** to the value of parameter iVal.
118847*/
118848static void fts3PutDeltaVarint3(
118849  char **pp,                      /* IN/OUT: Output pointer */
118850  int bDescIdx,                   /* True for descending docids */
118851  sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
118852  int *pbFirst,                   /* IN/OUT: True after first int written */
118853  sqlite3_int64 iVal              /* Write this value to the list */
118854){
118855  sqlite3_int64 iWrite;
118856  if( bDescIdx==0 || *pbFirst==0 ){
118857    iWrite = iVal - *piPrev;
118858  }else{
118859    iWrite = *piPrev - iVal;
118860  }
118861  assert( *pbFirst || *piPrev==0 );
118862  assert( *pbFirst==0 || iWrite>0 );
118863  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
118864  *piPrev = iVal;
118865  *pbFirst = 1;
118866}
118867
118868
118869/*
118870** This macro is used by various functions that merge doclists. The two
118871** arguments are 64-bit docid values. If the value of the stack variable
118872** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
118873** Otherwise, (i2-i1).
118874**
118875** Using this makes it easier to write code that can merge doclists that are
118876** sorted in either ascending or descending order.
118877*/
118878#define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
118879
118880/*
118881** This function does an "OR" merge of two doclists (output contains all
118882** positions contained in either argument doclist). If the docids in the
118883** input doclists are sorted in ascending order, parameter bDescDoclist
118884** should be false. If they are sorted in ascending order, it should be
118885** passed a non-zero value.
118886**
118887** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
118888** containing the output doclist and SQLITE_OK is returned. In this case
118889** *pnOut is set to the number of bytes in the output doclist.
118890**
118891** If an error occurs, an SQLite error code is returned. The output values
118892** are undefined in this case.
118893*/
118894static int fts3DoclistOrMerge(
118895  int bDescDoclist,               /* True if arguments are desc */
118896  char *a1, int n1,               /* First doclist */
118897  char *a2, int n2,               /* Second doclist */
118898  char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
118899){
118900  sqlite3_int64 i1 = 0;
118901  sqlite3_int64 i2 = 0;
118902  sqlite3_int64 iPrev = 0;
118903  char *pEnd1 = &a1[n1];
118904  char *pEnd2 = &a2[n2];
118905  char *p1 = a1;
118906  char *p2 = a2;
118907  char *p;
118908  char *aOut;
118909  int bFirstOut = 0;
118910
118911  *paOut = 0;
118912  *pnOut = 0;
118913
118914  /* Allocate space for the output. Both the input and output doclists
118915  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
118916  ** then the first docid in each list is simply encoded as a varint. For
118917  ** each subsequent docid, the varint stored is the difference between the
118918  ** current and previous docid (a positive number - since the list is in
118919  ** ascending order).
118920  **
118921  ** The first docid written to the output is therefore encoded using the
118922  ** same number of bytes as it is in whichever of the input lists it is
118923  ** read from. And each subsequent docid read from the same input list
118924  ** consumes either the same or less bytes as it did in the input (since
118925  ** the difference between it and the previous value in the output must
118926  ** be a positive value less than or equal to the delta value read from
118927  ** the input list). The same argument applies to all but the first docid
118928  ** read from the 'other' list. And to the contents of all position lists
118929  ** that will be copied and merged from the input to the output.
118930  **
118931  ** However, if the first docid copied to the output is a negative number,
118932  ** then the encoding of the first docid from the 'other' input list may
118933  ** be larger in the output than it was in the input (since the delta value
118934  ** may be a larger positive integer than the actual docid).
118935  **
118936  ** The space required to store the output is therefore the sum of the
118937  ** sizes of the two inputs, plus enough space for exactly one of the input
118938  ** docids to grow.
118939  **
118940  ** A symetric argument may be made if the doclists are in descending
118941  ** order.
118942  */
118943  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
118944  if( !aOut ) return SQLITE_NOMEM;
118945
118946  p = aOut;
118947  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
118948  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
118949  while( p1 || p2 ){
118950    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
118951
118952    if( p2 && p1 && iDiff==0 ){
118953      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118954      fts3PoslistMerge(&p, &p1, &p2);
118955      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118956      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118957    }else if( !p2 || (p1 && iDiff<0) ){
118958      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
118959      fts3PoslistCopy(&p, &p1);
118960      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
118961    }else{
118962      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
118963      fts3PoslistCopy(&p, &p2);
118964      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
118965    }
118966  }
118967
118968  *paOut = aOut;
118969  *pnOut = (int)(p-aOut);
118970  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
118971  return SQLITE_OK;
118972}
118973
118974/*
118975** This function does a "phrase" merge of two doclists. In a phrase merge,
118976** the output contains a copy of each position from the right-hand input
118977** doclist for which there is a position in the left-hand input doclist
118978** exactly nDist tokens before it.
118979**
118980** If the docids in the input doclists are sorted in ascending order,
118981** parameter bDescDoclist should be false. If they are sorted in ascending
118982** order, it should be passed a non-zero value.
118983**
118984** The right-hand input doclist is overwritten by this function.
118985*/
118986static void fts3DoclistPhraseMerge(
118987  int bDescDoclist,               /* True if arguments are desc */
118988  int nDist,                      /* Distance from left to right (1=adjacent) */
118989  char *aLeft, int nLeft,         /* Left doclist */
118990  char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
118991){
118992  sqlite3_int64 i1 = 0;
118993  sqlite3_int64 i2 = 0;
118994  sqlite3_int64 iPrev = 0;
118995  char *pEnd1 = &aLeft[nLeft];
118996  char *pEnd2 = &aRight[*pnRight];
118997  char *p1 = aLeft;
118998  char *p2 = aRight;
118999  char *p;
119000  int bFirstOut = 0;
119001  char *aOut = aRight;
119002
119003  assert( nDist>0 );
119004
119005  p = aOut;
119006  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
119007  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
119008
119009  while( p1 && p2 ){
119010    sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
119011    if( iDiff==0 ){
119012      char *pSave = p;
119013      sqlite3_int64 iPrevSave = iPrev;
119014      int bFirstOutSave = bFirstOut;
119015
119016      fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
119017      if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
119018        p = pSave;
119019        iPrev = iPrevSave;
119020        bFirstOut = bFirstOutSave;
119021      }
119022      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
119023      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
119024    }else if( iDiff<0 ){
119025      fts3PoslistCopy(0, &p1);
119026      fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
119027    }else{
119028      fts3PoslistCopy(0, &p2);
119029      fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
119030    }
119031  }
119032
119033  *pnRight = (int)(p - aOut);
119034}
119035
119036/*
119037** Argument pList points to a position list nList bytes in size. This
119038** function checks to see if the position list contains any entries for
119039** a token in position 0 (of any column). If so, it writes argument iDelta
119040** to the output buffer pOut, followed by a position list consisting only
119041** of the entries from pList at position 0, and terminated by an 0x00 byte.
119042** The value returned is the number of bytes written to pOut (if any).
119043*/
119044SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
119045  sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
119046  char *pList,                    /* Position list (no 0x00 term) */
119047  int nList,                      /* Size of pList in bytes */
119048  char *pOut                      /* Write output here */
119049){
119050  int nOut = 0;
119051  int bWritten = 0;               /* True once iDelta has been written */
119052  char *p = pList;
119053  char *pEnd = &pList[nList];
119054
119055  if( *p!=0x01 ){
119056    if( *p==0x02 ){
119057      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
119058      pOut[nOut++] = 0x02;
119059      bWritten = 1;
119060    }
119061    fts3ColumnlistCopy(0, &p);
119062  }
119063
119064  while( p<pEnd && *p==0x01 ){
119065    sqlite3_int64 iCol;
119066    p++;
119067    p += sqlite3Fts3GetVarint(p, &iCol);
119068    if( *p==0x02 ){
119069      if( bWritten==0 ){
119070        nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
119071        bWritten = 1;
119072      }
119073      pOut[nOut++] = 0x01;
119074      nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
119075      pOut[nOut++] = 0x02;
119076    }
119077    fts3ColumnlistCopy(0, &p);
119078  }
119079  if( bWritten ){
119080    pOut[nOut++] = 0x00;
119081  }
119082
119083  return nOut;
119084}
119085
119086
119087/*
119088** Merge all doclists in the TermSelect.aaOutput[] array into a single
119089** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
119090** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
119091**
119092** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
119093** the responsibility of the caller to free any doclists left in the
119094** TermSelect.aaOutput[] array.
119095*/
119096static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
119097  char *aOut = 0;
119098  int nOut = 0;
119099  int i;
119100
119101  /* Loop through the doclists in the aaOutput[] array. Merge them all
119102  ** into a single doclist.
119103  */
119104  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
119105    if( pTS->aaOutput[i] ){
119106      if( !aOut ){
119107        aOut = pTS->aaOutput[i];
119108        nOut = pTS->anOutput[i];
119109        pTS->aaOutput[i] = 0;
119110      }else{
119111        int nNew;
119112        char *aNew;
119113
119114        int rc = fts3DoclistOrMerge(p->bDescIdx,
119115            pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
119116        );
119117        if( rc!=SQLITE_OK ){
119118          sqlite3_free(aOut);
119119          return rc;
119120        }
119121
119122        sqlite3_free(pTS->aaOutput[i]);
119123        sqlite3_free(aOut);
119124        pTS->aaOutput[i] = 0;
119125        aOut = aNew;
119126        nOut = nNew;
119127      }
119128    }
119129  }
119130
119131  pTS->aaOutput[0] = aOut;
119132  pTS->anOutput[0] = nOut;
119133  return SQLITE_OK;
119134}
119135
119136/*
119137** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
119138** as the first argument. The merge is an "OR" merge (see function
119139** fts3DoclistOrMerge() for details).
119140**
119141** This function is called with the doclist for each term that matches
119142** a queried prefix. It merges all these doclists into one, the doclist
119143** for the specified prefix. Since there can be a very large number of
119144** doclists to merge, the merging is done pair-wise using the TermSelect
119145** object.
119146**
119147** This function returns SQLITE_OK if the merge is successful, or an
119148** SQLite error code (SQLITE_NOMEM) if an error occurs.
119149*/
119150static int fts3TermSelectMerge(
119151  Fts3Table *p,                   /* FTS table handle */
119152  TermSelect *pTS,                /* TermSelect object to merge into */
119153  char *aDoclist,                 /* Pointer to doclist */
119154  int nDoclist                    /* Size of aDoclist in bytes */
119155){
119156  if( pTS->aaOutput[0]==0 ){
119157    /* If this is the first term selected, copy the doclist to the output
119158    ** buffer using memcpy(). */
119159    pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
119160    pTS->anOutput[0] = nDoclist;
119161    if( pTS->aaOutput[0] ){
119162      memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
119163    }else{
119164      return SQLITE_NOMEM;
119165    }
119166  }else{
119167    char *aMerge = aDoclist;
119168    int nMerge = nDoclist;
119169    int iOut;
119170
119171    for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
119172      if( pTS->aaOutput[iOut]==0 ){
119173        assert( iOut>0 );
119174        pTS->aaOutput[iOut] = aMerge;
119175        pTS->anOutput[iOut] = nMerge;
119176        break;
119177      }else{
119178        char *aNew;
119179        int nNew;
119180
119181        int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
119182            pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
119183        );
119184        if( rc!=SQLITE_OK ){
119185          if( aMerge!=aDoclist ) sqlite3_free(aMerge);
119186          return rc;
119187        }
119188
119189        if( aMerge!=aDoclist ) sqlite3_free(aMerge);
119190        sqlite3_free(pTS->aaOutput[iOut]);
119191        pTS->aaOutput[iOut] = 0;
119192
119193        aMerge = aNew;
119194        nMerge = nNew;
119195        if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
119196          pTS->aaOutput[iOut] = aMerge;
119197          pTS->anOutput[iOut] = nMerge;
119198        }
119199      }
119200    }
119201  }
119202  return SQLITE_OK;
119203}
119204
119205/*
119206** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
119207*/
119208static int fts3SegReaderCursorAppend(
119209  Fts3MultiSegReader *pCsr,
119210  Fts3SegReader *pNew
119211){
119212  if( (pCsr->nSegment%16)==0 ){
119213    Fts3SegReader **apNew;
119214    int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
119215    apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
119216    if( !apNew ){
119217      sqlite3Fts3SegReaderFree(pNew);
119218      return SQLITE_NOMEM;
119219    }
119220    pCsr->apSegment = apNew;
119221  }
119222  pCsr->apSegment[pCsr->nSegment++] = pNew;
119223  return SQLITE_OK;
119224}
119225
119226/*
119227** Add seg-reader objects to the Fts3MultiSegReader object passed as the
119228** 8th argument.
119229**
119230** This function returns SQLITE_OK if successful, or an SQLite error code
119231** otherwise.
119232*/
119233static int fts3SegReaderCursor(
119234  Fts3Table *p,                   /* FTS3 table handle */
119235  int iLangid,                    /* Language id */
119236  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
119237  int iLevel,                     /* Level of segments to scan */
119238  const char *zTerm,              /* Term to query for */
119239  int nTerm,                      /* Size of zTerm in bytes */
119240  int isPrefix,                   /* True for a prefix search */
119241  int isScan,                     /* True to scan from zTerm to EOF */
119242  Fts3MultiSegReader *pCsr        /* Cursor object to populate */
119243){
119244  int rc = SQLITE_OK;             /* Error code */
119245  sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
119246  int rc2;                        /* Result of sqlite3_reset() */
119247
119248  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
119249  ** for the pending-terms. If this is a scan, then this call must be being
119250  ** made by an fts4aux module, not an FTS table. In this case calling
119251  ** Fts3SegReaderPending might segfault, as the data structures used by
119252  ** fts4aux are not completely populated. So it's easiest to filter these
119253  ** calls out here.  */
119254  if( iLevel<0 && p->aIndex ){
119255    Fts3SegReader *pSeg = 0;
119256    rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
119257    if( rc==SQLITE_OK && pSeg ){
119258      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
119259    }
119260  }
119261
119262  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
119263    if( rc==SQLITE_OK ){
119264      rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
119265    }
119266
119267    while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
119268      Fts3SegReader *pSeg = 0;
119269
119270      /* Read the values returned by the SELECT into local variables. */
119271      sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
119272      sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
119273      sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
119274      int nRoot = sqlite3_column_bytes(pStmt, 4);
119275      char const *zRoot = sqlite3_column_blob(pStmt, 4);
119276
119277      /* If zTerm is not NULL, and this segment is not stored entirely on its
119278      ** root node, the range of leaves scanned can be reduced. Do this. */
119279      if( iStartBlock && zTerm ){
119280        sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
119281        rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
119282        if( rc!=SQLITE_OK ) goto finished;
119283        if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
119284      }
119285
119286      rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
119287          (isPrefix==0 && isScan==0),
119288          iStartBlock, iLeavesEndBlock,
119289          iEndBlock, zRoot, nRoot, &pSeg
119290      );
119291      if( rc!=SQLITE_OK ) goto finished;
119292      rc = fts3SegReaderCursorAppend(pCsr, pSeg);
119293    }
119294  }
119295
119296 finished:
119297  rc2 = sqlite3_reset(pStmt);
119298  if( rc==SQLITE_DONE ) rc = rc2;
119299
119300  return rc;
119301}
119302
119303/*
119304** Set up a cursor object for iterating through a full-text index or a
119305** single level therein.
119306*/
119307SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
119308  Fts3Table *p,                   /* FTS3 table handle */
119309  int iLangid,
119310  int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
119311  int iLevel,                     /* Level of segments to scan */
119312  const char *zTerm,              /* Term to query for */
119313  int nTerm,                      /* Size of zTerm in bytes */
119314  int isPrefix,                   /* True for a prefix search */
119315  int isScan,                     /* True to scan from zTerm to EOF */
119316  Fts3MultiSegReader *pCsr       /* Cursor object to populate */
119317){
119318  assert( iIndex>=0 && iIndex<p->nIndex );
119319  assert( iLevel==FTS3_SEGCURSOR_ALL
119320      ||  iLevel==FTS3_SEGCURSOR_PENDING
119321      ||  iLevel>=0
119322  );
119323  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
119324  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
119325  assert( isPrefix==0 || isScan==0 );
119326
119327  /* "isScan" is only set to true by the ft4aux module, an ordinary
119328  ** full-text tables. */
119329  assert( isScan==0 || p->aIndex==0 );
119330
119331  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
119332
119333  return fts3SegReaderCursor(
119334      p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
119335  );
119336}
119337
119338/*
119339** In addition to its current configuration, have the Fts3MultiSegReader
119340** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
119341**
119342** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
119343*/
119344static int fts3SegReaderCursorAddZero(
119345  Fts3Table *p,                   /* FTS virtual table handle */
119346  int iLangid,
119347  const char *zTerm,              /* Term to scan doclist of */
119348  int nTerm,                      /* Number of bytes in zTerm */
119349  Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
119350){
119351  return fts3SegReaderCursor(p,
119352      iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
119353  );
119354}
119355
119356/*
119357** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
119358** if isPrefix is true, to scan the doclist for all terms for which
119359** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
119360** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
119361** an SQLite error code.
119362**
119363** It is the responsibility of the caller to free this object by eventually
119364** passing it to fts3SegReaderCursorFree()
119365**
119366** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
119367** Output parameter *ppSegcsr is set to 0 if an error occurs.
119368*/
119369static int fts3TermSegReaderCursor(
119370  Fts3Cursor *pCsr,               /* Virtual table cursor handle */
119371  const char *zTerm,              /* Term to query for */
119372  int nTerm,                      /* Size of zTerm in bytes */
119373  int isPrefix,                   /* True for a prefix search */
119374  Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
119375){
119376  Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
119377  int rc = SQLITE_NOMEM;          /* Return code */
119378
119379  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
119380  if( pSegcsr ){
119381    int i;
119382    int bFound = 0;               /* True once an index has been found */
119383    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
119384
119385    if( isPrefix ){
119386      for(i=1; bFound==0 && i<p->nIndex; i++){
119387        if( p->aIndex[i].nPrefix==nTerm ){
119388          bFound = 1;
119389          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
119390              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
119391          );
119392          pSegcsr->bLookup = 1;
119393        }
119394      }
119395
119396      for(i=1; bFound==0 && i<p->nIndex; i++){
119397        if( p->aIndex[i].nPrefix==nTerm+1 ){
119398          bFound = 1;
119399          rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
119400              i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
119401          );
119402          if( rc==SQLITE_OK ){
119403            rc = fts3SegReaderCursorAddZero(
119404                p, pCsr->iLangid, zTerm, nTerm, pSegcsr
119405            );
119406          }
119407        }
119408      }
119409    }
119410
119411    if( bFound==0 ){
119412      rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
119413          0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
119414      );
119415      pSegcsr->bLookup = !isPrefix;
119416    }
119417  }
119418
119419  *ppSegcsr = pSegcsr;
119420  return rc;
119421}
119422
119423/*
119424** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
119425*/
119426static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
119427  sqlite3Fts3SegReaderFinish(pSegcsr);
119428  sqlite3_free(pSegcsr);
119429}
119430
119431/*
119432** This function retreives the doclist for the specified term (or term
119433** prefix) from the database.
119434*/
119435static int fts3TermSelect(
119436  Fts3Table *p,                   /* Virtual table handle */
119437  Fts3PhraseToken *pTok,          /* Token to query for */
119438  int iColumn,                    /* Column to query (or -ve for all columns) */
119439  int *pnOut,                     /* OUT: Size of buffer at *ppOut */
119440  char **ppOut                    /* OUT: Malloced result buffer */
119441){
119442  int rc;                         /* Return code */
119443  Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
119444  TermSelect tsc;                 /* Object for pair-wise doclist merging */
119445  Fts3SegFilter filter;           /* Segment term filter configuration */
119446
119447  pSegcsr = pTok->pSegcsr;
119448  memset(&tsc, 0, sizeof(TermSelect));
119449
119450  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
119451        | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
119452        | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
119453        | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
119454  filter.iCol = iColumn;
119455  filter.zTerm = pTok->z;
119456  filter.nTerm = pTok->n;
119457
119458  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
119459  while( SQLITE_OK==rc
119460      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
119461  ){
119462    rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
119463  }
119464
119465  if( rc==SQLITE_OK ){
119466    rc = fts3TermSelectFinishMerge(p, &tsc);
119467  }
119468  if( rc==SQLITE_OK ){
119469    *ppOut = tsc.aaOutput[0];
119470    *pnOut = tsc.anOutput[0];
119471  }else{
119472    int i;
119473    for(i=0; i<SizeofArray(tsc.aaOutput); i++){
119474      sqlite3_free(tsc.aaOutput[i]);
119475    }
119476  }
119477
119478  fts3SegReaderCursorFree(pSegcsr);
119479  pTok->pSegcsr = 0;
119480  return rc;
119481}
119482
119483/*
119484** This function counts the total number of docids in the doclist stored
119485** in buffer aList[], size nList bytes.
119486**
119487** If the isPoslist argument is true, then it is assumed that the doclist
119488** contains a position-list following each docid. Otherwise, it is assumed
119489** that the doclist is simply a list of docids stored as delta encoded
119490** varints.
119491*/
119492static int fts3DoclistCountDocids(char *aList, int nList){
119493  int nDoc = 0;                   /* Return value */
119494  if( aList ){
119495    char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
119496    char *p = aList;              /* Cursor */
119497    while( p<aEnd ){
119498      nDoc++;
119499      while( (*p++)&0x80 );     /* Skip docid varint */
119500      fts3PoslistCopy(0, &p);   /* Skip over position list */
119501    }
119502  }
119503
119504  return nDoc;
119505}
119506
119507/*
119508** Advance the cursor to the next row in the %_content table that
119509** matches the search criteria.  For a MATCH search, this will be
119510** the next row that matches. For a full-table scan, this will be
119511** simply the next row in the %_content table.  For a docid lookup,
119512** this routine simply sets the EOF flag.
119513**
119514** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
119515** even if we reach end-of-file.  The fts3EofMethod() will be called
119516** subsequently to determine whether or not an EOF was hit.
119517*/
119518static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
119519  int rc;
119520  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
119521  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
119522    if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
119523      pCsr->isEof = 1;
119524      rc = sqlite3_reset(pCsr->pStmt);
119525    }else{
119526      pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
119527      rc = SQLITE_OK;
119528    }
119529  }else{
119530    rc = fts3EvalNext((Fts3Cursor *)pCursor);
119531  }
119532  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119533  return rc;
119534}
119535
119536/*
119537** This is the xFilter interface for the virtual table.  See
119538** the virtual table xFilter method documentation for additional
119539** information.
119540**
119541** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
119542** the %_content table.
119543**
119544** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
119545** in the %_content table.
119546**
119547** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
119548** column on the left-hand side of the MATCH operator is column
119549** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
119550** side of the MATCH operator.
119551*/
119552static int fts3FilterMethod(
119553  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
119554  int idxNum,                     /* Strategy index */
119555  const char *idxStr,             /* Unused */
119556  int nVal,                       /* Number of elements in apVal */
119557  sqlite3_value **apVal           /* Arguments for the indexing scheme */
119558){
119559  int rc;
119560  char *zSql;                     /* SQL statement used to access %_content */
119561  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
119562  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
119563
119564  UNUSED_PARAMETER(idxStr);
119565  UNUSED_PARAMETER(nVal);
119566
119567  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
119568  assert( nVal==0 || nVal==1 || nVal==2 );
119569  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
119570  assert( p->pSegments==0 );
119571
119572  /* In case the cursor has been used before, clear it now. */
119573  sqlite3_finalize(pCsr->pStmt);
119574  sqlite3_free(pCsr->aDoclist);
119575  sqlite3Fts3ExprFree(pCsr->pExpr);
119576  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
119577
119578  if( idxStr ){
119579    pCsr->bDesc = (idxStr[0]=='D');
119580  }else{
119581    pCsr->bDesc = p->bDescIdx;
119582  }
119583  pCsr->eSearch = (i16)idxNum;
119584
119585  if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
119586    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
119587    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
119588
119589    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
119590      return SQLITE_NOMEM;
119591    }
119592
119593    pCsr->iLangid = 0;
119594    if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
119595
119596    rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
119597        p->azColumn, p->bHasStat, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr
119598    );
119599    if( rc!=SQLITE_OK ){
119600      if( rc==SQLITE_ERROR ){
119601        static const char *zErr = "malformed MATCH expression: [%s]";
119602        p->base.zErrMsg = sqlite3_mprintf(zErr, zQuery);
119603      }
119604      return rc;
119605    }
119606
119607    rc = sqlite3Fts3ReadLock(p);
119608    if( rc!=SQLITE_OK ) return rc;
119609
119610    rc = fts3EvalStart(pCsr);
119611
119612    sqlite3Fts3SegmentsClose(p);
119613    if( rc!=SQLITE_OK ) return rc;
119614    pCsr->pNextId = pCsr->aDoclist;
119615    pCsr->iPrevId = 0;
119616  }
119617
119618  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
119619  ** statement loops through all rows of the %_content table. For a
119620  ** full-text query or docid lookup, the statement retrieves a single
119621  ** row by docid.
119622  */
119623  if( idxNum==FTS3_FULLSCAN_SEARCH ){
119624    zSql = sqlite3_mprintf(
119625        "SELECT %s ORDER BY rowid %s",
119626        p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
119627    );
119628    if( zSql ){
119629      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
119630      sqlite3_free(zSql);
119631    }else{
119632      rc = SQLITE_NOMEM;
119633    }
119634  }else if( idxNum==FTS3_DOCID_SEARCH ){
119635    rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
119636    if( rc==SQLITE_OK ){
119637      rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
119638    }
119639  }
119640  if( rc!=SQLITE_OK ) return rc;
119641
119642  return fts3NextMethod(pCursor);
119643}
119644
119645/*
119646** This is the xEof method of the virtual table. SQLite calls this
119647** routine to find out if it has reached the end of a result set.
119648*/
119649static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
119650  return ((Fts3Cursor *)pCursor)->isEof;
119651}
119652
119653/*
119654** This is the xRowid method. The SQLite core calls this routine to
119655** retrieve the rowid for the current row of the result set. fts3
119656** exposes %_content.docid as the rowid for the virtual table. The
119657** rowid should be written to *pRowid.
119658*/
119659static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
119660  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
119661  *pRowid = pCsr->iPrevId;
119662  return SQLITE_OK;
119663}
119664
119665/*
119666** This is the xColumn method, called by SQLite to request a value from
119667** the row that the supplied cursor currently points to.
119668**
119669** If:
119670**
119671**   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
119672**   (iCol == p->nColumn)   -> Magic column with the same name as the table.
119673**   (iCol == p->nColumn+1) -> Docid column
119674**   (iCol == p->nColumn+2) -> Langid column
119675*/
119676static int fts3ColumnMethod(
119677  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
119678  sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
119679  int iCol                        /* Index of column to read value from */
119680){
119681  int rc = SQLITE_OK;             /* Return Code */
119682  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
119683  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
119684
119685  /* The column value supplied by SQLite must be in range. */
119686  assert( iCol>=0 && iCol<=p->nColumn+2 );
119687
119688  if( iCol==p->nColumn+1 ){
119689    /* This call is a request for the "docid" column. Since "docid" is an
119690    ** alias for "rowid", use the xRowid() method to obtain the value.
119691    */
119692    sqlite3_result_int64(pCtx, pCsr->iPrevId);
119693  }else if( iCol==p->nColumn ){
119694    /* The extra column whose name is the same as the table.
119695    ** Return a blob which is a pointer to the cursor.  */
119696    sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
119697  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
119698    sqlite3_result_int64(pCtx, pCsr->iLangid);
119699  }else{
119700    /* The requested column is either a user column (one that contains
119701    ** indexed data), or the language-id column.  */
119702    rc = fts3CursorSeek(0, pCsr);
119703
119704    if( rc==SQLITE_OK ){
119705      if( iCol==p->nColumn+2 ){
119706        int iLangid = 0;
119707        if( p->zLanguageid ){
119708          iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
119709        }
119710        sqlite3_result_int(pCtx, iLangid);
119711      }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
119712        sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
119713      }
119714    }
119715  }
119716
119717  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
119718  return rc;
119719}
119720
119721/*
119722** This function is the implementation of the xUpdate callback used by
119723** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
119724** inserted, updated or deleted.
119725*/
119726static int fts3UpdateMethod(
119727  sqlite3_vtab *pVtab,            /* Virtual table handle */
119728  int nArg,                       /* Size of argument array */
119729  sqlite3_value **apVal,          /* Array of arguments */
119730  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
119731){
119732  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
119733}
119734
119735/*
119736** Implementation of xSync() method. Flush the contents of the pending-terms
119737** hash-table to the database.
119738*/
119739static int fts3SyncMethod(sqlite3_vtab *pVtab){
119740  int rc = sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
119741  sqlite3Fts3SegmentsClose((Fts3Table *)pVtab);
119742  return rc;
119743}
119744
119745/*
119746** Implementation of xBegin() method. This is a no-op.
119747*/
119748static int fts3BeginMethod(sqlite3_vtab *pVtab){
119749  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119750  UNUSED_PARAMETER(pVtab);
119751  assert( p->pSegments==0 );
119752  assert( p->nPendingData==0 );
119753  assert( p->inTransaction!=1 );
119754  TESTONLY( p->inTransaction = 1 );
119755  TESTONLY( p->mxSavepoint = -1; );
119756  return SQLITE_OK;
119757}
119758
119759/*
119760** Implementation of xCommit() method. This is a no-op. The contents of
119761** the pending-terms hash-table have already been flushed into the database
119762** by fts3SyncMethod().
119763*/
119764static int fts3CommitMethod(sqlite3_vtab *pVtab){
119765  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
119766  UNUSED_PARAMETER(pVtab);
119767  assert( p->nPendingData==0 );
119768  assert( p->inTransaction!=0 );
119769  assert( p->pSegments==0 );
119770  TESTONLY( p->inTransaction = 0 );
119771  TESTONLY( p->mxSavepoint = -1; );
119772  return SQLITE_OK;
119773}
119774
119775/*
119776** Implementation of xRollback(). Discard the contents of the pending-terms
119777** hash-table. Any changes made to the database are reverted by SQLite.
119778*/
119779static int fts3RollbackMethod(sqlite3_vtab *pVtab){
119780  Fts3Table *p = (Fts3Table*)pVtab;
119781  sqlite3Fts3PendingTermsClear(p);
119782  assert( p->inTransaction!=0 );
119783  TESTONLY( p->inTransaction = 0 );
119784  TESTONLY( p->mxSavepoint = -1; );
119785  return SQLITE_OK;
119786}
119787
119788/*
119789** When called, *ppPoslist must point to the byte immediately following the
119790** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
119791** moves *ppPoslist so that it instead points to the first byte of the
119792** same position list.
119793*/
119794static void fts3ReversePoslist(char *pStart, char **ppPoslist){
119795  char *p = &(*ppPoslist)[-2];
119796  char c = 0;
119797
119798  while( p>pStart && (c=*p--)==0 );
119799  while( p>pStart && (*p & 0x80) | c ){
119800    c = *p--;
119801  }
119802  if( p>pStart ){ p = &p[2]; }
119803  while( *p++&0x80 );
119804  *ppPoslist = p;
119805}
119806
119807/*
119808** Helper function used by the implementation of the overloaded snippet(),
119809** offsets() and optimize() SQL functions.
119810**
119811** If the value passed as the third argument is a blob of size
119812** sizeof(Fts3Cursor*), then the blob contents are copied to the
119813** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
119814** message is written to context pContext and SQLITE_ERROR returned. The
119815** string passed via zFunc is used as part of the error message.
119816*/
119817static int fts3FunctionArg(
119818  sqlite3_context *pContext,      /* SQL function call context */
119819  const char *zFunc,              /* Function name */
119820  sqlite3_value *pVal,            /* argv[0] passed to function */
119821  Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
119822){
119823  Fts3Cursor *pRet;
119824  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
119825   || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
119826  ){
119827    char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
119828    sqlite3_result_error(pContext, zErr, -1);
119829    sqlite3_free(zErr);
119830    return SQLITE_ERROR;
119831  }
119832  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
119833  *ppCsr = pRet;
119834  return SQLITE_OK;
119835}
119836
119837/*
119838** Implementation of the snippet() function for FTS3
119839*/
119840static void fts3SnippetFunc(
119841  sqlite3_context *pContext,      /* SQLite function call context */
119842  int nVal,                       /* Size of apVal[] array */
119843  sqlite3_value **apVal           /* Array of arguments */
119844){
119845  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119846  const char *zStart = "<b>";
119847  const char *zEnd = "</b>";
119848  const char *zEllipsis = "<b>...</b>";
119849  int iCol = -1;
119850  int nToken = 15;                /* Default number of tokens in snippet */
119851
119852  /* There must be at least one argument passed to this function (otherwise
119853  ** the non-overloaded version would have been called instead of this one).
119854  */
119855  assert( nVal>=1 );
119856
119857  if( nVal>6 ){
119858    sqlite3_result_error(pContext,
119859        "wrong number of arguments to function snippet()", -1);
119860    return;
119861  }
119862  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
119863
119864  switch( nVal ){
119865    case 6: nToken = sqlite3_value_int(apVal[5]);
119866    case 5: iCol = sqlite3_value_int(apVal[4]);
119867    case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
119868    case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
119869    case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
119870  }
119871  if( !zEllipsis || !zEnd || !zStart ){
119872    sqlite3_result_error_nomem(pContext);
119873  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
119874    sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
119875  }
119876}
119877
119878/*
119879** Implementation of the offsets() function for FTS3
119880*/
119881static void fts3OffsetsFunc(
119882  sqlite3_context *pContext,      /* SQLite function call context */
119883  int nVal,                       /* Size of argument array */
119884  sqlite3_value **apVal           /* Array of arguments */
119885){
119886  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119887
119888  UNUSED_PARAMETER(nVal);
119889
119890  assert( nVal==1 );
119891  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
119892  assert( pCsr );
119893  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
119894    sqlite3Fts3Offsets(pContext, pCsr);
119895  }
119896}
119897
119898/*
119899** Implementation of the special optimize() function for FTS3. This
119900** function merges all segments in the database to a single segment.
119901** Example usage is:
119902**
119903**   SELECT optimize(t) FROM t LIMIT 1;
119904**
119905** where 't' is the name of an FTS3 table.
119906*/
119907static void fts3OptimizeFunc(
119908  sqlite3_context *pContext,      /* SQLite function call context */
119909  int nVal,                       /* Size of argument array */
119910  sqlite3_value **apVal           /* Array of arguments */
119911){
119912  int rc;                         /* Return code */
119913  Fts3Table *p;                   /* Virtual table handle */
119914  Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
119915
119916  UNUSED_PARAMETER(nVal);
119917
119918  assert( nVal==1 );
119919  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
119920  p = (Fts3Table *)pCursor->base.pVtab;
119921  assert( p );
119922
119923  rc = sqlite3Fts3Optimize(p);
119924
119925  switch( rc ){
119926    case SQLITE_OK:
119927      sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
119928      break;
119929    case SQLITE_DONE:
119930      sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
119931      break;
119932    default:
119933      sqlite3_result_error_code(pContext, rc);
119934      break;
119935  }
119936}
119937
119938/*
119939** Implementation of the matchinfo() function for FTS3
119940*/
119941static void fts3MatchinfoFunc(
119942  sqlite3_context *pContext,      /* SQLite function call context */
119943  int nVal,                       /* Size of argument array */
119944  sqlite3_value **apVal           /* Array of arguments */
119945){
119946  Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
119947  assert( nVal==1 || nVal==2 );
119948  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
119949    const char *zArg = 0;
119950    if( nVal>1 ){
119951      zArg = (const char *)sqlite3_value_text(apVal[1]);
119952    }
119953    sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
119954  }
119955}
119956
119957/*
119958** This routine implements the xFindFunction method for the FTS3
119959** virtual table.
119960*/
119961static int fts3FindFunctionMethod(
119962  sqlite3_vtab *pVtab,            /* Virtual table handle */
119963  int nArg,                       /* Number of SQL function arguments */
119964  const char *zName,              /* Name of SQL function */
119965  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
119966  void **ppArg                    /* Unused */
119967){
119968  struct Overloaded {
119969    const char *zName;
119970    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
119971  } aOverload[] = {
119972    { "snippet", fts3SnippetFunc },
119973    { "offsets", fts3OffsetsFunc },
119974    { "optimize", fts3OptimizeFunc },
119975    { "matchinfo", fts3MatchinfoFunc },
119976  };
119977  int i;                          /* Iterator variable */
119978
119979  UNUSED_PARAMETER(pVtab);
119980  UNUSED_PARAMETER(nArg);
119981  UNUSED_PARAMETER(ppArg);
119982
119983  for(i=0; i<SizeofArray(aOverload); i++){
119984    if( strcmp(zName, aOverload[i].zName)==0 ){
119985      *pxFunc = aOverload[i].xFunc;
119986      return 1;
119987    }
119988  }
119989
119990  /* No function of the specified name was found. Return 0. */
119991  return 0;
119992}
119993
119994/*
119995** Implementation of FTS3 xRename method. Rename an fts3 table.
119996*/
119997static int fts3RenameMethod(
119998  sqlite3_vtab *pVtab,            /* Virtual table handle */
119999  const char *zName               /* New name of table */
120000){
120001  Fts3Table *p = (Fts3Table *)pVtab;
120002  sqlite3 *db = p->db;            /* Database connection */
120003  int rc;                         /* Return Code */
120004
120005  /* As it happens, the pending terms table is always empty here. This is
120006  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
120007  ** always opens a savepoint transaction. And the xSavepoint() method
120008  ** flushes the pending terms table. But leave the (no-op) call to
120009  ** PendingTermsFlush() in in case that changes.
120010  */
120011  assert( p->nPendingData==0 );
120012  rc = sqlite3Fts3PendingTermsFlush(p);
120013
120014  if( p->zContentTbl==0 ){
120015    fts3DbExec(&rc, db,
120016      "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
120017      p->zDb, p->zName, zName
120018    );
120019  }
120020
120021  if( p->bHasDocsize ){
120022    fts3DbExec(&rc, db,
120023      "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
120024      p->zDb, p->zName, zName
120025    );
120026  }
120027  if( p->bHasStat ){
120028    fts3DbExec(&rc, db,
120029      "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
120030      p->zDb, p->zName, zName
120031    );
120032  }
120033  fts3DbExec(&rc, db,
120034    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
120035    p->zDb, p->zName, zName
120036  );
120037  fts3DbExec(&rc, db,
120038    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
120039    p->zDb, p->zName, zName
120040  );
120041  return rc;
120042}
120043
120044/*
120045** The xSavepoint() method.
120046**
120047** Flush the contents of the pending-terms table to disk.
120048*/
120049static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
120050  UNUSED_PARAMETER(iSavepoint);
120051  assert( ((Fts3Table *)pVtab)->inTransaction );
120052  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
120053  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
120054  return fts3SyncMethod(pVtab);
120055}
120056
120057/*
120058** The xRelease() method.
120059**
120060** This is a no-op.
120061*/
120062static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
120063  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
120064  UNUSED_PARAMETER(iSavepoint);
120065  UNUSED_PARAMETER(pVtab);
120066  assert( p->inTransaction );
120067  assert( p->mxSavepoint >= iSavepoint );
120068  TESTONLY( p->mxSavepoint = iSavepoint-1 );
120069  return SQLITE_OK;
120070}
120071
120072/*
120073** The xRollbackTo() method.
120074**
120075** Discard the contents of the pending terms table.
120076*/
120077static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
120078  Fts3Table *p = (Fts3Table*)pVtab;
120079  UNUSED_PARAMETER(iSavepoint);
120080  assert( p->inTransaction );
120081  assert( p->mxSavepoint >= iSavepoint );
120082  TESTONLY( p->mxSavepoint = iSavepoint );
120083  sqlite3Fts3PendingTermsClear(p);
120084  return SQLITE_OK;
120085}
120086
120087static const sqlite3_module fts3Module = {
120088  /* iVersion      */ 2,
120089  /* xCreate       */ fts3CreateMethod,
120090  /* xConnect      */ fts3ConnectMethod,
120091  /* xBestIndex    */ fts3BestIndexMethod,
120092  /* xDisconnect   */ fts3DisconnectMethod,
120093  /* xDestroy      */ fts3DestroyMethod,
120094  /* xOpen         */ fts3OpenMethod,
120095  /* xClose        */ fts3CloseMethod,
120096  /* xFilter       */ fts3FilterMethod,
120097  /* xNext         */ fts3NextMethod,
120098  /* xEof          */ fts3EofMethod,
120099  /* xColumn       */ fts3ColumnMethod,
120100  /* xRowid        */ fts3RowidMethod,
120101  /* xUpdate       */ fts3UpdateMethod,
120102  /* xBegin        */ fts3BeginMethod,
120103  /* xSync         */ fts3SyncMethod,
120104  /* xCommit       */ fts3CommitMethod,
120105  /* xRollback     */ fts3RollbackMethod,
120106  /* xFindFunction */ fts3FindFunctionMethod,
120107  /* xRename */       fts3RenameMethod,
120108  /* xSavepoint    */ fts3SavepointMethod,
120109  /* xRelease      */ fts3ReleaseMethod,
120110  /* xRollbackTo   */ fts3RollbackToMethod,
120111};
120112
120113/*
120114** This function is registered as the module destructor (called when an
120115** FTS3 enabled database connection is closed). It frees the memory
120116** allocated for the tokenizer hash table.
120117*/
120118static void hashDestroy(void *p){
120119  Fts3Hash *pHash = (Fts3Hash *)p;
120120  sqlite3Fts3HashClear(pHash);
120121  sqlite3_free(pHash);
120122}
120123
120124/*
120125** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
120126** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
120127** respectively. The following three forward declarations are for functions
120128** declared in these files used to retrieve the respective implementations.
120129**
120130** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
120131** to by the argument to point to the "simple" tokenizer implementation.
120132** And so on.
120133*/
120134SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
120135SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
120136#ifdef SQLITE_ENABLE_ICU
120137SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
120138#endif
120139
120140/*
120141** Initialise the fts3 extension. If this extension is built as part
120142** of the sqlite library, then this function is called directly by
120143** SQLite. If fts3 is built as a dynamically loadable extension, this
120144** function is called by the sqlite3_extension_init() entry point.
120145*/
120146SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
120147  int rc = SQLITE_OK;
120148  Fts3Hash *pHash = 0;
120149  const sqlite3_tokenizer_module *pSimple = 0;
120150  const sqlite3_tokenizer_module *pPorter = 0;
120151
120152#ifdef SQLITE_ENABLE_ICU
120153  const sqlite3_tokenizer_module *pIcu = 0;
120154  sqlite3Fts3IcuTokenizerModule(&pIcu);
120155#endif
120156
120157#ifdef SQLITE_TEST
120158  rc = sqlite3Fts3InitTerm(db);
120159  if( rc!=SQLITE_OK ) return rc;
120160#endif
120161
120162  rc = sqlite3Fts3InitAux(db);
120163  if( rc!=SQLITE_OK ) return rc;
120164
120165  sqlite3Fts3SimpleTokenizerModule(&pSimple);
120166  sqlite3Fts3PorterTokenizerModule(&pPorter);
120167
120168  /* Allocate and initialise the hash-table used to store tokenizers. */
120169  pHash = sqlite3_malloc(sizeof(Fts3Hash));
120170  if( !pHash ){
120171    rc = SQLITE_NOMEM;
120172  }else{
120173    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
120174  }
120175
120176  /* Load the built-in tokenizers into the hash table */
120177  if( rc==SQLITE_OK ){
120178    if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
120179     || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
120180#ifdef SQLITE_ENABLE_ICU
120181     || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
120182#endif
120183    ){
120184      rc = SQLITE_NOMEM;
120185    }
120186  }
120187
120188#ifdef SQLITE_TEST
120189  if( rc==SQLITE_OK ){
120190    rc = sqlite3Fts3ExprInitTestInterface(db);
120191  }
120192#endif
120193
120194  /* Create the virtual table wrapper around the hash-table and overload
120195  ** the two scalar functions. If this is successful, register the
120196  ** module with sqlite.
120197  */
120198  if( SQLITE_OK==rc
120199   && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
120200   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
120201   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
120202   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
120203   && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
120204   && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
120205  ){
120206    rc = sqlite3_create_module_v2(
120207        db, "fts3", &fts3Module, (void *)pHash, hashDestroy
120208    );
120209    if( rc==SQLITE_OK ){
120210      rc = sqlite3_create_module_v2(
120211          db, "fts4", &fts3Module, (void *)pHash, 0
120212      );
120213    }
120214    return rc;
120215  }
120216
120217  /* An error has occurred. Delete the hash table and return the error code. */
120218  assert( rc!=SQLITE_OK );
120219  if( pHash ){
120220    sqlite3Fts3HashClear(pHash);
120221    sqlite3_free(pHash);
120222  }
120223  return rc;
120224}
120225
120226/*
120227** Allocate an Fts3MultiSegReader for each token in the expression headed
120228** by pExpr.
120229**
120230** An Fts3SegReader object is a cursor that can seek or scan a range of
120231** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
120232** Fts3SegReader objects internally to provide an interface to seek or scan
120233** within the union of all segments of a b-tree. Hence the name.
120234**
120235** If the allocated Fts3MultiSegReader just seeks to a single entry in a
120236** segment b-tree (if the term is not a prefix or it is a prefix for which
120237** there exists prefix b-tree of the right length) then it may be traversed
120238** and merged incrementally. Otherwise, it has to be merged into an in-memory
120239** doclist and then traversed.
120240*/
120241static void fts3EvalAllocateReaders(
120242  Fts3Cursor *pCsr,               /* FTS cursor handle */
120243  Fts3Expr *pExpr,                /* Allocate readers for this expression */
120244  int *pnToken,                   /* OUT: Total number of tokens in phrase. */
120245  int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
120246  int *pRc                        /* IN/OUT: Error code */
120247){
120248  if( pExpr && SQLITE_OK==*pRc ){
120249    if( pExpr->eType==FTSQUERY_PHRASE ){
120250      int i;
120251      int nToken = pExpr->pPhrase->nToken;
120252      *pnToken += nToken;
120253      for(i=0; i<nToken; i++){
120254        Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
120255        int rc = fts3TermSegReaderCursor(pCsr,
120256            pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
120257        );
120258        if( rc!=SQLITE_OK ){
120259          *pRc = rc;
120260          return;
120261        }
120262      }
120263      assert( pExpr->pPhrase->iDoclistToken==0 );
120264      pExpr->pPhrase->iDoclistToken = -1;
120265    }else{
120266      *pnOr += (pExpr->eType==FTSQUERY_OR);
120267      fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
120268      fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
120269    }
120270  }
120271}
120272
120273/*
120274** Arguments pList/nList contain the doclist for token iToken of phrase p.
120275** It is merged into the main doclist stored in p->doclist.aAll/nAll.
120276**
120277** This function assumes that pList points to a buffer allocated using
120278** sqlite3_malloc(). This function takes responsibility for eventually
120279** freeing the buffer.
120280*/
120281static void fts3EvalPhraseMergeToken(
120282  Fts3Table *pTab,                /* FTS Table pointer */
120283  Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
120284  int iToken,                     /* Token pList/nList corresponds to */
120285  char *pList,                    /* Pointer to doclist */
120286  int nList                       /* Number of bytes in pList */
120287){
120288  assert( iToken!=p->iDoclistToken );
120289
120290  if( pList==0 ){
120291    sqlite3_free(p->doclist.aAll);
120292    p->doclist.aAll = 0;
120293    p->doclist.nAll = 0;
120294  }
120295
120296  else if( p->iDoclistToken<0 ){
120297    p->doclist.aAll = pList;
120298    p->doclist.nAll = nList;
120299  }
120300
120301  else if( p->doclist.aAll==0 ){
120302    sqlite3_free(pList);
120303  }
120304
120305  else {
120306    char *pLeft;
120307    char *pRight;
120308    int nLeft;
120309    int nRight;
120310    int nDiff;
120311
120312    if( p->iDoclistToken<iToken ){
120313      pLeft = p->doclist.aAll;
120314      nLeft = p->doclist.nAll;
120315      pRight = pList;
120316      nRight = nList;
120317      nDiff = iToken - p->iDoclistToken;
120318    }else{
120319      pRight = p->doclist.aAll;
120320      nRight = p->doclist.nAll;
120321      pLeft = pList;
120322      nLeft = nList;
120323      nDiff = p->iDoclistToken - iToken;
120324    }
120325
120326    fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
120327    sqlite3_free(pLeft);
120328    p->doclist.aAll = pRight;
120329    p->doclist.nAll = nRight;
120330  }
120331
120332  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
120333}
120334
120335/*
120336** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
120337** does not take deferred tokens into account.
120338**
120339** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120340*/
120341static int fts3EvalPhraseLoad(
120342  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120343  Fts3Phrase *p                   /* Phrase object */
120344){
120345  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120346  int iToken;
120347  int rc = SQLITE_OK;
120348
120349  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
120350    Fts3PhraseToken *pToken = &p->aToken[iToken];
120351    assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
120352
120353    if( pToken->pSegcsr ){
120354      int nThis = 0;
120355      char *pThis = 0;
120356      rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
120357      if( rc==SQLITE_OK ){
120358        fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
120359      }
120360    }
120361    assert( pToken->pSegcsr==0 );
120362  }
120363
120364  return rc;
120365}
120366
120367/*
120368** This function is called on each phrase after the position lists for
120369** any deferred tokens have been loaded into memory. It updates the phrases
120370** current position list to include only those positions that are really
120371** instances of the phrase (after considering deferred tokens). If this
120372** means that the phrase does not appear in the current row, doclist.pList
120373** and doclist.nList are both zeroed.
120374**
120375** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120376*/
120377static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
120378  int iToken;                     /* Used to iterate through phrase tokens */
120379  char *aPoslist = 0;             /* Position list for deferred tokens */
120380  int nPoslist = 0;               /* Number of bytes in aPoslist */
120381  int iPrev = -1;                 /* Token number of previous deferred token */
120382
120383  assert( pPhrase->doclist.bFreeList==0 );
120384
120385  for(iToken=0; iToken<pPhrase->nToken; iToken++){
120386    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
120387    Fts3DeferredToken *pDeferred = pToken->pDeferred;
120388
120389    if( pDeferred ){
120390      char *pList;
120391      int nList;
120392      int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
120393      if( rc!=SQLITE_OK ) return rc;
120394
120395      if( pList==0 ){
120396        sqlite3_free(aPoslist);
120397        pPhrase->doclist.pList = 0;
120398        pPhrase->doclist.nList = 0;
120399        return SQLITE_OK;
120400
120401      }else if( aPoslist==0 ){
120402        aPoslist = pList;
120403        nPoslist = nList;
120404
120405      }else{
120406        char *aOut = pList;
120407        char *p1 = aPoslist;
120408        char *p2 = aOut;
120409
120410        assert( iPrev>=0 );
120411        fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
120412        sqlite3_free(aPoslist);
120413        aPoslist = pList;
120414        nPoslist = (int)(aOut - aPoslist);
120415        if( nPoslist==0 ){
120416          sqlite3_free(aPoslist);
120417          pPhrase->doclist.pList = 0;
120418          pPhrase->doclist.nList = 0;
120419          return SQLITE_OK;
120420        }
120421      }
120422      iPrev = iToken;
120423    }
120424  }
120425
120426  if( iPrev>=0 ){
120427    int nMaxUndeferred = pPhrase->iDoclistToken;
120428    if( nMaxUndeferred<0 ){
120429      pPhrase->doclist.pList = aPoslist;
120430      pPhrase->doclist.nList = nPoslist;
120431      pPhrase->doclist.iDocid = pCsr->iPrevId;
120432      pPhrase->doclist.bFreeList = 1;
120433    }else{
120434      int nDistance;
120435      char *p1;
120436      char *p2;
120437      char *aOut;
120438
120439      if( nMaxUndeferred>iPrev ){
120440        p1 = aPoslist;
120441        p2 = pPhrase->doclist.pList;
120442        nDistance = nMaxUndeferred - iPrev;
120443      }else{
120444        p1 = pPhrase->doclist.pList;
120445        p2 = aPoslist;
120446        nDistance = iPrev - nMaxUndeferred;
120447      }
120448
120449      aOut = (char *)sqlite3_malloc(nPoslist+8);
120450      if( !aOut ){
120451        sqlite3_free(aPoslist);
120452        return SQLITE_NOMEM;
120453      }
120454
120455      pPhrase->doclist.pList = aOut;
120456      if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
120457        pPhrase->doclist.bFreeList = 1;
120458        pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
120459      }else{
120460        sqlite3_free(aOut);
120461        pPhrase->doclist.pList = 0;
120462        pPhrase->doclist.nList = 0;
120463      }
120464      sqlite3_free(aPoslist);
120465    }
120466  }
120467
120468  return SQLITE_OK;
120469}
120470
120471/*
120472** This function is called for each Fts3Phrase in a full-text query
120473** expression to initialize the mechanism for returning rows. Once this
120474** function has been called successfully on an Fts3Phrase, it may be
120475** used with fts3EvalPhraseNext() to iterate through the matching docids.
120476**
120477** If parameter bOptOk is true, then the phrase may (or may not) use the
120478** incremental loading strategy. Otherwise, the entire doclist is loaded into
120479** memory within this call.
120480**
120481** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
120482*/
120483static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
120484  int rc;                         /* Error code */
120485  Fts3PhraseToken *pFirst = &p->aToken[0];
120486  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120487
120488  if( pCsr->bDesc==pTab->bDescIdx
120489   && bOptOk==1
120490   && p->nToken==1
120491   && pFirst->pSegcsr
120492   && pFirst->pSegcsr->bLookup
120493   && pFirst->bFirst==0
120494  ){
120495    /* Use the incremental approach. */
120496    int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
120497    rc = sqlite3Fts3MsrIncrStart(
120498        pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
120499    p->bIncr = 1;
120500
120501  }else{
120502    /* Load the full doclist for the phrase into memory. */
120503    rc = fts3EvalPhraseLoad(pCsr, p);
120504    p->bIncr = 0;
120505  }
120506
120507  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
120508  return rc;
120509}
120510
120511/*
120512** This function is used to iterate backwards (from the end to start)
120513** through doclists. It is used by this module to iterate through phrase
120514** doclists in reverse and by the fts3_write.c module to iterate through
120515** pending-terms lists when writing to databases with "order=desc".
120516**
120517** The doclist may be sorted in ascending (parameter bDescIdx==0) or
120518** descending (parameter bDescIdx==1) order of docid. Regardless, this
120519** function iterates from the end of the doclist to the beginning.
120520*/
120521SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
120522  int bDescIdx,                   /* True if the doclist is desc */
120523  char *aDoclist,                 /* Pointer to entire doclist */
120524  int nDoclist,                   /* Length of aDoclist in bytes */
120525  char **ppIter,                  /* IN/OUT: Iterator pointer */
120526  sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
120527  int *pnList,                    /* IN/OUT: List length pointer */
120528  u8 *pbEof                       /* OUT: End-of-file flag */
120529){
120530  char *p = *ppIter;
120531
120532  assert( nDoclist>0 );
120533  assert( *pbEof==0 );
120534  assert( p || *piDocid==0 );
120535  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
120536
120537  if( p==0 ){
120538    sqlite3_int64 iDocid = 0;
120539    char *pNext = 0;
120540    char *pDocid = aDoclist;
120541    char *pEnd = &aDoclist[nDoclist];
120542    int iMul = 1;
120543
120544    while( pDocid<pEnd ){
120545      sqlite3_int64 iDelta;
120546      pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
120547      iDocid += (iMul * iDelta);
120548      pNext = pDocid;
120549      fts3PoslistCopy(0, &pDocid);
120550      while( pDocid<pEnd && *pDocid==0 ) pDocid++;
120551      iMul = (bDescIdx ? -1 : 1);
120552    }
120553
120554    *pnList = (int)(pEnd - pNext);
120555    *ppIter = pNext;
120556    *piDocid = iDocid;
120557  }else{
120558    int iMul = (bDescIdx ? -1 : 1);
120559    sqlite3_int64 iDelta;
120560    fts3GetReverseVarint(&p, aDoclist, &iDelta);
120561    *piDocid -= (iMul * iDelta);
120562
120563    if( p==aDoclist ){
120564      *pbEof = 1;
120565    }else{
120566      char *pSave = p;
120567      fts3ReversePoslist(aDoclist, &p);
120568      *pnList = (int)(pSave - p);
120569    }
120570    *ppIter = p;
120571  }
120572}
120573
120574/*
120575** Attempt to move the phrase iterator to point to the next matching docid.
120576** If an error occurs, return an SQLite error code. Otherwise, return
120577** SQLITE_OK.
120578**
120579** If there is no "next" entry and no error occurs, then *pbEof is set to
120580** 1 before returning. Otherwise, if no error occurs and the iterator is
120581** successfully advanced, *pbEof is set to 0.
120582*/
120583static int fts3EvalPhraseNext(
120584  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120585  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
120586  u8 *pbEof                       /* OUT: Set to 1 if EOF */
120587){
120588  int rc = SQLITE_OK;
120589  Fts3Doclist *pDL = &p->doclist;
120590  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120591
120592  if( p->bIncr ){
120593    assert( p->nToken==1 );
120594    assert( pDL->pNextDocid==0 );
120595    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
120596        &pDL->iDocid, &pDL->pList, &pDL->nList
120597    );
120598    if( rc==SQLITE_OK && !pDL->pList ){
120599      *pbEof = 1;
120600    }
120601  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
120602    sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
120603        &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
120604    );
120605    pDL->pList = pDL->pNextDocid;
120606  }else{
120607    char *pIter;                            /* Used to iterate through aAll */
120608    char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
120609    if( pDL->pNextDocid ){
120610      pIter = pDL->pNextDocid;
120611    }else{
120612      pIter = pDL->aAll;
120613    }
120614
120615    if( pIter>=pEnd ){
120616      /* We have already reached the end of this doclist. EOF. */
120617      *pbEof = 1;
120618    }else{
120619      sqlite3_int64 iDelta;
120620      pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
120621      if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
120622        pDL->iDocid += iDelta;
120623      }else{
120624        pDL->iDocid -= iDelta;
120625      }
120626      pDL->pList = pIter;
120627      fts3PoslistCopy(0, &pIter);
120628      pDL->nList = (int)(pIter - pDL->pList);
120629
120630      /* pIter now points just past the 0x00 that terminates the position-
120631      ** list for document pDL->iDocid. However, if this position-list was
120632      ** edited in place by fts3EvalNearTrim(), then pIter may not actually
120633      ** point to the start of the next docid value. The following line deals
120634      ** with this case by advancing pIter past the zero-padding added by
120635      ** fts3EvalNearTrim().  */
120636      while( pIter<pEnd && *pIter==0 ) pIter++;
120637
120638      pDL->pNextDocid = pIter;
120639      assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
120640      *pbEof = 0;
120641    }
120642  }
120643
120644  return rc;
120645}
120646
120647/*
120648**
120649** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
120650** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
120651** expression. Also the Fts3Expr.bDeferred variable is set to true for any
120652** expressions for which all descendent tokens are deferred.
120653**
120654** If parameter bOptOk is zero, then it is guaranteed that the
120655** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
120656** each phrase in the expression (subject to deferred token processing).
120657** Or, if bOptOk is non-zero, then one or more tokens within the expression
120658** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
120659**
120660** If an error occurs within this function, *pRc is set to an SQLite error
120661** code before returning.
120662*/
120663static void fts3EvalStartReaders(
120664  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120665  Fts3Expr *pExpr,                /* Expression to initialize phrases in */
120666  int bOptOk,                     /* True to enable incremental loading */
120667  int *pRc                        /* IN/OUT: Error code */
120668){
120669  if( pExpr && SQLITE_OK==*pRc ){
120670    if( pExpr->eType==FTSQUERY_PHRASE ){
120671      int i;
120672      int nToken = pExpr->pPhrase->nToken;
120673      for(i=0; i<nToken; i++){
120674        if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
120675      }
120676      pExpr->bDeferred = (i==nToken);
120677      *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
120678    }else{
120679      fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
120680      fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
120681      pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
120682    }
120683  }
120684}
120685
120686/*
120687** An array of the following structures is assembled as part of the process
120688** of selecting tokens to defer before the query starts executing (as part
120689** of the xFilter() method). There is one element in the array for each
120690** token in the FTS expression.
120691**
120692** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
120693** to phrases that are connected only by AND and NEAR operators (not OR or
120694** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
120695** separately. The root of a tokens AND/NEAR cluster is stored in
120696** Fts3TokenAndCost.pRoot.
120697*/
120698typedef struct Fts3TokenAndCost Fts3TokenAndCost;
120699struct Fts3TokenAndCost {
120700  Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
120701  int iToken;                     /* Position of token in phrase */
120702  Fts3PhraseToken *pToken;        /* The token itself */
120703  Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
120704  int nOvfl;                      /* Number of overflow pages to load doclist */
120705  int iCol;                       /* The column the token must match */
120706};
120707
120708/*
120709** This function is used to populate an allocated Fts3TokenAndCost array.
120710**
120711** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
120712** Otherwise, if an error occurs during execution, *pRc is set to an
120713** SQLite error code.
120714*/
120715static void fts3EvalTokenCosts(
120716  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120717  Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
120718  Fts3Expr *pExpr,                /* Expression to consider */
120719  Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
120720  Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
120721  int *pRc                        /* IN/OUT: Error code */
120722){
120723  if( *pRc==SQLITE_OK ){
120724    if( pExpr->eType==FTSQUERY_PHRASE ){
120725      Fts3Phrase *pPhrase = pExpr->pPhrase;
120726      int i;
120727      for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
120728        Fts3TokenAndCost *pTC = (*ppTC)++;
120729        pTC->pPhrase = pPhrase;
120730        pTC->iToken = i;
120731        pTC->pRoot = pRoot;
120732        pTC->pToken = &pPhrase->aToken[i];
120733        pTC->iCol = pPhrase->iColumn;
120734        *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
120735      }
120736    }else if( pExpr->eType!=FTSQUERY_NOT ){
120737      assert( pExpr->eType==FTSQUERY_OR
120738           || pExpr->eType==FTSQUERY_AND
120739           || pExpr->eType==FTSQUERY_NEAR
120740      );
120741      assert( pExpr->pLeft && pExpr->pRight );
120742      if( pExpr->eType==FTSQUERY_OR ){
120743        pRoot = pExpr->pLeft;
120744        **ppOr = pRoot;
120745        (*ppOr)++;
120746      }
120747      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
120748      if( pExpr->eType==FTSQUERY_OR ){
120749        pRoot = pExpr->pRight;
120750        **ppOr = pRoot;
120751        (*ppOr)++;
120752      }
120753      fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
120754    }
120755  }
120756}
120757
120758/*
120759** Determine the average document (row) size in pages. If successful,
120760** write this value to *pnPage and return SQLITE_OK. Otherwise, return
120761** an SQLite error code.
120762**
120763** The average document size in pages is calculated by first calculating
120764** determining the average size in bytes, B. If B is less than the amount
120765** of data that will fit on a single leaf page of an intkey table in
120766** this database, then the average docsize is 1. Otherwise, it is 1 plus
120767** the number of overflow pages consumed by a record B bytes in size.
120768*/
120769static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
120770  if( pCsr->nRowAvg==0 ){
120771    /* The average document size, which is required to calculate the cost
120772    ** of each doclist, has not yet been determined. Read the required
120773    ** data from the %_stat table to calculate it.
120774    **
120775    ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
120776    ** varints, where nCol is the number of columns in the FTS3 table.
120777    ** The first varint is the number of documents currently stored in
120778    ** the table. The following nCol varints contain the total amount of
120779    ** data stored in all rows of each column of the table, from left
120780    ** to right.
120781    */
120782    int rc;
120783    Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
120784    sqlite3_stmt *pStmt;
120785    sqlite3_int64 nDoc = 0;
120786    sqlite3_int64 nByte = 0;
120787    const char *pEnd;
120788    const char *a;
120789
120790    rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
120791    if( rc!=SQLITE_OK ) return rc;
120792    a = sqlite3_column_blob(pStmt, 0);
120793    assert( a );
120794
120795    pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
120796    a += sqlite3Fts3GetVarint(a, &nDoc);
120797    while( a<pEnd ){
120798      a += sqlite3Fts3GetVarint(a, &nByte);
120799    }
120800    if( nDoc==0 || nByte==0 ){
120801      sqlite3_reset(pStmt);
120802      return FTS_CORRUPT_VTAB;
120803    }
120804
120805    pCsr->nDoc = nDoc;
120806    pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
120807    assert( pCsr->nRowAvg>0 );
120808    rc = sqlite3_reset(pStmt);
120809    if( rc!=SQLITE_OK ) return rc;
120810  }
120811
120812  *pnPage = pCsr->nRowAvg;
120813  return SQLITE_OK;
120814}
120815
120816/*
120817** This function is called to select the tokens (if any) that will be
120818** deferred. The array aTC[] has already been populated when this is
120819** called.
120820**
120821** This function is called once for each AND/NEAR cluster in the
120822** expression. Each invocation determines which tokens to defer within
120823** the cluster with root node pRoot. See comments above the definition
120824** of struct Fts3TokenAndCost for more details.
120825**
120826** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
120827** called on each token to defer. Otherwise, an SQLite error code is
120828** returned.
120829*/
120830static int fts3EvalSelectDeferred(
120831  Fts3Cursor *pCsr,               /* FTS Cursor handle */
120832  Fts3Expr *pRoot,                /* Consider tokens with this root node */
120833  Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
120834  int nTC                         /* Number of entries in aTC[] */
120835){
120836  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120837  int nDocSize = 0;               /* Number of pages per doc loaded */
120838  int rc = SQLITE_OK;             /* Return code */
120839  int ii;                         /* Iterator variable for various purposes */
120840  int nOvfl = 0;                  /* Total overflow pages used by doclists */
120841  int nToken = 0;                 /* Total number of tokens in cluster */
120842
120843  int nMinEst = 0;                /* The minimum count for any phrase so far. */
120844  int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
120845
120846  /* Tokens are never deferred for FTS tables created using the content=xxx
120847  ** option. The reason being that it is not guaranteed that the content
120848  ** table actually contains the same data as the index. To prevent this from
120849  ** causing any problems, the deferred token optimization is completely
120850  ** disabled for content=xxx tables. */
120851  if( pTab->zContentTbl ){
120852    return SQLITE_OK;
120853  }
120854
120855  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
120856  ** associated with the tokens spill onto overflow pages, or if there is
120857  ** only 1 token, exit early. No tokens to defer in this case. */
120858  for(ii=0; ii<nTC; ii++){
120859    if( aTC[ii].pRoot==pRoot ){
120860      nOvfl += aTC[ii].nOvfl;
120861      nToken++;
120862    }
120863  }
120864  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
120865
120866  /* Obtain the average docsize (in pages). */
120867  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
120868  assert( rc!=SQLITE_OK || nDocSize>0 );
120869
120870
120871  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
120872  ** of the number of overflow pages that will be loaded by the pager layer
120873  ** to retrieve the entire doclist for the token from the full-text index.
120874  ** Load the doclists for tokens that are either:
120875  **
120876  **   a. The cheapest token in the entire query (i.e. the one visited by the
120877  **      first iteration of this loop), or
120878  **
120879  **   b. Part of a multi-token phrase.
120880  **
120881  ** After each token doclist is loaded, merge it with the others from the
120882  ** same phrase and count the number of documents that the merged doclist
120883  ** contains. Set variable "nMinEst" to the smallest number of documents in
120884  ** any phrase doclist for which 1 or more token doclists have been loaded.
120885  ** Let nOther be the number of other phrases for which it is certain that
120886  ** one or more tokens will not be deferred.
120887  **
120888  ** Then, for each token, defer it if loading the doclist would result in
120889  ** loading N or more overflow pages into memory, where N is computed as:
120890  **
120891  **    (nMinEst + 4^nOther - 1) / (4^nOther)
120892  */
120893  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
120894    int iTC;                      /* Used to iterate through aTC[] array. */
120895    Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
120896
120897    /* Set pTC to point to the cheapest remaining token. */
120898    for(iTC=0; iTC<nTC; iTC++){
120899      if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
120900       && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
120901      ){
120902        pTC = &aTC[iTC];
120903      }
120904    }
120905    assert( pTC );
120906
120907    if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
120908      /* The number of overflow pages to load for this (and therefore all
120909      ** subsequent) tokens is greater than the estimated number of pages
120910      ** that will be loaded if all subsequent tokens are deferred.
120911      */
120912      Fts3PhraseToken *pToken = pTC->pToken;
120913      rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
120914      fts3SegReaderCursorFree(pToken->pSegcsr);
120915      pToken->pSegcsr = 0;
120916    }else{
120917      /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
120918      ** for-loop. Except, limit the value to 2^24 to prevent it from
120919      ** overflowing the 32-bit integer it is stored in. */
120920      if( ii<12 ) nLoad4 = nLoad4*4;
120921
120922      if( ii==0 || pTC->pPhrase->nToken>1 ){
120923        /* Either this is the cheapest token in the entire query, or it is
120924        ** part of a multi-token phrase. Either way, the entire doclist will
120925        ** (eventually) be loaded into memory. It may as well be now. */
120926        Fts3PhraseToken *pToken = pTC->pToken;
120927        int nList = 0;
120928        char *pList = 0;
120929        rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
120930        assert( rc==SQLITE_OK || pList==0 );
120931        if( rc==SQLITE_OK ){
120932          int nCount;
120933          fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
120934          nCount = fts3DoclistCountDocids(
120935              pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
120936          );
120937          if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
120938        }
120939      }
120940    }
120941    pTC->pToken = 0;
120942  }
120943
120944  return rc;
120945}
120946
120947/*
120948** This function is called from within the xFilter method. It initializes
120949** the full-text query currently stored in pCsr->pExpr. To iterate through
120950** the results of a query, the caller does:
120951**
120952**    fts3EvalStart(pCsr);
120953**    while( 1 ){
120954**      fts3EvalNext(pCsr);
120955**      if( pCsr->bEof ) break;
120956**      ... return row pCsr->iPrevId to the caller ...
120957**    }
120958*/
120959static int fts3EvalStart(Fts3Cursor *pCsr){
120960  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
120961  int rc = SQLITE_OK;
120962  int nToken = 0;
120963  int nOr = 0;
120964
120965  /* Allocate a MultiSegReader for each token in the expression. */
120966  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
120967
120968  /* Determine which, if any, tokens in the expression should be deferred. */
120969  if( rc==SQLITE_OK && nToken>1 && pTab->bHasStat ){
120970    Fts3TokenAndCost *aTC;
120971    Fts3Expr **apOr;
120972    aTC = (Fts3TokenAndCost *)sqlite3_malloc(
120973        sizeof(Fts3TokenAndCost) * nToken
120974      + sizeof(Fts3Expr *) * nOr * 2
120975    );
120976    apOr = (Fts3Expr **)&aTC[nToken];
120977
120978    if( !aTC ){
120979      rc = SQLITE_NOMEM;
120980    }else{
120981      int ii;
120982      Fts3TokenAndCost *pTC = aTC;
120983      Fts3Expr **ppOr = apOr;
120984
120985      fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
120986      nToken = (int)(pTC-aTC);
120987      nOr = (int)(ppOr-apOr);
120988
120989      if( rc==SQLITE_OK ){
120990        rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
120991        for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
120992          rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
120993        }
120994      }
120995
120996      sqlite3_free(aTC);
120997    }
120998  }
120999
121000  fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
121001  return rc;
121002}
121003
121004/*
121005** Invalidate the current position list for phrase pPhrase.
121006*/
121007static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
121008  if( pPhrase->doclist.bFreeList ){
121009    sqlite3_free(pPhrase->doclist.pList);
121010  }
121011  pPhrase->doclist.pList = 0;
121012  pPhrase->doclist.nList = 0;
121013  pPhrase->doclist.bFreeList = 0;
121014}
121015
121016/*
121017** This function is called to edit the position list associated with
121018** the phrase object passed as the fifth argument according to a NEAR
121019** condition. For example:
121020**
121021**     abc NEAR/5 "def ghi"
121022**
121023** Parameter nNear is passed the NEAR distance of the expression (5 in
121024** the example above). When this function is called, *paPoslist points to
121025** the position list, and *pnToken is the number of phrase tokens in, the
121026** phrase on the other side of the NEAR operator to pPhrase. For example,
121027** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
121028** the position list associated with phrase "abc".
121029**
121030** All positions in the pPhrase position list that are not sufficiently
121031** close to a position in the *paPoslist position list are removed. If this
121032** leaves 0 positions, zero is returned. Otherwise, non-zero.
121033**
121034** Before returning, *paPoslist is set to point to the position lsit
121035** associated with pPhrase. And *pnToken is set to the number of tokens in
121036** pPhrase.
121037*/
121038static int fts3EvalNearTrim(
121039  int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
121040  char *aTmp,                     /* Temporary space to use */
121041  char **paPoslist,               /* IN/OUT: Position list */
121042  int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
121043  Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
121044){
121045  int nParam1 = nNear + pPhrase->nToken;
121046  int nParam2 = nNear + *pnToken;
121047  int nNew;
121048  char *p2;
121049  char *pOut;
121050  int res;
121051
121052  assert( pPhrase->doclist.pList );
121053
121054  p2 = pOut = pPhrase->doclist.pList;
121055  res = fts3PoslistNearMerge(
121056    &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
121057  );
121058  if( res ){
121059    nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
121060    assert( pPhrase->doclist.pList[nNew]=='\0' );
121061    assert( nNew<=pPhrase->doclist.nList && nNew>0 );
121062    memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
121063    pPhrase->doclist.nList = nNew;
121064    *paPoslist = pPhrase->doclist.pList;
121065    *pnToken = pPhrase->nToken;
121066  }
121067
121068  return res;
121069}
121070
121071/*
121072** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
121073** Otherwise, it advances the expression passed as the second argument to
121074** point to the next matching row in the database. Expressions iterate through
121075** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
121076** or descending if it is non-zero.
121077**
121078** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
121079** successful, the following variables in pExpr are set:
121080**
121081**   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
121082**   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
121083**
121084** If the expression is of type FTSQUERY_PHRASE, and the expression is not
121085** at EOF, then the following variables are populated with the position list
121086** for the phrase for the visited row:
121087**
121088**   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
121089**   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
121090**
121091** It says above that this function advances the expression to the next
121092** matching row. This is usually true, but there are the following exceptions:
121093**
121094**   1. Deferred tokens are not taken into account. If a phrase consists
121095**      entirely of deferred tokens, it is assumed to match every row in
121096**      the db. In this case the position-list is not populated at all.
121097**
121098**      Or, if a phrase contains one or more deferred tokens and one or
121099**      more non-deferred tokens, then the expression is advanced to the
121100**      next possible match, considering only non-deferred tokens. In other
121101**      words, if the phrase is "A B C", and "B" is deferred, the expression
121102**      is advanced to the next row that contains an instance of "A * C",
121103**      where "*" may match any single token. The position list in this case
121104**      is populated as for "A * C" before returning.
121105**
121106**   2. NEAR is treated as AND. If the expression is "x NEAR y", it is
121107**      advanced to point to the next row that matches "x AND y".
121108**
121109** See fts3EvalTestDeferredAndNear() for details on testing if a row is
121110** really a match, taking into account deferred tokens and NEAR operators.
121111*/
121112static void fts3EvalNextRow(
121113  Fts3Cursor *pCsr,               /* FTS Cursor handle */
121114  Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
121115  int *pRc                        /* IN/OUT: Error code */
121116){
121117  if( *pRc==SQLITE_OK ){
121118    int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
121119    assert( pExpr->bEof==0 );
121120    pExpr->bStart = 1;
121121
121122    switch( pExpr->eType ){
121123      case FTSQUERY_NEAR:
121124      case FTSQUERY_AND: {
121125        Fts3Expr *pLeft = pExpr->pLeft;
121126        Fts3Expr *pRight = pExpr->pRight;
121127        assert( !pLeft->bDeferred || !pRight->bDeferred );
121128
121129        if( pLeft->bDeferred ){
121130          /* LHS is entirely deferred. So we assume it matches every row.
121131          ** Advance the RHS iterator to find the next row visited. */
121132          fts3EvalNextRow(pCsr, pRight, pRc);
121133          pExpr->iDocid = pRight->iDocid;
121134          pExpr->bEof = pRight->bEof;
121135        }else if( pRight->bDeferred ){
121136          /* RHS is entirely deferred. So we assume it matches every row.
121137          ** Advance the LHS iterator to find the next row visited. */
121138          fts3EvalNextRow(pCsr, pLeft, pRc);
121139          pExpr->iDocid = pLeft->iDocid;
121140          pExpr->bEof = pLeft->bEof;
121141        }else{
121142          /* Neither the RHS or LHS are deferred. */
121143          fts3EvalNextRow(pCsr, pLeft, pRc);
121144          fts3EvalNextRow(pCsr, pRight, pRc);
121145          while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
121146            sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
121147            if( iDiff==0 ) break;
121148            if( iDiff<0 ){
121149              fts3EvalNextRow(pCsr, pLeft, pRc);
121150            }else{
121151              fts3EvalNextRow(pCsr, pRight, pRc);
121152            }
121153          }
121154          pExpr->iDocid = pLeft->iDocid;
121155          pExpr->bEof = (pLeft->bEof || pRight->bEof);
121156        }
121157        break;
121158      }
121159
121160      case FTSQUERY_OR: {
121161        Fts3Expr *pLeft = pExpr->pLeft;
121162        Fts3Expr *pRight = pExpr->pRight;
121163        sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
121164
121165        assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
121166        assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
121167
121168        if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
121169          fts3EvalNextRow(pCsr, pLeft, pRc);
121170        }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
121171          fts3EvalNextRow(pCsr, pRight, pRc);
121172        }else{
121173          fts3EvalNextRow(pCsr, pLeft, pRc);
121174          fts3EvalNextRow(pCsr, pRight, pRc);
121175        }
121176
121177        pExpr->bEof = (pLeft->bEof && pRight->bEof);
121178        iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
121179        if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
121180          pExpr->iDocid = pLeft->iDocid;
121181        }else{
121182          pExpr->iDocid = pRight->iDocid;
121183        }
121184
121185        break;
121186      }
121187
121188      case FTSQUERY_NOT: {
121189        Fts3Expr *pLeft = pExpr->pLeft;
121190        Fts3Expr *pRight = pExpr->pRight;
121191
121192        if( pRight->bStart==0 ){
121193          fts3EvalNextRow(pCsr, pRight, pRc);
121194          assert( *pRc!=SQLITE_OK || pRight->bStart );
121195        }
121196
121197        fts3EvalNextRow(pCsr, pLeft, pRc);
121198        if( pLeft->bEof==0 ){
121199          while( !*pRc
121200              && !pRight->bEof
121201              && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
121202          ){
121203            fts3EvalNextRow(pCsr, pRight, pRc);
121204          }
121205        }
121206        pExpr->iDocid = pLeft->iDocid;
121207        pExpr->bEof = pLeft->bEof;
121208        break;
121209      }
121210
121211      default: {
121212        Fts3Phrase *pPhrase = pExpr->pPhrase;
121213        fts3EvalInvalidatePoslist(pPhrase);
121214        *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
121215        pExpr->iDocid = pPhrase->doclist.iDocid;
121216        break;
121217      }
121218    }
121219  }
121220}
121221
121222/*
121223** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
121224** cluster, then this function returns 1 immediately.
121225**
121226** Otherwise, it checks if the current row really does match the NEAR
121227** expression, using the data currently stored in the position lists
121228** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
121229**
121230** If the current row is a match, the position list associated with each
121231** phrase in the NEAR expression is edited in place to contain only those
121232** phrase instances sufficiently close to their peers to satisfy all NEAR
121233** constraints. In this case it returns 1. If the NEAR expression does not
121234** match the current row, 0 is returned. The position lists may or may not
121235** be edited if 0 is returned.
121236*/
121237static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
121238  int res = 1;
121239
121240  /* The following block runs if pExpr is the root of a NEAR query.
121241  ** For example, the query:
121242  **
121243  **         "w" NEAR "x" NEAR "y" NEAR "z"
121244  **
121245  ** which is represented in tree form as:
121246  **
121247  **                               |
121248  **                          +--NEAR--+      <-- root of NEAR query
121249  **                          |        |
121250  **                     +--NEAR--+   "z"
121251  **                     |        |
121252  **                +--NEAR--+   "y"
121253  **                |        |
121254  **               "w"      "x"
121255  **
121256  ** The right-hand child of a NEAR node is always a phrase. The
121257  ** left-hand child may be either a phrase or a NEAR node. There are
121258  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
121259  */
121260  if( *pRc==SQLITE_OK
121261   && pExpr->eType==FTSQUERY_NEAR
121262   && pExpr->bEof==0
121263   && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
121264  ){
121265    Fts3Expr *p;
121266    int nTmp = 0;                 /* Bytes of temp space */
121267    char *aTmp;                   /* Temp space for PoslistNearMerge() */
121268
121269    /* Allocate temporary working space. */
121270    for(p=pExpr; p->pLeft; p=p->pLeft){
121271      nTmp += p->pRight->pPhrase->doclist.nList;
121272    }
121273    nTmp += p->pPhrase->doclist.nList;
121274    aTmp = sqlite3_malloc(nTmp*2);
121275    if( !aTmp ){
121276      *pRc = SQLITE_NOMEM;
121277      res = 0;
121278    }else{
121279      char *aPoslist = p->pPhrase->doclist.pList;
121280      int nToken = p->pPhrase->nToken;
121281
121282      for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
121283        Fts3Phrase *pPhrase = p->pRight->pPhrase;
121284        int nNear = p->nNear;
121285        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
121286      }
121287
121288      aPoslist = pExpr->pRight->pPhrase->doclist.pList;
121289      nToken = pExpr->pRight->pPhrase->nToken;
121290      for(p=pExpr->pLeft; p && res; p=p->pLeft){
121291        int nNear;
121292        Fts3Phrase *pPhrase;
121293        assert( p->pParent && p->pParent->pLeft==p );
121294        nNear = p->pParent->nNear;
121295        pPhrase = (
121296            p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
121297        );
121298        res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
121299      }
121300    }
121301
121302    sqlite3_free(aTmp);
121303  }
121304
121305  return res;
121306}
121307
121308/*
121309** This function is a helper function for fts3EvalTestDeferredAndNear().
121310** Assuming no error occurs or has occurred, It returns non-zero if the
121311** expression passed as the second argument matches the row that pCsr
121312** currently points to, or zero if it does not.
121313**
121314** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
121315** If an error occurs during execution of this function, *pRc is set to
121316** the appropriate SQLite error code. In this case the returned value is
121317** undefined.
121318*/
121319static int fts3EvalTestExpr(
121320  Fts3Cursor *pCsr,               /* FTS cursor handle */
121321  Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
121322  int *pRc                        /* IN/OUT: Error code */
121323){
121324  int bHit = 1;                   /* Return value */
121325  if( *pRc==SQLITE_OK ){
121326    switch( pExpr->eType ){
121327      case FTSQUERY_NEAR:
121328      case FTSQUERY_AND:
121329        bHit = (
121330            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
121331         && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
121332         && fts3EvalNearTest(pExpr, pRc)
121333        );
121334
121335        /* If the NEAR expression does not match any rows, zero the doclist for
121336        ** all phrases involved in the NEAR. This is because the snippet(),
121337        ** offsets() and matchinfo() functions are not supposed to recognize
121338        ** any instances of phrases that are part of unmatched NEAR queries.
121339        ** For example if this expression:
121340        **
121341        **    ... MATCH 'a OR (b NEAR c)'
121342        **
121343        ** is matched against a row containing:
121344        **
121345        **        'a b d e'
121346        **
121347        ** then any snippet() should ony highlight the "a" term, not the "b"
121348        ** (as "b" is part of a non-matching NEAR clause).
121349        */
121350        if( bHit==0
121351         && pExpr->eType==FTSQUERY_NEAR
121352         && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
121353        ){
121354          Fts3Expr *p;
121355          for(p=pExpr; p->pPhrase==0; p=p->pLeft){
121356            if( p->pRight->iDocid==pCsr->iPrevId ){
121357              fts3EvalInvalidatePoslist(p->pRight->pPhrase);
121358            }
121359          }
121360          if( p->iDocid==pCsr->iPrevId ){
121361            fts3EvalInvalidatePoslist(p->pPhrase);
121362          }
121363        }
121364
121365        break;
121366
121367      case FTSQUERY_OR: {
121368        int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
121369        int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
121370        bHit = bHit1 || bHit2;
121371        break;
121372      }
121373
121374      case FTSQUERY_NOT:
121375        bHit = (
121376            fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
121377         && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
121378        );
121379        break;
121380
121381      default: {
121382        if( pCsr->pDeferred
121383         && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
121384        ){
121385          Fts3Phrase *pPhrase = pExpr->pPhrase;
121386          assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
121387          if( pExpr->bDeferred ){
121388            fts3EvalInvalidatePoslist(pPhrase);
121389          }
121390          *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
121391          bHit = (pPhrase->doclist.pList!=0);
121392          pExpr->iDocid = pCsr->iPrevId;
121393        }else{
121394          bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
121395        }
121396        break;
121397      }
121398    }
121399  }
121400  return bHit;
121401}
121402
121403/*
121404** This function is called as the second part of each xNext operation when
121405** iterating through the results of a full-text query. At this point the
121406** cursor points to a row that matches the query expression, with the
121407** following caveats:
121408**
121409**   * Up until this point, "NEAR" operators in the expression have been
121410**     treated as "AND".
121411**
121412**   * Deferred tokens have not yet been considered.
121413**
121414** If *pRc is not SQLITE_OK when this function is called, it immediately
121415** returns 0. Otherwise, it tests whether or not after considering NEAR
121416** operators and deferred tokens the current row is still a match for the
121417** expression. It returns 1 if both of the following are true:
121418**
121419**   1. *pRc is SQLITE_OK when this function returns, and
121420**
121421**   2. After scanning the current FTS table row for the deferred tokens,
121422**      it is determined that the row does *not* match the query.
121423**
121424** Or, if no error occurs and it seems the current row does match the FTS
121425** query, return 0.
121426*/
121427static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
121428  int rc = *pRc;
121429  int bMiss = 0;
121430  if( rc==SQLITE_OK ){
121431
121432    /* If there are one or more deferred tokens, load the current row into
121433    ** memory and scan it to determine the position list for each deferred
121434    ** token. Then, see if this row is really a match, considering deferred
121435    ** tokens and NEAR operators (neither of which were taken into account
121436    ** earlier, by fts3EvalNextRow()).
121437    */
121438    if( pCsr->pDeferred ){
121439      rc = fts3CursorSeek(0, pCsr);
121440      if( rc==SQLITE_OK ){
121441        rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
121442      }
121443    }
121444    bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
121445
121446    /* Free the position-lists accumulated for each deferred token above. */
121447    sqlite3Fts3FreeDeferredDoclists(pCsr);
121448    *pRc = rc;
121449  }
121450  return (rc==SQLITE_OK && bMiss);
121451}
121452
121453/*
121454** Advance to the next document that matches the FTS expression in
121455** Fts3Cursor.pExpr.
121456*/
121457static int fts3EvalNext(Fts3Cursor *pCsr){
121458  int rc = SQLITE_OK;             /* Return Code */
121459  Fts3Expr *pExpr = pCsr->pExpr;
121460  assert( pCsr->isEof==0 );
121461  if( pExpr==0 ){
121462    pCsr->isEof = 1;
121463  }else{
121464    do {
121465      if( pCsr->isRequireSeek==0 ){
121466        sqlite3_reset(pCsr->pStmt);
121467      }
121468      assert( sqlite3_data_count(pCsr->pStmt)==0 );
121469      fts3EvalNextRow(pCsr, pExpr, &rc);
121470      pCsr->isEof = pExpr->bEof;
121471      pCsr->isRequireSeek = 1;
121472      pCsr->isMatchinfoNeeded = 1;
121473      pCsr->iPrevId = pExpr->iDocid;
121474    }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
121475  }
121476  return rc;
121477}
121478
121479/*
121480** Restart interation for expression pExpr so that the next call to
121481** fts3EvalNext() visits the first row. Do not allow incremental
121482** loading or merging of phrase doclists for this iteration.
121483**
121484** If *pRc is other than SQLITE_OK when this function is called, it is
121485** a no-op. If an error occurs within this function, *pRc is set to an
121486** SQLite error code before returning.
121487*/
121488static void fts3EvalRestart(
121489  Fts3Cursor *pCsr,
121490  Fts3Expr *pExpr,
121491  int *pRc
121492){
121493  if( pExpr && *pRc==SQLITE_OK ){
121494    Fts3Phrase *pPhrase = pExpr->pPhrase;
121495
121496    if( pPhrase ){
121497      fts3EvalInvalidatePoslist(pPhrase);
121498      if( pPhrase->bIncr ){
121499        assert( pPhrase->nToken==1 );
121500        assert( pPhrase->aToken[0].pSegcsr );
121501        sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
121502        *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
121503      }
121504
121505      pPhrase->doclist.pNextDocid = 0;
121506      pPhrase->doclist.iDocid = 0;
121507    }
121508
121509    pExpr->iDocid = 0;
121510    pExpr->bEof = 0;
121511    pExpr->bStart = 0;
121512
121513    fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
121514    fts3EvalRestart(pCsr, pExpr->pRight, pRc);
121515  }
121516}
121517
121518/*
121519** After allocating the Fts3Expr.aMI[] array for each phrase in the
121520** expression rooted at pExpr, the cursor iterates through all rows matched
121521** by pExpr, calling this function for each row. This function increments
121522** the values in Fts3Expr.aMI[] according to the position-list currently
121523** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
121524** expression nodes.
121525*/
121526static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
121527  if( pExpr ){
121528    Fts3Phrase *pPhrase = pExpr->pPhrase;
121529    if( pPhrase && pPhrase->doclist.pList ){
121530      int iCol = 0;
121531      char *p = pPhrase->doclist.pList;
121532
121533      assert( *p );
121534      while( 1 ){
121535        u8 c = 0;
121536        int iCnt = 0;
121537        while( 0xFE & (*p | c) ){
121538          if( (c&0x80)==0 ) iCnt++;
121539          c = *p++ & 0x80;
121540        }
121541
121542        /* aMI[iCol*3 + 1] = Number of occurrences
121543        ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
121544        */
121545        pExpr->aMI[iCol*3 + 1] += iCnt;
121546        pExpr->aMI[iCol*3 + 2] += (iCnt>0);
121547        if( *p==0x00 ) break;
121548        p++;
121549        p += sqlite3Fts3GetVarint32(p, &iCol);
121550      }
121551    }
121552
121553    fts3EvalUpdateCounts(pExpr->pLeft);
121554    fts3EvalUpdateCounts(pExpr->pRight);
121555  }
121556}
121557
121558/*
121559** Expression pExpr must be of type FTSQUERY_PHRASE.
121560**
121561** If it is not already allocated and populated, this function allocates and
121562** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
121563** of a NEAR expression, then it also allocates and populates the same array
121564** for all other phrases that are part of the NEAR expression.
121565**
121566** SQLITE_OK is returned if the aMI[] array is successfully allocated and
121567** populated. Otherwise, if an error occurs, an SQLite error code is returned.
121568*/
121569static int fts3EvalGatherStats(
121570  Fts3Cursor *pCsr,               /* Cursor object */
121571  Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
121572){
121573  int rc = SQLITE_OK;             /* Return code */
121574
121575  assert( pExpr->eType==FTSQUERY_PHRASE );
121576  if( pExpr->aMI==0 ){
121577    Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121578    Fts3Expr *pRoot;                /* Root of NEAR expression */
121579    Fts3Expr *p;                    /* Iterator used for several purposes */
121580
121581    sqlite3_int64 iPrevId = pCsr->iPrevId;
121582    sqlite3_int64 iDocid;
121583    u8 bEof;
121584
121585    /* Find the root of the NEAR expression */
121586    pRoot = pExpr;
121587    while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
121588      pRoot = pRoot->pParent;
121589    }
121590    iDocid = pRoot->iDocid;
121591    bEof = pRoot->bEof;
121592    assert( pRoot->bStart );
121593
121594    /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
121595    for(p=pRoot; p; p=p->pLeft){
121596      Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
121597      assert( pE->aMI==0 );
121598      pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
121599      if( !pE->aMI ) return SQLITE_NOMEM;
121600      memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
121601    }
121602
121603    fts3EvalRestart(pCsr, pRoot, &rc);
121604
121605    while( pCsr->isEof==0 && rc==SQLITE_OK ){
121606
121607      do {
121608        /* Ensure the %_content statement is reset. */
121609        if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
121610        assert( sqlite3_data_count(pCsr->pStmt)==0 );
121611
121612        /* Advance to the next document */
121613        fts3EvalNextRow(pCsr, pRoot, &rc);
121614        pCsr->isEof = pRoot->bEof;
121615        pCsr->isRequireSeek = 1;
121616        pCsr->isMatchinfoNeeded = 1;
121617        pCsr->iPrevId = pRoot->iDocid;
121618      }while( pCsr->isEof==0
121619           && pRoot->eType==FTSQUERY_NEAR
121620           && fts3EvalTestDeferredAndNear(pCsr, &rc)
121621      );
121622
121623      if( rc==SQLITE_OK && pCsr->isEof==0 ){
121624        fts3EvalUpdateCounts(pRoot);
121625      }
121626    }
121627
121628    pCsr->isEof = 0;
121629    pCsr->iPrevId = iPrevId;
121630
121631    if( bEof ){
121632      pRoot->bEof = bEof;
121633    }else{
121634      /* Caution: pRoot may iterate through docids in ascending or descending
121635      ** order. For this reason, even though it seems more defensive, the
121636      ** do loop can not be written:
121637      **
121638      **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
121639      */
121640      fts3EvalRestart(pCsr, pRoot, &rc);
121641      do {
121642        fts3EvalNextRow(pCsr, pRoot, &rc);
121643        assert( pRoot->bEof==0 );
121644      }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
121645      fts3EvalTestDeferredAndNear(pCsr, &rc);
121646    }
121647  }
121648  return rc;
121649}
121650
121651/*
121652** This function is used by the matchinfo() module to query a phrase
121653** expression node for the following information:
121654**
121655**   1. The total number of occurrences of the phrase in each column of
121656**      the FTS table (considering all rows), and
121657**
121658**   2. For each column, the number of rows in the table for which the
121659**      column contains at least one instance of the phrase.
121660**
121661** If no error occurs, SQLITE_OK is returned and the values for each column
121662** written into the array aiOut as follows:
121663**
121664**   aiOut[iCol*3 + 1] = Number of occurrences
121665**   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
121666**
121667** Caveats:
121668**
121669**   * If a phrase consists entirely of deferred tokens, then all output
121670**     values are set to the number of documents in the table. In other
121671**     words we assume that very common tokens occur exactly once in each
121672**     column of each row of the table.
121673**
121674**   * If a phrase contains some deferred tokens (and some non-deferred
121675**     tokens), count the potential occurrence identified by considering
121676**     the non-deferred tokens instead of actual phrase occurrences.
121677**
121678**   * If the phrase is part of a NEAR expression, then only phrase instances
121679**     that meet the NEAR constraint are included in the counts.
121680*/
121681SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
121682  Fts3Cursor *pCsr,               /* FTS cursor handle */
121683  Fts3Expr *pExpr,                /* Phrase expression */
121684  u32 *aiOut                      /* Array to write results into (see above) */
121685){
121686  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121687  int rc = SQLITE_OK;
121688  int iCol;
121689
121690  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
121691    assert( pCsr->nDoc>0 );
121692    for(iCol=0; iCol<pTab->nColumn; iCol++){
121693      aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
121694      aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
121695    }
121696  }else{
121697    rc = fts3EvalGatherStats(pCsr, pExpr);
121698    if( rc==SQLITE_OK ){
121699      assert( pExpr->aMI );
121700      for(iCol=0; iCol<pTab->nColumn; iCol++){
121701        aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
121702        aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
121703      }
121704    }
121705  }
121706
121707  return rc;
121708}
121709
121710/*
121711** The expression pExpr passed as the second argument to this function
121712** must be of type FTSQUERY_PHRASE.
121713**
121714** The returned value is either NULL or a pointer to a buffer containing
121715** a position-list indicating the occurrences of the phrase in column iCol
121716** of the current row.
121717**
121718** More specifically, the returned buffer contains 1 varint for each
121719** occurence of the phrase in the column, stored using the normal (delta+2)
121720** compression and is terminated by either an 0x01 or 0x00 byte. For example,
121721** if the requested column contains "a b X c d X X" and the position-list
121722** for 'X' is requested, the buffer returned may contain:
121723**
121724**     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
121725**
121726** This function works regardless of whether or not the phrase is deferred,
121727** incremental, or neither.
121728*/
121729SQLITE_PRIVATE char *sqlite3Fts3EvalPhrasePoslist(
121730  Fts3Cursor *pCsr,               /* FTS3 cursor object */
121731  Fts3Expr *pExpr,                /* Phrase to return doclist for */
121732  int iCol                        /* Column to return position list for */
121733){
121734  Fts3Phrase *pPhrase = pExpr->pPhrase;
121735  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
121736  char *pIter = pPhrase->doclist.pList;
121737  int iThis;
121738
121739  assert( iCol>=0 && iCol<pTab->nColumn );
121740  if( !pIter
121741   || pExpr->bEof
121742   || pExpr->iDocid!=pCsr->iPrevId
121743   || (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol)
121744  ){
121745    return 0;
121746  }
121747
121748  assert( pPhrase->doclist.nList>0 );
121749  if( *pIter==0x01 ){
121750    pIter++;
121751    pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
121752  }else{
121753    iThis = 0;
121754  }
121755  while( iThis<iCol ){
121756    fts3ColumnlistCopy(0, &pIter);
121757    if( *pIter==0x00 ) return 0;
121758    pIter++;
121759    pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
121760  }
121761
121762  return ((iCol==iThis)?pIter:0);
121763}
121764
121765/*
121766** Free all components of the Fts3Phrase structure that were allocated by
121767** the eval module. Specifically, this means to free:
121768**
121769**   * the contents of pPhrase->doclist, and
121770**   * any Fts3MultiSegReader objects held by phrase tokens.
121771*/
121772SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
121773  if( pPhrase ){
121774    int i;
121775    sqlite3_free(pPhrase->doclist.aAll);
121776    fts3EvalInvalidatePoslist(pPhrase);
121777    memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
121778    for(i=0; i<pPhrase->nToken; i++){
121779      fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
121780      pPhrase->aToken[i].pSegcsr = 0;
121781    }
121782  }
121783}
121784
121785/*
121786** Return SQLITE_CORRUPT_VTAB.
121787*/
121788#ifdef SQLITE_DEBUG
121789SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
121790  return SQLITE_CORRUPT_VTAB;
121791}
121792#endif
121793
121794#if !SQLITE_CORE
121795/*
121796** Initialize API pointer table, if required.
121797*/
121798SQLITE_API int sqlite3_extension_init(
121799  sqlite3 *db,
121800  char **pzErrMsg,
121801  const sqlite3_api_routines *pApi
121802){
121803  SQLITE_EXTENSION_INIT2(pApi)
121804  return sqlite3Fts3Init(db);
121805}
121806#endif
121807
121808#endif
121809
121810/************** End of fts3.c ************************************************/
121811/************** Begin file fts3_aux.c ****************************************/
121812/*
121813** 2011 Jan 27
121814**
121815** The author disclaims copyright to this source code.  In place of
121816** a legal notice, here is a blessing:
121817**
121818**    May you do good and not evil.
121819**    May you find forgiveness for yourself and forgive others.
121820**    May you share freely, never taking more than you give.
121821**
121822******************************************************************************
121823**
121824*/
121825#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
121826
121827/* #include <string.h> */
121828/* #include <assert.h> */
121829
121830typedef struct Fts3auxTable Fts3auxTable;
121831typedef struct Fts3auxCursor Fts3auxCursor;
121832
121833struct Fts3auxTable {
121834  sqlite3_vtab base;              /* Base class used by SQLite core */
121835  Fts3Table *pFts3Tab;
121836};
121837
121838struct Fts3auxCursor {
121839  sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
121840  Fts3MultiSegReader csr;        /* Must be right after "base" */
121841  Fts3SegFilter filter;
121842  char *zStop;
121843  int nStop;                      /* Byte-length of string zStop */
121844  int isEof;                      /* True if cursor is at EOF */
121845  sqlite3_int64 iRowid;           /* Current rowid */
121846
121847  int iCol;                       /* Current value of 'col' column */
121848  int nStat;                      /* Size of aStat[] array */
121849  struct Fts3auxColstats {
121850    sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
121851    sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
121852  } *aStat;
121853};
121854
121855/*
121856** Schema of the terms table.
121857*/
121858#define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
121859
121860/*
121861** This function does all the work for both the xConnect and xCreate methods.
121862** These tables have no persistent representation of their own, so xConnect
121863** and xCreate are identical operations.
121864*/
121865static int fts3auxConnectMethod(
121866  sqlite3 *db,                    /* Database connection */
121867  void *pUnused,                  /* Unused */
121868  int argc,                       /* Number of elements in argv array */
121869  const char * const *argv,       /* xCreate/xConnect argument array */
121870  sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
121871  char **pzErr                    /* OUT: sqlite3_malloc'd error message */
121872){
121873  char const *zDb;                /* Name of database (e.g. "main") */
121874  char const *zFts3;              /* Name of fts3 table */
121875  int nDb;                        /* Result of strlen(zDb) */
121876  int nFts3;                      /* Result of strlen(zFts3) */
121877  int nByte;                      /* Bytes of space to allocate here */
121878  int rc;                         /* value returned by declare_vtab() */
121879  Fts3auxTable *p;                /* Virtual table object to return */
121880
121881  UNUSED_PARAMETER(pUnused);
121882
121883  /* The user should specify a single argument - the name of an fts3 table. */
121884  if( argc!=4 ){
121885    *pzErr = sqlite3_mprintf(
121886        "wrong number of arguments to fts4aux constructor"
121887    );
121888    return SQLITE_ERROR;
121889  }
121890
121891  zDb = argv[1];
121892  nDb = (int)strlen(zDb);
121893  zFts3 = argv[3];
121894  nFts3 = (int)strlen(zFts3);
121895
121896  rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
121897  if( rc!=SQLITE_OK ) return rc;
121898
121899  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
121900  p = (Fts3auxTable *)sqlite3_malloc(nByte);
121901  if( !p ) return SQLITE_NOMEM;
121902  memset(p, 0, nByte);
121903
121904  p->pFts3Tab = (Fts3Table *)&p[1];
121905  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
121906  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
121907  p->pFts3Tab->db = db;
121908  p->pFts3Tab->nIndex = 1;
121909
121910  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
121911  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
121912  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
121913
121914  *ppVtab = (sqlite3_vtab *)p;
121915  return SQLITE_OK;
121916}
121917
121918/*
121919** This function does the work for both the xDisconnect and xDestroy methods.
121920** These tables have no persistent representation of their own, so xDisconnect
121921** and xDestroy are identical operations.
121922*/
121923static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
121924  Fts3auxTable *p = (Fts3auxTable *)pVtab;
121925  Fts3Table *pFts3 = p->pFts3Tab;
121926  int i;
121927
121928  /* Free any prepared statements held */
121929  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
121930    sqlite3_finalize(pFts3->aStmt[i]);
121931  }
121932  sqlite3_free(pFts3->zSegmentsTbl);
121933  sqlite3_free(p);
121934  return SQLITE_OK;
121935}
121936
121937#define FTS4AUX_EQ_CONSTRAINT 1
121938#define FTS4AUX_GE_CONSTRAINT 2
121939#define FTS4AUX_LE_CONSTRAINT 4
121940
121941/*
121942** xBestIndex - Analyze a WHERE and ORDER BY clause.
121943*/
121944static int fts3auxBestIndexMethod(
121945  sqlite3_vtab *pVTab,
121946  sqlite3_index_info *pInfo
121947){
121948  int i;
121949  int iEq = -1;
121950  int iGe = -1;
121951  int iLe = -1;
121952
121953  UNUSED_PARAMETER(pVTab);
121954
121955  /* This vtab delivers always results in "ORDER BY term ASC" order. */
121956  if( pInfo->nOrderBy==1
121957   && pInfo->aOrderBy[0].iColumn==0
121958   && pInfo->aOrderBy[0].desc==0
121959  ){
121960    pInfo->orderByConsumed = 1;
121961  }
121962
121963  /* Search for equality and range constraints on the "term" column. */
121964  for(i=0; i<pInfo->nConstraint; i++){
121965    if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
121966      int op = pInfo->aConstraint[i].op;
121967      if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
121968      if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
121969      if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
121970      if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
121971      if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
121972    }
121973  }
121974
121975  if( iEq>=0 ){
121976    pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
121977    pInfo->aConstraintUsage[iEq].argvIndex = 1;
121978    pInfo->estimatedCost = 5;
121979  }else{
121980    pInfo->idxNum = 0;
121981    pInfo->estimatedCost = 20000;
121982    if( iGe>=0 ){
121983      pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
121984      pInfo->aConstraintUsage[iGe].argvIndex = 1;
121985      pInfo->estimatedCost /= 2;
121986    }
121987    if( iLe>=0 ){
121988      pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
121989      pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
121990      pInfo->estimatedCost /= 2;
121991    }
121992  }
121993
121994  return SQLITE_OK;
121995}
121996
121997/*
121998** xOpen - Open a cursor.
121999*/
122000static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
122001  Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
122002
122003  UNUSED_PARAMETER(pVTab);
122004
122005  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
122006  if( !pCsr ) return SQLITE_NOMEM;
122007  memset(pCsr, 0, sizeof(Fts3auxCursor));
122008
122009  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
122010  return SQLITE_OK;
122011}
122012
122013/*
122014** xClose - Close a cursor.
122015*/
122016static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
122017  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
122018  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122019
122020  sqlite3Fts3SegmentsClose(pFts3);
122021  sqlite3Fts3SegReaderFinish(&pCsr->csr);
122022  sqlite3_free((void *)pCsr->filter.zTerm);
122023  sqlite3_free(pCsr->zStop);
122024  sqlite3_free(pCsr->aStat);
122025  sqlite3_free(pCsr);
122026  return SQLITE_OK;
122027}
122028
122029static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
122030  if( nSize>pCsr->nStat ){
122031    struct Fts3auxColstats *aNew;
122032    aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
122033        sizeof(struct Fts3auxColstats) * nSize
122034    );
122035    if( aNew==0 ) return SQLITE_NOMEM;
122036    memset(&aNew[pCsr->nStat], 0,
122037        sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
122038    );
122039    pCsr->aStat = aNew;
122040    pCsr->nStat = nSize;
122041  }
122042  return SQLITE_OK;
122043}
122044
122045/*
122046** xNext - Advance the cursor to the next row, if any.
122047*/
122048static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
122049  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122050  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
122051  int rc;
122052
122053  /* Increment our pretend rowid value. */
122054  pCsr->iRowid++;
122055
122056  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
122057    if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
122058  }
122059
122060  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
122061  if( rc==SQLITE_ROW ){
122062    int i = 0;
122063    int nDoclist = pCsr->csr.nDoclist;
122064    char *aDoclist = pCsr->csr.aDoclist;
122065    int iCol;
122066
122067    int eState = 0;
122068
122069    if( pCsr->zStop ){
122070      int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
122071      int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
122072      if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
122073        pCsr->isEof = 1;
122074        return SQLITE_OK;
122075      }
122076    }
122077
122078    if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
122079    memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
122080    iCol = 0;
122081
122082    while( i<nDoclist ){
122083      sqlite3_int64 v = 0;
122084
122085      i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
122086      switch( eState ){
122087        /* State 0. In this state the integer just read was a docid. */
122088        case 0:
122089          pCsr->aStat[0].nDoc++;
122090          eState = 1;
122091          iCol = 0;
122092          break;
122093
122094        /* State 1. In this state we are expecting either a 1, indicating
122095        ** that the following integer will be a column number, or the
122096        ** start of a position list for column 0.
122097        **
122098        ** The only difference between state 1 and state 2 is that if the
122099        ** integer encountered in state 1 is not 0 or 1, then we need to
122100        ** increment the column 0 "nDoc" count for this term.
122101        */
122102        case 1:
122103          assert( iCol==0 );
122104          if( v>1 ){
122105            pCsr->aStat[1].nDoc++;
122106          }
122107          eState = 2;
122108          /* fall through */
122109
122110        case 2:
122111          if( v==0 ){       /* 0x00. Next integer will be a docid. */
122112            eState = 0;
122113          }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
122114            eState = 3;
122115          }else{            /* 2 or greater. A position. */
122116            pCsr->aStat[iCol+1].nOcc++;
122117            pCsr->aStat[0].nOcc++;
122118          }
122119          break;
122120
122121        /* State 3. The integer just read is a column number. */
122122        default: assert( eState==3 );
122123          iCol = (int)v;
122124          if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
122125          pCsr->aStat[iCol+1].nDoc++;
122126          eState = 2;
122127          break;
122128      }
122129    }
122130
122131    pCsr->iCol = 0;
122132    rc = SQLITE_OK;
122133  }else{
122134    pCsr->isEof = 1;
122135  }
122136  return rc;
122137}
122138
122139/*
122140** xFilter - Initialize a cursor to point at the start of its data.
122141*/
122142static int fts3auxFilterMethod(
122143  sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
122144  int idxNum,                     /* Strategy index */
122145  const char *idxStr,             /* Unused */
122146  int nVal,                       /* Number of elements in apVal */
122147  sqlite3_value **apVal           /* Arguments for the indexing scheme */
122148){
122149  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122150  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
122151  int rc;
122152  int isScan;
122153
122154  UNUSED_PARAMETER(nVal);
122155  UNUSED_PARAMETER(idxStr);
122156
122157  assert( idxStr==0 );
122158  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
122159       || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
122160       || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
122161  );
122162  isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
122163
122164  /* In case this cursor is being reused, close and zero it. */
122165  testcase(pCsr->filter.zTerm);
122166  sqlite3Fts3SegReaderFinish(&pCsr->csr);
122167  sqlite3_free((void *)pCsr->filter.zTerm);
122168  sqlite3_free(pCsr->aStat);
122169  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
122170
122171  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
122172  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
122173
122174  if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
122175    const unsigned char *zStr = sqlite3_value_text(apVal[0]);
122176    if( zStr ){
122177      pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
122178      pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
122179      if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
122180    }
122181  }
122182  if( idxNum&FTS4AUX_LE_CONSTRAINT ){
122183    int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
122184    pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
122185    pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
122186    if( pCsr->zStop==0 ) return SQLITE_NOMEM;
122187  }
122188
122189  rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
122190      pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
122191  );
122192  if( rc==SQLITE_OK ){
122193    rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
122194  }
122195
122196  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
122197  return rc;
122198}
122199
122200/*
122201** xEof - Return true if the cursor is at EOF, or false otherwise.
122202*/
122203static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
122204  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122205  return pCsr->isEof;
122206}
122207
122208/*
122209** xColumn - Return a column value.
122210*/
122211static int fts3auxColumnMethod(
122212  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
122213  sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
122214  int iCol                        /* Index of column to read value from */
122215){
122216  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
122217
122218  assert( p->isEof==0 );
122219  if( iCol==0 ){        /* Column "term" */
122220    sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
122221  }else if( iCol==1 ){  /* Column "col" */
122222    if( p->iCol ){
122223      sqlite3_result_int(pContext, p->iCol-1);
122224    }else{
122225      sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
122226    }
122227  }else if( iCol==2 ){  /* Column "documents" */
122228    sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
122229  }else{                /* Column "occurrences" */
122230    sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
122231  }
122232
122233  return SQLITE_OK;
122234}
122235
122236/*
122237** xRowid - Return the current rowid for the cursor.
122238*/
122239static int fts3auxRowidMethod(
122240  sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
122241  sqlite_int64 *pRowid            /* OUT: Rowid value */
122242){
122243  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
122244  *pRowid = pCsr->iRowid;
122245  return SQLITE_OK;
122246}
122247
122248/*
122249** Register the fts3aux module with database connection db. Return SQLITE_OK
122250** if successful or an error code if sqlite3_create_module() fails.
122251*/
122252SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
122253  static const sqlite3_module fts3aux_module = {
122254     0,                           /* iVersion      */
122255     fts3auxConnectMethod,        /* xCreate       */
122256     fts3auxConnectMethod,        /* xConnect      */
122257     fts3auxBestIndexMethod,      /* xBestIndex    */
122258     fts3auxDisconnectMethod,     /* xDisconnect   */
122259     fts3auxDisconnectMethod,     /* xDestroy      */
122260     fts3auxOpenMethod,           /* xOpen         */
122261     fts3auxCloseMethod,          /* xClose        */
122262     fts3auxFilterMethod,         /* xFilter       */
122263     fts3auxNextMethod,           /* xNext         */
122264     fts3auxEofMethod,            /* xEof          */
122265     fts3auxColumnMethod,         /* xColumn       */
122266     fts3auxRowidMethod,          /* xRowid        */
122267     0,                           /* xUpdate       */
122268     0,                           /* xBegin        */
122269     0,                           /* xSync         */
122270     0,                           /* xCommit       */
122271     0,                           /* xRollback     */
122272     0,                           /* xFindFunction */
122273     0,                           /* xRename       */
122274     0,                           /* xSavepoint    */
122275     0,                           /* xRelease      */
122276     0                            /* xRollbackTo   */
122277  };
122278  int rc;                         /* Return code */
122279
122280  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
122281  return rc;
122282}
122283
122284#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
122285
122286/************** End of fts3_aux.c ********************************************/
122287/************** Begin file fts3_expr.c ***************************************/
122288/*
122289** 2008 Nov 28
122290**
122291** The author disclaims copyright to this source code.  In place of
122292** a legal notice, here is a blessing:
122293**
122294**    May you do good and not evil.
122295**    May you find forgiveness for yourself and forgive others.
122296**    May you share freely, never taking more than you give.
122297**
122298******************************************************************************
122299**
122300** This module contains code that implements a parser for fts3 query strings
122301** (the right-hand argument to the MATCH operator). Because the supported
122302** syntax is relatively simple, the whole tokenizer/parser system is
122303** hand-coded.
122304*/
122305#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
122306
122307/*
122308** By default, this module parses the legacy syntax that has been
122309** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
122310** is defined, then it uses the new syntax. The differences between
122311** the new and the old syntaxes are:
122312**
122313**  a) The new syntax supports parenthesis. The old does not.
122314**
122315**  b) The new syntax supports the AND and NOT operators. The old does not.
122316**
122317**  c) The old syntax supports the "-" token qualifier. This is not
122318**     supported by the new syntax (it is replaced by the NOT operator).
122319**
122320**  d) When using the old syntax, the OR operator has a greater precedence
122321**     than an implicit AND. When using the new, both implicity and explicit
122322**     AND operators have a higher precedence than OR.
122323**
122324** If compiled with SQLITE_TEST defined, then this module exports the
122325** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
122326** to zero causes the module to use the old syntax. If it is set to
122327** non-zero the new syntax is activated. This is so both syntaxes can
122328** be tested using a single build of testfixture.
122329**
122330** The following describes the syntax supported by the fts3 MATCH
122331** operator in a similar format to that used by the lemon parser
122332** generator. This module does not use actually lemon, it uses a
122333** custom parser.
122334**
122335**   query ::= andexpr (OR andexpr)*.
122336**
122337**   andexpr ::= notexpr (AND? notexpr)*.
122338**
122339**   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
122340**   notexpr ::= LP query RP.
122341**
122342**   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
122343**
122344**   distance_opt ::= .
122345**   distance_opt ::= / INTEGER.
122346**
122347**   phrase ::= TOKEN.
122348**   phrase ::= COLUMN:TOKEN.
122349**   phrase ::= "TOKEN TOKEN TOKEN...".
122350*/
122351
122352#ifdef SQLITE_TEST
122353SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
122354#else
122355# ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
122356#  define sqlite3_fts3_enable_parentheses 1
122357# else
122358#  define sqlite3_fts3_enable_parentheses 0
122359# endif
122360#endif
122361
122362/*
122363** Default span for NEAR operators.
122364*/
122365#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
122366
122367/* #include <string.h> */
122368/* #include <assert.h> */
122369
122370/*
122371** isNot:
122372**   This variable is used by function getNextNode(). When getNextNode() is
122373**   called, it sets ParseContext.isNot to true if the 'next node' is a
122374**   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
122375**   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
122376**   zero.
122377*/
122378typedef struct ParseContext ParseContext;
122379struct ParseContext {
122380  sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
122381  int iLangid;                        /* Language id used with tokenizer */
122382  const char **azCol;                 /* Array of column names for fts3 table */
122383  int bFts4;                          /* True to allow FTS4-only syntax */
122384  int nCol;                           /* Number of entries in azCol[] */
122385  int iDefaultCol;                    /* Default column to query */
122386  int isNot;                          /* True if getNextNode() sees a unary - */
122387  sqlite3_context *pCtx;              /* Write error message here */
122388  int nNest;                          /* Number of nested brackets */
122389};
122390
122391/*
122392** This function is equivalent to the standard isspace() function.
122393**
122394** The standard isspace() can be awkward to use safely, because although it
122395** is defined to accept an argument of type int, its behaviour when passed
122396** an integer that falls outside of the range of the unsigned char type
122397** is undefined (and sometimes, "undefined" means segfault). This wrapper
122398** is defined to accept an argument of type char, and always returns 0 for
122399** any values that fall outside of the range of the unsigned char type (i.e.
122400** negative values).
122401*/
122402static int fts3isspace(char c){
122403  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
122404}
122405
122406/*
122407** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
122408** zero the memory before returning a pointer to it. If unsuccessful,
122409** return NULL.
122410*/
122411static void *fts3MallocZero(int nByte){
122412  void *pRet = sqlite3_malloc(nByte);
122413  if( pRet ) memset(pRet, 0, nByte);
122414  return pRet;
122415}
122416
122417SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
122418  sqlite3_tokenizer *pTokenizer,
122419  int iLangid,
122420  const char *z,
122421  int n,
122422  sqlite3_tokenizer_cursor **ppCsr
122423){
122424  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
122425  sqlite3_tokenizer_cursor *pCsr = 0;
122426  int rc;
122427
122428  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
122429  assert( rc==SQLITE_OK || pCsr==0 );
122430  if( rc==SQLITE_OK ){
122431    pCsr->pTokenizer = pTokenizer;
122432    if( pModule->iVersion>=1 ){
122433      rc = pModule->xLanguageid(pCsr, iLangid);
122434      if( rc!=SQLITE_OK ){
122435        pModule->xClose(pCsr);
122436        pCsr = 0;
122437      }
122438    }
122439  }
122440  *ppCsr = pCsr;
122441  return rc;
122442}
122443
122444
122445/*
122446** Extract the next token from buffer z (length n) using the tokenizer
122447** and other information (column names etc.) in pParse. Create an Fts3Expr
122448** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
122449** single token and set *ppExpr to point to it. If the end of the buffer is
122450** reached before a token is found, set *ppExpr to zero. It is the
122451** responsibility of the caller to eventually deallocate the allocated
122452** Fts3Expr structure (if any) by passing it to sqlite3_free().
122453**
122454** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
122455** fails.
122456*/
122457static int getNextToken(
122458  ParseContext *pParse,                   /* fts3 query parse context */
122459  int iCol,                               /* Value for Fts3Phrase.iColumn */
122460  const char *z, int n,                   /* Input string */
122461  Fts3Expr **ppExpr,                      /* OUT: expression */
122462  int *pnConsumed                         /* OUT: Number of bytes consumed */
122463){
122464  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
122465  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
122466  int rc;
122467  sqlite3_tokenizer_cursor *pCursor;
122468  Fts3Expr *pRet = 0;
122469  int nConsumed = 0;
122470
122471  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
122472  if( rc==SQLITE_OK ){
122473    const char *zToken;
122474    int nToken, iStart, iEnd, iPosition;
122475    int nByte;                               /* total space to allocate */
122476
122477    rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
122478    if( rc==SQLITE_OK ){
122479      nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
122480      pRet = (Fts3Expr *)fts3MallocZero(nByte);
122481      if( !pRet ){
122482        rc = SQLITE_NOMEM;
122483      }else{
122484        pRet->eType = FTSQUERY_PHRASE;
122485        pRet->pPhrase = (Fts3Phrase *)&pRet[1];
122486        pRet->pPhrase->nToken = 1;
122487        pRet->pPhrase->iColumn = iCol;
122488        pRet->pPhrase->aToken[0].n = nToken;
122489        pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
122490        memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
122491
122492        if( iEnd<n && z[iEnd]=='*' ){
122493          pRet->pPhrase->aToken[0].isPrefix = 1;
122494          iEnd++;
122495        }
122496
122497        while( 1 ){
122498          if( !sqlite3_fts3_enable_parentheses
122499           && iStart>0 && z[iStart-1]=='-'
122500          ){
122501            pParse->isNot = 1;
122502            iStart--;
122503          }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
122504            pRet->pPhrase->aToken[0].bFirst = 1;
122505            iStart--;
122506          }else{
122507            break;
122508          }
122509        }
122510
122511      }
122512      nConsumed = iEnd;
122513    }
122514
122515    pModule->xClose(pCursor);
122516  }
122517
122518  *pnConsumed = nConsumed;
122519  *ppExpr = pRet;
122520  return rc;
122521}
122522
122523
122524/*
122525** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
122526** then free the old allocation.
122527*/
122528static void *fts3ReallocOrFree(void *pOrig, int nNew){
122529  void *pRet = sqlite3_realloc(pOrig, nNew);
122530  if( !pRet ){
122531    sqlite3_free(pOrig);
122532  }
122533  return pRet;
122534}
122535
122536/*
122537** Buffer zInput, length nInput, contains the contents of a quoted string
122538** that appeared as part of an fts3 query expression. Neither quote character
122539** is included in the buffer. This function attempts to tokenize the entire
122540** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
122541** containing the results.
122542**
122543** If successful, SQLITE_OK is returned and *ppExpr set to point at the
122544** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
122545** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
122546** to 0.
122547*/
122548static int getNextString(
122549  ParseContext *pParse,                   /* fts3 query parse context */
122550  const char *zInput, int nInput,         /* Input string */
122551  Fts3Expr **ppExpr                       /* OUT: expression */
122552){
122553  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
122554  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
122555  int rc;
122556  Fts3Expr *p = 0;
122557  sqlite3_tokenizer_cursor *pCursor = 0;
122558  char *zTemp = 0;
122559  int nTemp = 0;
122560
122561  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
122562  int nToken = 0;
122563
122564  /* The final Fts3Expr data structure, including the Fts3Phrase,
122565  ** Fts3PhraseToken structures token buffers are all stored as a single
122566  ** allocation so that the expression can be freed with a single call to
122567  ** sqlite3_free(). Setting this up requires a two pass approach.
122568  **
122569  ** The first pass, in the block below, uses a tokenizer cursor to iterate
122570  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
122571  ** to assemble data in two dynamic buffers:
122572  **
122573  **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
122574  **             structure, followed by the array of Fts3PhraseToken
122575  **             structures. This pass only populates the Fts3PhraseToken array.
122576  **
122577  **   Buffer zTemp: Contains copies of all tokens.
122578  **
122579  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
122580  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
122581  ** structures.
122582  */
122583  rc = sqlite3Fts3OpenTokenizer(
122584      pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
122585  if( rc==SQLITE_OK ){
122586    int ii;
122587    for(ii=0; rc==SQLITE_OK; ii++){
122588      const char *zByte;
122589      int nByte, iBegin, iEnd, iPos;
122590      rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
122591      if( rc==SQLITE_OK ){
122592        Fts3PhraseToken *pToken;
122593
122594        p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
122595        if( !p ) goto no_mem;
122596
122597        zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
122598        if( !zTemp ) goto no_mem;
122599
122600        assert( nToken==ii );
122601        pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
122602        memset(pToken, 0, sizeof(Fts3PhraseToken));
122603
122604        memcpy(&zTemp[nTemp], zByte, nByte);
122605        nTemp += nByte;
122606
122607        pToken->n = nByte;
122608        pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
122609        pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
122610        nToken = ii+1;
122611      }
122612    }
122613
122614    pModule->xClose(pCursor);
122615    pCursor = 0;
122616  }
122617
122618  if( rc==SQLITE_DONE ){
122619    int jj;
122620    char *zBuf = 0;
122621
122622    p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
122623    if( !p ) goto no_mem;
122624    memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
122625    p->eType = FTSQUERY_PHRASE;
122626    p->pPhrase = (Fts3Phrase *)&p[1];
122627    p->pPhrase->iColumn = pParse->iDefaultCol;
122628    p->pPhrase->nToken = nToken;
122629
122630    zBuf = (char *)&p->pPhrase->aToken[nToken];
122631    if( zTemp ){
122632      memcpy(zBuf, zTemp, nTemp);
122633      sqlite3_free(zTemp);
122634    }else{
122635      assert( nTemp==0 );
122636    }
122637
122638    for(jj=0; jj<p->pPhrase->nToken; jj++){
122639      p->pPhrase->aToken[jj].z = zBuf;
122640      zBuf += p->pPhrase->aToken[jj].n;
122641    }
122642    rc = SQLITE_OK;
122643  }
122644
122645  *ppExpr = p;
122646  return rc;
122647no_mem:
122648
122649  if( pCursor ){
122650    pModule->xClose(pCursor);
122651  }
122652  sqlite3_free(zTemp);
122653  sqlite3_free(p);
122654  *ppExpr = 0;
122655  return SQLITE_NOMEM;
122656}
122657
122658/*
122659** Function getNextNode(), which is called by fts3ExprParse(), may itself
122660** call fts3ExprParse(). So this forward declaration is required.
122661*/
122662static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
122663
122664/*
122665** The output variable *ppExpr is populated with an allocated Fts3Expr
122666** structure, or set to 0 if the end of the input buffer is reached.
122667**
122668** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
122669** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
122670** If SQLITE_ERROR is returned, pContext is populated with an error message.
122671*/
122672static int getNextNode(
122673  ParseContext *pParse,                   /* fts3 query parse context */
122674  const char *z, int n,                   /* Input string */
122675  Fts3Expr **ppExpr,                      /* OUT: expression */
122676  int *pnConsumed                         /* OUT: Number of bytes consumed */
122677){
122678  static const struct Fts3Keyword {
122679    char *z;                              /* Keyword text */
122680    unsigned char n;                      /* Length of the keyword */
122681    unsigned char parenOnly;              /* Only valid in paren mode */
122682    unsigned char eType;                  /* Keyword code */
122683  } aKeyword[] = {
122684    { "OR" ,  2, 0, FTSQUERY_OR   },
122685    { "AND",  3, 1, FTSQUERY_AND  },
122686    { "NOT",  3, 1, FTSQUERY_NOT  },
122687    { "NEAR", 4, 0, FTSQUERY_NEAR }
122688  };
122689  int ii;
122690  int iCol;
122691  int iColLen;
122692  int rc;
122693  Fts3Expr *pRet = 0;
122694
122695  const char *zInput = z;
122696  int nInput = n;
122697
122698  pParse->isNot = 0;
122699
122700  /* Skip over any whitespace before checking for a keyword, an open or
122701  ** close bracket, or a quoted string.
122702  */
122703  while( nInput>0 && fts3isspace(*zInput) ){
122704    nInput--;
122705    zInput++;
122706  }
122707  if( nInput==0 ){
122708    return SQLITE_DONE;
122709  }
122710
122711  /* See if we are dealing with a keyword. */
122712  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
122713    const struct Fts3Keyword *pKey = &aKeyword[ii];
122714
122715    if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
122716      continue;
122717    }
122718
122719    if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
122720      int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
122721      int nKey = pKey->n;
122722      char cNext;
122723
122724      /* If this is a "NEAR" keyword, check for an explicit nearness. */
122725      if( pKey->eType==FTSQUERY_NEAR ){
122726        assert( nKey==4 );
122727        if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
122728          nNear = 0;
122729          for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
122730            nNear = nNear * 10 + (zInput[nKey] - '0');
122731          }
122732        }
122733      }
122734
122735      /* At this point this is probably a keyword. But for that to be true,
122736      ** the next byte must contain either whitespace, an open or close
122737      ** parenthesis, a quote character, or EOF.
122738      */
122739      cNext = zInput[nKey];
122740      if( fts3isspace(cNext)
122741       || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
122742      ){
122743        pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
122744        if( !pRet ){
122745          return SQLITE_NOMEM;
122746        }
122747        pRet->eType = pKey->eType;
122748        pRet->nNear = nNear;
122749        *ppExpr = pRet;
122750        *pnConsumed = (int)((zInput - z) + nKey);
122751        return SQLITE_OK;
122752      }
122753
122754      /* Turns out that wasn't a keyword after all. This happens if the
122755      ** user has supplied a token such as "ORacle". Continue.
122756      */
122757    }
122758  }
122759
122760  /* Check for an open bracket. */
122761  if( sqlite3_fts3_enable_parentheses ){
122762    if( *zInput=='(' ){
122763      int nConsumed;
122764      pParse->nNest++;
122765      rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
122766      if( rc==SQLITE_OK && !*ppExpr ){
122767        rc = SQLITE_DONE;
122768      }
122769      *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
122770      return rc;
122771    }
122772
122773    /* Check for a close bracket. */
122774    if( *zInput==')' ){
122775      pParse->nNest--;
122776      *pnConsumed = (int)((zInput - z) + 1);
122777      return SQLITE_DONE;
122778    }
122779  }
122780
122781  /* See if we are dealing with a quoted phrase. If this is the case, then
122782  ** search for the closing quote and pass the whole string to getNextString()
122783  ** for processing. This is easy to do, as fts3 has no syntax for escaping
122784  ** a quote character embedded in a string.
122785  */
122786  if( *zInput=='"' ){
122787    for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
122788    *pnConsumed = (int)((zInput - z) + ii + 1);
122789    if( ii==nInput ){
122790      return SQLITE_ERROR;
122791    }
122792    return getNextString(pParse, &zInput[1], ii-1, ppExpr);
122793  }
122794
122795
122796  /* If control flows to this point, this must be a regular token, or
122797  ** the end of the input. Read a regular token using the sqlite3_tokenizer
122798  ** interface. Before doing so, figure out if there is an explicit
122799  ** column specifier for the token.
122800  **
122801  ** TODO: Strangely, it is not possible to associate a column specifier
122802  ** with a quoted phrase, only with a single token. Not sure if this was
122803  ** an implementation artifact or an intentional decision when fts3 was
122804  ** first implemented. Whichever it was, this module duplicates the
122805  ** limitation.
122806  */
122807  iCol = pParse->iDefaultCol;
122808  iColLen = 0;
122809  for(ii=0; ii<pParse->nCol; ii++){
122810    const char *zStr = pParse->azCol[ii];
122811    int nStr = (int)strlen(zStr);
122812    if( nInput>nStr && zInput[nStr]==':'
122813     && sqlite3_strnicmp(zStr, zInput, nStr)==0
122814    ){
122815      iCol = ii;
122816      iColLen = (int)((zInput - z) + nStr + 1);
122817      break;
122818    }
122819  }
122820  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
122821  *pnConsumed += iColLen;
122822  return rc;
122823}
122824
122825/*
122826** The argument is an Fts3Expr structure for a binary operator (any type
122827** except an FTSQUERY_PHRASE). Return an integer value representing the
122828** precedence of the operator. Lower values have a higher precedence (i.e.
122829** group more tightly). For example, in the C language, the == operator
122830** groups more tightly than ||, and would therefore have a higher precedence.
122831**
122832** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
122833** is defined), the order of the operators in precedence from highest to
122834** lowest is:
122835**
122836**   NEAR
122837**   NOT
122838**   AND (including implicit ANDs)
122839**   OR
122840**
122841** Note that when using the old query syntax, the OR operator has a higher
122842** precedence than the AND operator.
122843*/
122844static int opPrecedence(Fts3Expr *p){
122845  assert( p->eType!=FTSQUERY_PHRASE );
122846  if( sqlite3_fts3_enable_parentheses ){
122847    return p->eType;
122848  }else if( p->eType==FTSQUERY_NEAR ){
122849    return 1;
122850  }else if( p->eType==FTSQUERY_OR ){
122851    return 2;
122852  }
122853  assert( p->eType==FTSQUERY_AND );
122854  return 3;
122855}
122856
122857/*
122858** Argument ppHead contains a pointer to the current head of a query
122859** expression tree being parsed. pPrev is the expression node most recently
122860** inserted into the tree. This function adds pNew, which is always a binary
122861** operator node, into the expression tree based on the relative precedence
122862** of pNew and the existing nodes of the tree. This may result in the head
122863** of the tree changing, in which case *ppHead is set to the new root node.
122864*/
122865static void insertBinaryOperator(
122866  Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
122867  Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
122868  Fts3Expr *pNew           /* New binary node to insert into expression tree */
122869){
122870  Fts3Expr *pSplit = pPrev;
122871  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
122872    pSplit = pSplit->pParent;
122873  }
122874
122875  if( pSplit->pParent ){
122876    assert( pSplit->pParent->pRight==pSplit );
122877    pSplit->pParent->pRight = pNew;
122878    pNew->pParent = pSplit->pParent;
122879  }else{
122880    *ppHead = pNew;
122881  }
122882  pNew->pLeft = pSplit;
122883  pSplit->pParent = pNew;
122884}
122885
122886/*
122887** Parse the fts3 query expression found in buffer z, length n. This function
122888** returns either when the end of the buffer is reached or an unmatched
122889** closing bracket - ')' - is encountered.
122890**
122891** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
122892** parsed form of the expression and *pnConsumed is set to the number of
122893** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
122894** (out of memory error) or SQLITE_ERROR (parse error) is returned.
122895*/
122896static int fts3ExprParse(
122897  ParseContext *pParse,                   /* fts3 query parse context */
122898  const char *z, int n,                   /* Text of MATCH query */
122899  Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
122900  int *pnConsumed                         /* OUT: Number of bytes consumed */
122901){
122902  Fts3Expr *pRet = 0;
122903  Fts3Expr *pPrev = 0;
122904  Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
122905  int nIn = n;
122906  const char *zIn = z;
122907  int rc = SQLITE_OK;
122908  int isRequirePhrase = 1;
122909
122910  while( rc==SQLITE_OK ){
122911    Fts3Expr *p = 0;
122912    int nByte = 0;
122913    rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
122914    if( rc==SQLITE_OK ){
122915      int isPhrase;
122916
122917      if( !sqlite3_fts3_enable_parentheses
122918       && p->eType==FTSQUERY_PHRASE && pParse->isNot
122919      ){
122920        /* Create an implicit NOT operator. */
122921        Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
122922        if( !pNot ){
122923          sqlite3Fts3ExprFree(p);
122924          rc = SQLITE_NOMEM;
122925          goto exprparse_out;
122926        }
122927        pNot->eType = FTSQUERY_NOT;
122928        pNot->pRight = p;
122929        if( pNotBranch ){
122930          pNot->pLeft = pNotBranch;
122931        }
122932        pNotBranch = pNot;
122933        p = pPrev;
122934      }else{
122935        int eType = p->eType;
122936        isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
122937
122938        /* The isRequirePhrase variable is set to true if a phrase or
122939        ** an expression contained in parenthesis is required. If a
122940        ** binary operator (AND, OR, NOT or NEAR) is encounted when
122941        ** isRequirePhrase is set, this is a syntax error.
122942        */
122943        if( !isPhrase && isRequirePhrase ){
122944          sqlite3Fts3ExprFree(p);
122945          rc = SQLITE_ERROR;
122946          goto exprparse_out;
122947        }
122948
122949        if( isPhrase && !isRequirePhrase ){
122950          /* Insert an implicit AND operator. */
122951          Fts3Expr *pAnd;
122952          assert( pRet && pPrev );
122953          pAnd = fts3MallocZero(sizeof(Fts3Expr));
122954          if( !pAnd ){
122955            sqlite3Fts3ExprFree(p);
122956            rc = SQLITE_NOMEM;
122957            goto exprparse_out;
122958          }
122959          pAnd->eType = FTSQUERY_AND;
122960          insertBinaryOperator(&pRet, pPrev, pAnd);
122961          pPrev = pAnd;
122962        }
122963
122964        /* This test catches attempts to make either operand of a NEAR
122965        ** operator something other than a phrase. For example, either of
122966        ** the following:
122967        **
122968        **    (bracketed expression) NEAR phrase
122969        **    phrase NEAR (bracketed expression)
122970        **
122971        ** Return an error in either case.
122972        */
122973        if( pPrev && (
122974            (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
122975         || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
122976        )){
122977          sqlite3Fts3ExprFree(p);
122978          rc = SQLITE_ERROR;
122979          goto exprparse_out;
122980        }
122981
122982        if( isPhrase ){
122983          if( pRet ){
122984            assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
122985            pPrev->pRight = p;
122986            p->pParent = pPrev;
122987          }else{
122988            pRet = p;
122989          }
122990        }else{
122991          insertBinaryOperator(&pRet, pPrev, p);
122992        }
122993        isRequirePhrase = !isPhrase;
122994      }
122995      assert( nByte>0 );
122996    }
122997    assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
122998    nIn -= nByte;
122999    zIn += nByte;
123000    pPrev = p;
123001  }
123002
123003  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
123004    rc = SQLITE_ERROR;
123005  }
123006
123007  if( rc==SQLITE_DONE ){
123008    rc = SQLITE_OK;
123009    if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
123010      if( !pRet ){
123011        rc = SQLITE_ERROR;
123012      }else{
123013        Fts3Expr *pIter = pNotBranch;
123014        while( pIter->pLeft ){
123015          pIter = pIter->pLeft;
123016        }
123017        pIter->pLeft = pRet;
123018        pRet = pNotBranch;
123019      }
123020    }
123021  }
123022  *pnConsumed = n - nIn;
123023
123024exprparse_out:
123025  if( rc!=SQLITE_OK ){
123026    sqlite3Fts3ExprFree(pRet);
123027    sqlite3Fts3ExprFree(pNotBranch);
123028    pRet = 0;
123029  }
123030  *ppExpr = pRet;
123031  return rc;
123032}
123033
123034/*
123035** Parameters z and n contain a pointer to and length of a buffer containing
123036** an fts3 query expression, respectively. This function attempts to parse the
123037** query expression and create a tree of Fts3Expr structures representing the
123038** parsed expression. If successful, *ppExpr is set to point to the head
123039** of the parsed expression tree and SQLITE_OK is returned. If an error
123040** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
123041** error) is returned and *ppExpr is set to 0.
123042**
123043** If parameter n is a negative number, then z is assumed to point to a
123044** nul-terminated string and the length is determined using strlen().
123045**
123046** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
123047** use to normalize query tokens while parsing the expression. The azCol[]
123048** array, which is assumed to contain nCol entries, should contain the names
123049** of each column in the target fts3 table, in order from left to right.
123050** Column names must be nul-terminated strings.
123051**
123052** The iDefaultCol parameter should be passed the index of the table column
123053** that appears on the left-hand-side of the MATCH operator (the default
123054** column to match against for tokens for which a column name is not explicitly
123055** specified as part of the query string), or -1 if tokens may by default
123056** match any table column.
123057*/
123058SQLITE_PRIVATE int sqlite3Fts3ExprParse(
123059  sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
123060  int iLangid,                        /* Language id for tokenizer */
123061  char **azCol,                       /* Array of column names for fts3 table */
123062  int bFts4,                          /* True to allow FTS4-only syntax */
123063  int nCol,                           /* Number of entries in azCol[] */
123064  int iDefaultCol,                    /* Default column to query */
123065  const char *z, int n,               /* Text of MATCH query */
123066  Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
123067){
123068  int nParsed;
123069  int rc;
123070  ParseContext sParse;
123071
123072  memset(&sParse, 0, sizeof(ParseContext));
123073  sParse.pTokenizer = pTokenizer;
123074  sParse.iLangid = iLangid;
123075  sParse.azCol = (const char **)azCol;
123076  sParse.nCol = nCol;
123077  sParse.iDefaultCol = iDefaultCol;
123078  sParse.bFts4 = bFts4;
123079  if( z==0 ){
123080    *ppExpr = 0;
123081    return SQLITE_OK;
123082  }
123083  if( n<0 ){
123084    n = (int)strlen(z);
123085  }
123086  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
123087
123088  /* Check for mismatched parenthesis */
123089  if( rc==SQLITE_OK && sParse.nNest ){
123090    rc = SQLITE_ERROR;
123091    sqlite3Fts3ExprFree(*ppExpr);
123092    *ppExpr = 0;
123093  }
123094
123095  return rc;
123096}
123097
123098/*
123099** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
123100*/
123101SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
123102  if( p ){
123103    assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
123104    sqlite3Fts3ExprFree(p->pLeft);
123105    sqlite3Fts3ExprFree(p->pRight);
123106    sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
123107    sqlite3_free(p->aMI);
123108    sqlite3_free(p);
123109  }
123110}
123111
123112/****************************************************************************
123113*****************************************************************************
123114** Everything after this point is just test code.
123115*/
123116
123117#ifdef SQLITE_TEST
123118
123119/* #include <stdio.h> */
123120
123121/*
123122** Function to query the hash-table of tokenizers (see README.tokenizers).
123123*/
123124static int queryTestTokenizer(
123125  sqlite3 *db,
123126  const char *zName,
123127  const sqlite3_tokenizer_module **pp
123128){
123129  int rc;
123130  sqlite3_stmt *pStmt;
123131  const char zSql[] = "SELECT fts3_tokenizer(?)";
123132
123133  *pp = 0;
123134  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
123135  if( rc!=SQLITE_OK ){
123136    return rc;
123137  }
123138
123139  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
123140  if( SQLITE_ROW==sqlite3_step(pStmt) ){
123141    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
123142      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
123143    }
123144  }
123145
123146  return sqlite3_finalize(pStmt);
123147}
123148
123149/*
123150** Return a pointer to a buffer containing a text representation of the
123151** expression passed as the first argument. The buffer is obtained from
123152** sqlite3_malloc(). It is the responsibility of the caller to use
123153** sqlite3_free() to release the memory. If an OOM condition is encountered,
123154** NULL is returned.
123155**
123156** If the second argument is not NULL, then its contents are prepended to
123157** the returned expression text and then freed using sqlite3_free().
123158*/
123159static char *exprToString(Fts3Expr *pExpr, char *zBuf){
123160  switch( pExpr->eType ){
123161    case FTSQUERY_PHRASE: {
123162      Fts3Phrase *pPhrase = pExpr->pPhrase;
123163      int i;
123164      zBuf = sqlite3_mprintf(
123165          "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
123166      for(i=0; zBuf && i<pPhrase->nToken; i++){
123167        zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
123168            pPhrase->aToken[i].n, pPhrase->aToken[i].z,
123169            (pPhrase->aToken[i].isPrefix?"+":"")
123170        );
123171      }
123172      return zBuf;
123173    }
123174
123175    case FTSQUERY_NEAR:
123176      zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
123177      break;
123178    case FTSQUERY_NOT:
123179      zBuf = sqlite3_mprintf("%zNOT ", zBuf);
123180      break;
123181    case FTSQUERY_AND:
123182      zBuf = sqlite3_mprintf("%zAND ", zBuf);
123183      break;
123184    case FTSQUERY_OR:
123185      zBuf = sqlite3_mprintf("%zOR ", zBuf);
123186      break;
123187  }
123188
123189  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
123190  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
123191  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
123192
123193  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
123194  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
123195
123196  return zBuf;
123197}
123198
123199/*
123200** This is the implementation of a scalar SQL function used to test the
123201** expression parser. It should be called as follows:
123202**
123203**   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
123204**
123205** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
123206** to parse the query expression (see README.tokenizers). The second argument
123207** is the query expression to parse. Each subsequent argument is the name
123208** of a column of the fts3 table that the query expression may refer to.
123209** For example:
123210**
123211**   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
123212*/
123213static void fts3ExprTest(
123214  sqlite3_context *context,
123215  int argc,
123216  sqlite3_value **argv
123217){
123218  sqlite3_tokenizer_module const *pModule = 0;
123219  sqlite3_tokenizer *pTokenizer = 0;
123220  int rc;
123221  char **azCol = 0;
123222  const char *zExpr;
123223  int nExpr;
123224  int nCol;
123225  int ii;
123226  Fts3Expr *pExpr;
123227  char *zBuf = 0;
123228  sqlite3 *db = sqlite3_context_db_handle(context);
123229
123230  if( argc<3 ){
123231    sqlite3_result_error(context,
123232        "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
123233    );
123234    return;
123235  }
123236
123237  rc = queryTestTokenizer(db,
123238                          (const char *)sqlite3_value_text(argv[0]), &pModule);
123239  if( rc==SQLITE_NOMEM ){
123240    sqlite3_result_error_nomem(context);
123241    goto exprtest_out;
123242  }else if( !pModule ){
123243    sqlite3_result_error(context, "No such tokenizer module", -1);
123244    goto exprtest_out;
123245  }
123246
123247  rc = pModule->xCreate(0, 0, &pTokenizer);
123248  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
123249  if( rc==SQLITE_NOMEM ){
123250    sqlite3_result_error_nomem(context);
123251    goto exprtest_out;
123252  }
123253  pTokenizer->pModule = pModule;
123254
123255  zExpr = (const char *)sqlite3_value_text(argv[1]);
123256  nExpr = sqlite3_value_bytes(argv[1]);
123257  nCol = argc-2;
123258  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
123259  if( !azCol ){
123260    sqlite3_result_error_nomem(context);
123261    goto exprtest_out;
123262  }
123263  for(ii=0; ii<nCol; ii++){
123264    azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
123265  }
123266
123267  rc = sqlite3Fts3ExprParse(
123268      pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
123269  );
123270  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
123271    sqlite3_result_error(context, "Error parsing expression", -1);
123272  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
123273    sqlite3_result_error_nomem(context);
123274  }else{
123275    sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
123276    sqlite3_free(zBuf);
123277  }
123278
123279  sqlite3Fts3ExprFree(pExpr);
123280
123281exprtest_out:
123282  if( pModule && pTokenizer ){
123283    rc = pModule->xDestroy(pTokenizer);
123284  }
123285  sqlite3_free(azCol);
123286}
123287
123288/*
123289** Register the query expression parser test function fts3_exprtest()
123290** with database connection db.
123291*/
123292SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
123293  return sqlite3_create_function(
123294      db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
123295  );
123296}
123297
123298#endif
123299#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123300
123301/************** End of fts3_expr.c *******************************************/
123302/************** Begin file fts3_hash.c ***************************************/
123303/*
123304** 2001 September 22
123305**
123306** The author disclaims copyright to this source code.  In place of
123307** a legal notice, here is a blessing:
123308**
123309**    May you do good and not evil.
123310**    May you find forgiveness for yourself and forgive others.
123311**    May you share freely, never taking more than you give.
123312**
123313*************************************************************************
123314** This is the implementation of generic hash-tables used in SQLite.
123315** We've modified it slightly to serve as a standalone hash table
123316** implementation for the full-text indexing module.
123317*/
123318
123319/*
123320** The code in this file is only compiled if:
123321**
123322**     * The FTS3 module is being built as an extension
123323**       (in which case SQLITE_CORE is not defined), or
123324**
123325**     * The FTS3 module is being built into the core of
123326**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
123327*/
123328#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123329
123330/* #include <assert.h> */
123331/* #include <stdlib.h> */
123332/* #include <string.h> */
123333
123334
123335/*
123336** Malloc and Free functions
123337*/
123338static void *fts3HashMalloc(int n){
123339  void *p = sqlite3_malloc(n);
123340  if( p ){
123341    memset(p, 0, n);
123342  }
123343  return p;
123344}
123345static void fts3HashFree(void *p){
123346  sqlite3_free(p);
123347}
123348
123349/* Turn bulk memory into a hash table object by initializing the
123350** fields of the Hash structure.
123351**
123352** "pNew" is a pointer to the hash table that is to be initialized.
123353** keyClass is one of the constants
123354** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass
123355** determines what kind of key the hash table will use.  "copyKey" is
123356** true if the hash table should make its own private copy of keys and
123357** false if it should just use the supplied pointer.
123358*/
123359SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
123360  assert( pNew!=0 );
123361  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
123362  pNew->keyClass = keyClass;
123363  pNew->copyKey = copyKey;
123364  pNew->first = 0;
123365  pNew->count = 0;
123366  pNew->htsize = 0;
123367  pNew->ht = 0;
123368}
123369
123370/* Remove all entries from a hash table.  Reclaim all memory.
123371** Call this routine to delete a hash table or to reset a hash table
123372** to the empty state.
123373*/
123374SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
123375  Fts3HashElem *elem;         /* For looping over all elements of the table */
123376
123377  assert( pH!=0 );
123378  elem = pH->first;
123379  pH->first = 0;
123380  fts3HashFree(pH->ht);
123381  pH->ht = 0;
123382  pH->htsize = 0;
123383  while( elem ){
123384    Fts3HashElem *next_elem = elem->next;
123385    if( pH->copyKey && elem->pKey ){
123386      fts3HashFree(elem->pKey);
123387    }
123388    fts3HashFree(elem);
123389    elem = next_elem;
123390  }
123391  pH->count = 0;
123392}
123393
123394/*
123395** Hash and comparison functions when the mode is FTS3_HASH_STRING
123396*/
123397static int fts3StrHash(const void *pKey, int nKey){
123398  const char *z = (const char *)pKey;
123399  int h = 0;
123400  if( nKey<=0 ) nKey = (int) strlen(z);
123401  while( nKey > 0  ){
123402    h = (h<<3) ^ h ^ *z++;
123403    nKey--;
123404  }
123405  return h & 0x7fffffff;
123406}
123407static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
123408  if( n1!=n2 ) return 1;
123409  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
123410}
123411
123412/*
123413** Hash and comparison functions when the mode is FTS3_HASH_BINARY
123414*/
123415static int fts3BinHash(const void *pKey, int nKey){
123416  int h = 0;
123417  const char *z = (const char *)pKey;
123418  while( nKey-- > 0 ){
123419    h = (h<<3) ^ h ^ *(z++);
123420  }
123421  return h & 0x7fffffff;
123422}
123423static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
123424  if( n1!=n2 ) return 1;
123425  return memcmp(pKey1,pKey2,n1);
123426}
123427
123428/*
123429** Return a pointer to the appropriate hash function given the key class.
123430**
123431** The C syntax in this function definition may be unfamilar to some
123432** programmers, so we provide the following additional explanation:
123433**
123434** The name of the function is "ftsHashFunction".  The function takes a
123435** single parameter "keyClass".  The return value of ftsHashFunction()
123436** is a pointer to another function.  Specifically, the return value
123437** of ftsHashFunction() is a pointer to a function that takes two parameters
123438** with types "const void*" and "int" and returns an "int".
123439*/
123440static int (*ftsHashFunction(int keyClass))(const void*,int){
123441  if( keyClass==FTS3_HASH_STRING ){
123442    return &fts3StrHash;
123443  }else{
123444    assert( keyClass==FTS3_HASH_BINARY );
123445    return &fts3BinHash;
123446  }
123447}
123448
123449/*
123450** Return a pointer to the appropriate hash function given the key class.
123451**
123452** For help in interpreted the obscure C code in the function definition,
123453** see the header comment on the previous function.
123454*/
123455static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
123456  if( keyClass==FTS3_HASH_STRING ){
123457    return &fts3StrCompare;
123458  }else{
123459    assert( keyClass==FTS3_HASH_BINARY );
123460    return &fts3BinCompare;
123461  }
123462}
123463
123464/* Link an element into the hash table
123465*/
123466static void fts3HashInsertElement(
123467  Fts3Hash *pH,            /* The complete hash table */
123468  struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
123469  Fts3HashElem *pNew       /* The element to be inserted */
123470){
123471  Fts3HashElem *pHead;     /* First element already in pEntry */
123472  pHead = pEntry->chain;
123473  if( pHead ){
123474    pNew->next = pHead;
123475    pNew->prev = pHead->prev;
123476    if( pHead->prev ){ pHead->prev->next = pNew; }
123477    else             { pH->first = pNew; }
123478    pHead->prev = pNew;
123479  }else{
123480    pNew->next = pH->first;
123481    if( pH->first ){ pH->first->prev = pNew; }
123482    pNew->prev = 0;
123483    pH->first = pNew;
123484  }
123485  pEntry->count++;
123486  pEntry->chain = pNew;
123487}
123488
123489
123490/* Resize the hash table so that it cantains "new_size" buckets.
123491** "new_size" must be a power of 2.  The hash table might fail
123492** to resize if sqliteMalloc() fails.
123493**
123494** Return non-zero if a memory allocation error occurs.
123495*/
123496static int fts3Rehash(Fts3Hash *pH, int new_size){
123497  struct _fts3ht *new_ht;          /* The new hash table */
123498  Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
123499  int (*xHash)(const void*,int);   /* The hash function */
123500
123501  assert( (new_size & (new_size-1))==0 );
123502  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
123503  if( new_ht==0 ) return 1;
123504  fts3HashFree(pH->ht);
123505  pH->ht = new_ht;
123506  pH->htsize = new_size;
123507  xHash = ftsHashFunction(pH->keyClass);
123508  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
123509    int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
123510    next_elem = elem->next;
123511    fts3HashInsertElement(pH, &new_ht[h], elem);
123512  }
123513  return 0;
123514}
123515
123516/* This function (for internal use only) locates an element in an
123517** hash table that matches the given key.  The hash for this key has
123518** already been computed and is passed as the 4th parameter.
123519*/
123520static Fts3HashElem *fts3FindElementByHash(
123521  const Fts3Hash *pH, /* The pH to be searched */
123522  const void *pKey,   /* The key we are searching for */
123523  int nKey,
123524  int h               /* The hash for this key. */
123525){
123526  Fts3HashElem *elem;            /* Used to loop thru the element list */
123527  int count;                     /* Number of elements left to test */
123528  int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
123529
123530  if( pH->ht ){
123531    struct _fts3ht *pEntry = &pH->ht[h];
123532    elem = pEntry->chain;
123533    count = pEntry->count;
123534    xCompare = ftsCompareFunction(pH->keyClass);
123535    while( count-- && elem ){
123536      if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
123537        return elem;
123538      }
123539      elem = elem->next;
123540    }
123541  }
123542  return 0;
123543}
123544
123545/* Remove a single entry from the hash table given a pointer to that
123546** element and a hash on the element's key.
123547*/
123548static void fts3RemoveElementByHash(
123549  Fts3Hash *pH,         /* The pH containing "elem" */
123550  Fts3HashElem* elem,   /* The element to be removed from the pH */
123551  int h                 /* Hash value for the element */
123552){
123553  struct _fts3ht *pEntry;
123554  if( elem->prev ){
123555    elem->prev->next = elem->next;
123556  }else{
123557    pH->first = elem->next;
123558  }
123559  if( elem->next ){
123560    elem->next->prev = elem->prev;
123561  }
123562  pEntry = &pH->ht[h];
123563  if( pEntry->chain==elem ){
123564    pEntry->chain = elem->next;
123565  }
123566  pEntry->count--;
123567  if( pEntry->count<=0 ){
123568    pEntry->chain = 0;
123569  }
123570  if( pH->copyKey && elem->pKey ){
123571    fts3HashFree(elem->pKey);
123572  }
123573  fts3HashFree( elem );
123574  pH->count--;
123575  if( pH->count<=0 ){
123576    assert( pH->first==0 );
123577    assert( pH->count==0 );
123578    fts3HashClear(pH);
123579  }
123580}
123581
123582SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
123583  const Fts3Hash *pH,
123584  const void *pKey,
123585  int nKey
123586){
123587  int h;                          /* A hash on key */
123588  int (*xHash)(const void*,int);  /* The hash function */
123589
123590  if( pH==0 || pH->ht==0 ) return 0;
123591  xHash = ftsHashFunction(pH->keyClass);
123592  assert( xHash!=0 );
123593  h = (*xHash)(pKey,nKey);
123594  assert( (pH->htsize & (pH->htsize-1))==0 );
123595  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
123596}
123597
123598/*
123599** Attempt to locate an element of the hash table pH with a key
123600** that matches pKey,nKey.  Return the data for this element if it is
123601** found, or NULL if there is no match.
123602*/
123603SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
123604  Fts3HashElem *pElem;            /* The element that matches key (if any) */
123605
123606  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
123607  return pElem ? pElem->data : 0;
123608}
123609
123610/* Insert an element into the hash table pH.  The key is pKey,nKey
123611** and the data is "data".
123612**
123613** If no element exists with a matching key, then a new
123614** element is created.  A copy of the key is made if the copyKey
123615** flag is set.  NULL is returned.
123616**
123617** If another element already exists with the same key, then the
123618** new data replaces the old data and the old data is returned.
123619** The key is not copied in this instance.  If a malloc fails, then
123620** the new data is returned and the hash table is unchanged.
123621**
123622** If the "data" parameter to this function is NULL, then the
123623** element corresponding to "key" is removed from the hash table.
123624*/
123625SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
123626  Fts3Hash *pH,        /* The hash table to insert into */
123627  const void *pKey,    /* The key */
123628  int nKey,            /* Number of bytes in the key */
123629  void *data           /* The data */
123630){
123631  int hraw;                 /* Raw hash value of the key */
123632  int h;                    /* the hash of the key modulo hash table size */
123633  Fts3HashElem *elem;       /* Used to loop thru the element list */
123634  Fts3HashElem *new_elem;   /* New element added to the pH */
123635  int (*xHash)(const void*,int);  /* The hash function */
123636
123637  assert( pH!=0 );
123638  xHash = ftsHashFunction(pH->keyClass);
123639  assert( xHash!=0 );
123640  hraw = (*xHash)(pKey, nKey);
123641  assert( (pH->htsize & (pH->htsize-1))==0 );
123642  h = hraw & (pH->htsize-1);
123643  elem = fts3FindElementByHash(pH,pKey,nKey,h);
123644  if( elem ){
123645    void *old_data = elem->data;
123646    if( data==0 ){
123647      fts3RemoveElementByHash(pH,elem,h);
123648    }else{
123649      elem->data = data;
123650    }
123651    return old_data;
123652  }
123653  if( data==0 ) return 0;
123654  if( (pH->htsize==0 && fts3Rehash(pH,8))
123655   || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
123656  ){
123657    pH->count = 0;
123658    return data;
123659  }
123660  assert( pH->htsize>0 );
123661  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
123662  if( new_elem==0 ) return data;
123663  if( pH->copyKey && pKey!=0 ){
123664    new_elem->pKey = fts3HashMalloc( nKey );
123665    if( new_elem->pKey==0 ){
123666      fts3HashFree(new_elem);
123667      return data;
123668    }
123669    memcpy((void*)new_elem->pKey, pKey, nKey);
123670  }else{
123671    new_elem->pKey = (void*)pKey;
123672  }
123673  new_elem->nKey = nKey;
123674  pH->count++;
123675  assert( pH->htsize>0 );
123676  assert( (pH->htsize & (pH->htsize-1))==0 );
123677  h = hraw & (pH->htsize-1);
123678  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
123679  new_elem->data = data;
123680  return 0;
123681}
123682
123683#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
123684
123685/************** End of fts3_hash.c *******************************************/
123686/************** Begin file fts3_porter.c *************************************/
123687/*
123688** 2006 September 30
123689**
123690** The author disclaims copyright to this source code.  In place of
123691** a legal notice, here is a blessing:
123692**
123693**    May you do good and not evil.
123694**    May you find forgiveness for yourself and forgive others.
123695**    May you share freely, never taking more than you give.
123696**
123697*************************************************************************
123698** Implementation of the full-text-search tokenizer that implements
123699** a Porter stemmer.
123700*/
123701
123702/*
123703** The code in this file is only compiled if:
123704**
123705**     * The FTS3 module is being built as an extension
123706**       (in which case SQLITE_CORE is not defined), or
123707**
123708**     * The FTS3 module is being built into the core of
123709**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
123710*/
123711#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
123712
123713/* #include <assert.h> */
123714/* #include <stdlib.h> */
123715/* #include <stdio.h> */
123716/* #include <string.h> */
123717
123718
123719/*
123720** Class derived from sqlite3_tokenizer
123721*/
123722typedef struct porter_tokenizer {
123723  sqlite3_tokenizer base;      /* Base class */
123724} porter_tokenizer;
123725
123726/*
123727** Class derived from sqlite3_tokenizer_cursor
123728*/
123729typedef struct porter_tokenizer_cursor {
123730  sqlite3_tokenizer_cursor base;
123731  const char *zInput;          /* input we are tokenizing */
123732  int nInput;                  /* size of the input */
123733  int iOffset;                 /* current position in zInput */
123734  int iToken;                  /* index of next token to be returned */
123735  char *zToken;                /* storage for current token */
123736  int nAllocated;              /* space allocated to zToken buffer */
123737} porter_tokenizer_cursor;
123738
123739
123740/*
123741** Create a new tokenizer instance.
123742*/
123743static int porterCreate(
123744  int argc, const char * const *argv,
123745  sqlite3_tokenizer **ppTokenizer
123746){
123747  porter_tokenizer *t;
123748
123749  UNUSED_PARAMETER(argc);
123750  UNUSED_PARAMETER(argv);
123751
123752  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
123753  if( t==NULL ) return SQLITE_NOMEM;
123754  memset(t, 0, sizeof(*t));
123755  *ppTokenizer = &t->base;
123756  return SQLITE_OK;
123757}
123758
123759/*
123760** Destroy a tokenizer
123761*/
123762static int porterDestroy(sqlite3_tokenizer *pTokenizer){
123763  sqlite3_free(pTokenizer);
123764  return SQLITE_OK;
123765}
123766
123767/*
123768** Prepare to begin tokenizing a particular string.  The input
123769** string to be tokenized is zInput[0..nInput-1].  A cursor
123770** used to incrementally tokenize this string is returned in
123771** *ppCursor.
123772*/
123773static int porterOpen(
123774  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
123775  const char *zInput, int nInput,        /* String to be tokenized */
123776  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
123777){
123778  porter_tokenizer_cursor *c;
123779
123780  UNUSED_PARAMETER(pTokenizer);
123781
123782  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
123783  if( c==NULL ) return SQLITE_NOMEM;
123784
123785  c->zInput = zInput;
123786  if( zInput==0 ){
123787    c->nInput = 0;
123788  }else if( nInput<0 ){
123789    c->nInput = (int)strlen(zInput);
123790  }else{
123791    c->nInput = nInput;
123792  }
123793  c->iOffset = 0;                 /* start tokenizing at the beginning */
123794  c->iToken = 0;
123795  c->zToken = NULL;               /* no space allocated, yet. */
123796  c->nAllocated = 0;
123797
123798  *ppCursor = &c->base;
123799  return SQLITE_OK;
123800}
123801
123802/*
123803** Close a tokenization cursor previously opened by a call to
123804** porterOpen() above.
123805*/
123806static int porterClose(sqlite3_tokenizer_cursor *pCursor){
123807  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
123808  sqlite3_free(c->zToken);
123809  sqlite3_free(c);
123810  return SQLITE_OK;
123811}
123812/*
123813** Vowel or consonant
123814*/
123815static const char cType[] = {
123816   0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
123817   1, 1, 1, 2, 1
123818};
123819
123820/*
123821** isConsonant() and isVowel() determine if their first character in
123822** the string they point to is a consonant or a vowel, according
123823** to Porter ruls.
123824**
123825** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
123826** 'Y' is a consonant unless it follows another consonant,
123827** in which case it is a vowel.
123828**
123829** In these routine, the letters are in reverse order.  So the 'y' rule
123830** is that 'y' is a consonant unless it is followed by another
123831** consonent.
123832*/
123833static int isVowel(const char*);
123834static int isConsonant(const char *z){
123835  int j;
123836  char x = *z;
123837  if( x==0 ) return 0;
123838  assert( x>='a' && x<='z' );
123839  j = cType[x-'a'];
123840  if( j<2 ) return j;
123841  return z[1]==0 || isVowel(z + 1);
123842}
123843static int isVowel(const char *z){
123844  int j;
123845  char x = *z;
123846  if( x==0 ) return 0;
123847  assert( x>='a' && x<='z' );
123848  j = cType[x-'a'];
123849  if( j<2 ) return 1-j;
123850  return isConsonant(z + 1);
123851}
123852
123853/*
123854** Let any sequence of one or more vowels be represented by V and let
123855** C be sequence of one or more consonants.  Then every word can be
123856** represented as:
123857**
123858**           [C] (VC){m} [V]
123859**
123860** In prose:  A word is an optional consonant followed by zero or
123861** vowel-consonant pairs followed by an optional vowel.  "m" is the
123862** number of vowel consonant pairs.  This routine computes the value
123863** of m for the first i bytes of a word.
123864**
123865** Return true if the m-value for z is 1 or more.  In other words,
123866** return true if z contains at least one vowel that is followed
123867** by a consonant.
123868**
123869** In this routine z[] is in reverse order.  So we are really looking
123870** for an instance of of a consonant followed by a vowel.
123871*/
123872static int m_gt_0(const char *z){
123873  while( isVowel(z) ){ z++; }
123874  if( *z==0 ) return 0;
123875  while( isConsonant(z) ){ z++; }
123876  return *z!=0;
123877}
123878
123879/* Like mgt0 above except we are looking for a value of m which is
123880** exactly 1
123881*/
123882static int m_eq_1(const char *z){
123883  while( isVowel(z) ){ z++; }
123884  if( *z==0 ) return 0;
123885  while( isConsonant(z) ){ z++; }
123886  if( *z==0 ) return 0;
123887  while( isVowel(z) ){ z++; }
123888  if( *z==0 ) return 1;
123889  while( isConsonant(z) ){ z++; }
123890  return *z==0;
123891}
123892
123893/* Like mgt0 above except we are looking for a value of m>1 instead
123894** or m>0
123895*/
123896static int m_gt_1(const char *z){
123897  while( isVowel(z) ){ z++; }
123898  if( *z==0 ) return 0;
123899  while( isConsonant(z) ){ z++; }
123900  if( *z==0 ) return 0;
123901  while( isVowel(z) ){ z++; }
123902  if( *z==0 ) return 0;
123903  while( isConsonant(z) ){ z++; }
123904  return *z!=0;
123905}
123906
123907/*
123908** Return TRUE if there is a vowel anywhere within z[0..n-1]
123909*/
123910static int hasVowel(const char *z){
123911  while( isConsonant(z) ){ z++; }
123912  return *z!=0;
123913}
123914
123915/*
123916** Return TRUE if the word ends in a double consonant.
123917**
123918** The text is reversed here. So we are really looking at
123919** the first two characters of z[].
123920*/
123921static int doubleConsonant(const char *z){
123922  return isConsonant(z) && z[0]==z[1];
123923}
123924
123925/*
123926** Return TRUE if the word ends with three letters which
123927** are consonant-vowel-consonent and where the final consonant
123928** is not 'w', 'x', or 'y'.
123929**
123930** The word is reversed here.  So we are really checking the
123931** first three letters and the first one cannot be in [wxy].
123932*/
123933static int star_oh(const char *z){
123934  return
123935    isConsonant(z) &&
123936    z[0]!='w' && z[0]!='x' && z[0]!='y' &&
123937    isVowel(z+1) &&
123938    isConsonant(z+2);
123939}
123940
123941/*
123942** If the word ends with zFrom and xCond() is true for the stem
123943** of the word that preceeds the zFrom ending, then change the
123944** ending to zTo.
123945**
123946** The input word *pz and zFrom are both in reverse order.  zTo
123947** is in normal order.
123948**
123949** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
123950** match.  Not that TRUE is returned even if xCond() fails and
123951** no substitution occurs.
123952*/
123953static int stem(
123954  char **pz,             /* The word being stemmed (Reversed) */
123955  const char *zFrom,     /* If the ending matches this... (Reversed) */
123956  const char *zTo,       /* ... change the ending to this (not reversed) */
123957  int (*xCond)(const char*)   /* Condition that must be true */
123958){
123959  char *z = *pz;
123960  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
123961  if( *zFrom!=0 ) return 0;
123962  if( xCond && !xCond(z) ) return 1;
123963  while( *zTo ){
123964    *(--z) = *(zTo++);
123965  }
123966  *pz = z;
123967  return 1;
123968}
123969
123970/*
123971** This is the fallback stemmer used when the porter stemmer is
123972** inappropriate.  The input word is copied into the output with
123973** US-ASCII case folding.  If the input word is too long (more
123974** than 20 bytes if it contains no digits or more than 6 bytes if
123975** it contains digits) then word is truncated to 20 or 6 bytes
123976** by taking 10 or 3 bytes from the beginning and end.
123977*/
123978static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
123979  int i, mx, j;
123980  int hasDigit = 0;
123981  for(i=0; i<nIn; i++){
123982    char c = zIn[i];
123983    if( c>='A' && c<='Z' ){
123984      zOut[i] = c - 'A' + 'a';
123985    }else{
123986      if( c>='0' && c<='9' ) hasDigit = 1;
123987      zOut[i] = c;
123988    }
123989  }
123990  mx = hasDigit ? 3 : 10;
123991  if( nIn>mx*2 ){
123992    for(j=mx, i=nIn-mx; i<nIn; i++, j++){
123993      zOut[j] = zOut[i];
123994    }
123995    i = j;
123996  }
123997  zOut[i] = 0;
123998  *pnOut = i;
123999}
124000
124001
124002/*
124003** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
124004** zOut is at least big enough to hold nIn bytes.  Write the actual
124005** size of the output word (exclusive of the '\0' terminator) into *pnOut.
124006**
124007** Any upper-case characters in the US-ASCII character set ([A-Z])
124008** are converted to lower case.  Upper-case UTF characters are
124009** unchanged.
124010**
124011** Words that are longer than about 20 bytes are stemmed by retaining
124012** a few bytes from the beginning and the end of the word.  If the
124013** word contains digits, 3 bytes are taken from the beginning and
124014** 3 bytes from the end.  For long words without digits, 10 bytes
124015** are taken from each end.  US-ASCII case folding still applies.
124016**
124017** If the input word contains not digits but does characters not
124018** in [a-zA-Z] then no stemming is attempted and this routine just
124019** copies the input into the input into the output with US-ASCII
124020** case folding.
124021**
124022** Stemming never increases the length of the word.  So there is
124023** no chance of overflowing the zOut buffer.
124024*/
124025static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
124026  int i, j;
124027  char zReverse[28];
124028  char *z, *z2;
124029  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
124030    /* The word is too big or too small for the porter stemmer.
124031    ** Fallback to the copy stemmer */
124032    copy_stemmer(zIn, nIn, zOut, pnOut);
124033    return;
124034  }
124035  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
124036    char c = zIn[i];
124037    if( c>='A' && c<='Z' ){
124038      zReverse[j] = c + 'a' - 'A';
124039    }else if( c>='a' && c<='z' ){
124040      zReverse[j] = c;
124041    }else{
124042      /* The use of a character not in [a-zA-Z] means that we fallback
124043      ** to the copy stemmer */
124044      copy_stemmer(zIn, nIn, zOut, pnOut);
124045      return;
124046    }
124047  }
124048  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
124049  z = &zReverse[j+1];
124050
124051
124052  /* Step 1a */
124053  if( z[0]=='s' ){
124054    if(
124055     !stem(&z, "sess", "ss", 0) &&
124056     !stem(&z, "sei", "i", 0)  &&
124057     !stem(&z, "ss", "ss", 0)
124058    ){
124059      z++;
124060    }
124061  }
124062
124063  /* Step 1b */
124064  z2 = z;
124065  if( stem(&z, "dee", "ee", m_gt_0) ){
124066    /* Do nothing.  The work was all in the test */
124067  }else if(
124068     (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
124069      && z!=z2
124070  ){
124071     if( stem(&z, "ta", "ate", 0) ||
124072         stem(&z, "lb", "ble", 0) ||
124073         stem(&z, "zi", "ize", 0) ){
124074       /* Do nothing.  The work was all in the test */
124075     }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
124076       z++;
124077     }else if( m_eq_1(z) && star_oh(z) ){
124078       *(--z) = 'e';
124079     }
124080  }
124081
124082  /* Step 1c */
124083  if( z[0]=='y' && hasVowel(z+1) ){
124084    z[0] = 'i';
124085  }
124086
124087  /* Step 2 */
124088  switch( z[1] ){
124089   case 'a':
124090     stem(&z, "lanoita", "ate", m_gt_0) ||
124091     stem(&z, "lanoit", "tion", m_gt_0);
124092     break;
124093   case 'c':
124094     stem(&z, "icne", "ence", m_gt_0) ||
124095     stem(&z, "icna", "ance", m_gt_0);
124096     break;
124097   case 'e':
124098     stem(&z, "rezi", "ize", m_gt_0);
124099     break;
124100   case 'g':
124101     stem(&z, "igol", "log", m_gt_0);
124102     break;
124103   case 'l':
124104     stem(&z, "ilb", "ble", m_gt_0) ||
124105     stem(&z, "illa", "al", m_gt_0) ||
124106     stem(&z, "iltne", "ent", m_gt_0) ||
124107     stem(&z, "ile", "e", m_gt_0) ||
124108     stem(&z, "ilsuo", "ous", m_gt_0);
124109     break;
124110   case 'o':
124111     stem(&z, "noitazi", "ize", m_gt_0) ||
124112     stem(&z, "noita", "ate", m_gt_0) ||
124113     stem(&z, "rota", "ate", m_gt_0);
124114     break;
124115   case 's':
124116     stem(&z, "msila", "al", m_gt_0) ||
124117     stem(&z, "ssenevi", "ive", m_gt_0) ||
124118     stem(&z, "ssenluf", "ful", m_gt_0) ||
124119     stem(&z, "ssensuo", "ous", m_gt_0);
124120     break;
124121   case 't':
124122     stem(&z, "itila", "al", m_gt_0) ||
124123     stem(&z, "itivi", "ive", m_gt_0) ||
124124     stem(&z, "itilib", "ble", m_gt_0);
124125     break;
124126  }
124127
124128  /* Step 3 */
124129  switch( z[0] ){
124130   case 'e':
124131     stem(&z, "etaci", "ic", m_gt_0) ||
124132     stem(&z, "evita", "", m_gt_0)   ||
124133     stem(&z, "ezila", "al", m_gt_0);
124134     break;
124135   case 'i':
124136     stem(&z, "itici", "ic", m_gt_0);
124137     break;
124138   case 'l':
124139     stem(&z, "laci", "ic", m_gt_0) ||
124140     stem(&z, "luf", "", m_gt_0);
124141     break;
124142   case 's':
124143     stem(&z, "ssen", "", m_gt_0);
124144     break;
124145  }
124146
124147  /* Step 4 */
124148  switch( z[1] ){
124149   case 'a':
124150     if( z[0]=='l' && m_gt_1(z+2) ){
124151       z += 2;
124152     }
124153     break;
124154   case 'c':
124155     if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
124156       z += 4;
124157     }
124158     break;
124159   case 'e':
124160     if( z[0]=='r' && m_gt_1(z+2) ){
124161       z += 2;
124162     }
124163     break;
124164   case 'i':
124165     if( z[0]=='c' && m_gt_1(z+2) ){
124166       z += 2;
124167     }
124168     break;
124169   case 'l':
124170     if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
124171       z += 4;
124172     }
124173     break;
124174   case 'n':
124175     if( z[0]=='t' ){
124176       if( z[2]=='a' ){
124177         if( m_gt_1(z+3) ){
124178           z += 3;
124179         }
124180       }else if( z[2]=='e' ){
124181         stem(&z, "tneme", "", m_gt_1) ||
124182         stem(&z, "tnem", "", m_gt_1) ||
124183         stem(&z, "tne", "", m_gt_1);
124184       }
124185     }
124186     break;
124187   case 'o':
124188     if( z[0]=='u' ){
124189       if( m_gt_1(z+2) ){
124190         z += 2;
124191       }
124192     }else if( z[3]=='s' || z[3]=='t' ){
124193       stem(&z, "noi", "", m_gt_1);
124194     }
124195     break;
124196   case 's':
124197     if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
124198       z += 3;
124199     }
124200     break;
124201   case 't':
124202     stem(&z, "eta", "", m_gt_1) ||
124203     stem(&z, "iti", "", m_gt_1);
124204     break;
124205   case 'u':
124206     if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
124207       z += 3;
124208     }
124209     break;
124210   case 'v':
124211   case 'z':
124212     if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
124213       z += 3;
124214     }
124215     break;
124216  }
124217
124218  /* Step 5a */
124219  if( z[0]=='e' ){
124220    if( m_gt_1(z+1) ){
124221      z++;
124222    }else if( m_eq_1(z+1) && !star_oh(z+1) ){
124223      z++;
124224    }
124225  }
124226
124227  /* Step 5b */
124228  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
124229    z++;
124230  }
124231
124232  /* z[] is now the stemmed word in reverse order.  Flip it back
124233  ** around into forward order and return.
124234  */
124235  *pnOut = i = (int)strlen(z);
124236  zOut[i] = 0;
124237  while( *z ){
124238    zOut[--i] = *(z++);
124239  }
124240}
124241
124242/*
124243** Characters that can be part of a token.  We assume any character
124244** whose value is greater than 0x80 (any UTF character) can be
124245** part of a token.  In other words, delimiters all must have
124246** values of 0x7f or lower.
124247*/
124248static const char porterIdChar[] = {
124249/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
124250    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
124251    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
124252    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
124253    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
124254    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
124255};
124256#define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
124257
124258/*
124259** Extract the next token from a tokenization cursor.  The cursor must
124260** have been opened by a prior call to porterOpen().
124261*/
124262static int porterNext(
124263  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
124264  const char **pzToken,               /* OUT: *pzToken is the token text */
124265  int *pnBytes,                       /* OUT: Number of bytes in token */
124266  int *piStartOffset,                 /* OUT: Starting offset of token */
124267  int *piEndOffset,                   /* OUT: Ending offset of token */
124268  int *piPosition                     /* OUT: Position integer of token */
124269){
124270  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
124271  const char *z = c->zInput;
124272
124273  while( c->iOffset<c->nInput ){
124274    int iStartOffset, ch;
124275
124276    /* Scan past delimiter characters */
124277    while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
124278      c->iOffset++;
124279    }
124280
124281    /* Count non-delimiter characters. */
124282    iStartOffset = c->iOffset;
124283    while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
124284      c->iOffset++;
124285    }
124286
124287    if( c->iOffset>iStartOffset ){
124288      int n = c->iOffset-iStartOffset;
124289      if( n>c->nAllocated ){
124290        char *pNew;
124291        c->nAllocated = n+20;
124292        pNew = sqlite3_realloc(c->zToken, c->nAllocated);
124293        if( !pNew ) return SQLITE_NOMEM;
124294        c->zToken = pNew;
124295      }
124296      porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
124297      *pzToken = c->zToken;
124298      *piStartOffset = iStartOffset;
124299      *piEndOffset = c->iOffset;
124300      *piPosition = c->iToken++;
124301      return SQLITE_OK;
124302    }
124303  }
124304  return SQLITE_DONE;
124305}
124306
124307/*
124308** The set of routines that implement the porter-stemmer tokenizer
124309*/
124310static const sqlite3_tokenizer_module porterTokenizerModule = {
124311  0,
124312  porterCreate,
124313  porterDestroy,
124314  porterOpen,
124315  porterClose,
124316  porterNext,
124317  0
124318};
124319
124320/*
124321** Allocate a new porter tokenizer.  Return a pointer to the new
124322** tokenizer in *ppModule
124323*/
124324SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
124325  sqlite3_tokenizer_module const**ppModule
124326){
124327  *ppModule = &porterTokenizerModule;
124328}
124329
124330#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124331
124332/************** End of fts3_porter.c *****************************************/
124333/************** Begin file fts3_tokenizer.c **********************************/
124334/*
124335** 2007 June 22
124336**
124337** The author disclaims copyright to this source code.  In place of
124338** a legal notice, here is a blessing:
124339**
124340**    May you do good and not evil.
124341**    May you find forgiveness for yourself and forgive others.
124342**    May you share freely, never taking more than you give.
124343**
124344******************************************************************************
124345**
124346** This is part of an SQLite module implementing full-text search.
124347** This particular file implements the generic tokenizer interface.
124348*/
124349
124350/*
124351** The code in this file is only compiled if:
124352**
124353**     * The FTS3 module is being built as an extension
124354**       (in which case SQLITE_CORE is not defined), or
124355**
124356**     * The FTS3 module is being built into the core of
124357**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124358*/
124359#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124360
124361/* #include <assert.h> */
124362/* #include <string.h> */
124363
124364/*
124365** Implementation of the SQL scalar function for accessing the underlying
124366** hash table. This function may be called as follows:
124367**
124368**   SELECT <function-name>(<key-name>);
124369**   SELECT <function-name>(<key-name>, <pointer>);
124370**
124371** where <function-name> is the name passed as the second argument
124372** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
124373**
124374** If the <pointer> argument is specified, it must be a blob value
124375** containing a pointer to be stored as the hash data corresponding
124376** to the string <key-name>. If <pointer> is not specified, then
124377** the string <key-name> must already exist in the has table. Otherwise,
124378** an error is returned.
124379**
124380** Whether or not the <pointer> argument is specified, the value returned
124381** is a blob containing the pointer stored as the hash data corresponding
124382** to string <key-name> (after the hash-table is updated, if applicable).
124383*/
124384static void scalarFunc(
124385  sqlite3_context *context,
124386  int argc,
124387  sqlite3_value **argv
124388){
124389  Fts3Hash *pHash;
124390  void *pPtr = 0;
124391  const unsigned char *zName;
124392  int nName;
124393
124394  assert( argc==1 || argc==2 );
124395
124396  pHash = (Fts3Hash *)sqlite3_user_data(context);
124397
124398  zName = sqlite3_value_text(argv[0]);
124399  nName = sqlite3_value_bytes(argv[0])+1;
124400
124401  if( argc==2 ){
124402    void *pOld;
124403    int n = sqlite3_value_bytes(argv[1]);
124404    if( n!=sizeof(pPtr) ){
124405      sqlite3_result_error(context, "argument type mismatch", -1);
124406      return;
124407    }
124408    pPtr = *(void **)sqlite3_value_blob(argv[1]);
124409    pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
124410    if( pOld==pPtr ){
124411      sqlite3_result_error(context, "out of memory", -1);
124412      return;
124413    }
124414  }else{
124415    pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
124416    if( !pPtr ){
124417      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
124418      sqlite3_result_error(context, zErr, -1);
124419      sqlite3_free(zErr);
124420      return;
124421    }
124422  }
124423
124424  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
124425}
124426
124427SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
124428  static const char isFtsIdChar[] = {
124429      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
124430      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
124431      0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
124432      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
124433      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
124434      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
124435      0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
124436      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
124437  };
124438  return (c&0x80 || isFtsIdChar[(int)(c)]);
124439}
124440
124441SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
124442  const char *z1;
124443  const char *z2 = 0;
124444
124445  /* Find the start of the next token. */
124446  z1 = zStr;
124447  while( z2==0 ){
124448    char c = *z1;
124449    switch( c ){
124450      case '\0': return 0;        /* No more tokens here */
124451      case '\'':
124452      case '"':
124453      case '`': {
124454        z2 = z1;
124455        while( *++z2 && (*z2!=c || *++z2==c) );
124456        break;
124457      }
124458      case '[':
124459        z2 = &z1[1];
124460        while( *z2 && z2[0]!=']' ) z2++;
124461        if( *z2 ) z2++;
124462        break;
124463
124464      default:
124465        if( sqlite3Fts3IsIdChar(*z1) ){
124466          z2 = &z1[1];
124467          while( sqlite3Fts3IsIdChar(*z2) ) z2++;
124468        }else{
124469          z1++;
124470        }
124471    }
124472  }
124473
124474  *pn = (int)(z2-z1);
124475  return z1;
124476}
124477
124478SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
124479  Fts3Hash *pHash,                /* Tokenizer hash table */
124480  const char *zArg,               /* Tokenizer name */
124481  sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
124482  char **pzErr                    /* OUT: Set to malloced error message */
124483){
124484  int rc;
124485  char *z = (char *)zArg;
124486  int n = 0;
124487  char *zCopy;
124488  char *zEnd;                     /* Pointer to nul-term of zCopy */
124489  sqlite3_tokenizer_module *m;
124490
124491  zCopy = sqlite3_mprintf("%s", zArg);
124492  if( !zCopy ) return SQLITE_NOMEM;
124493  zEnd = &zCopy[strlen(zCopy)];
124494
124495  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
124496  z[n] = '\0';
124497  sqlite3Fts3Dequote(z);
124498
124499  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
124500  if( !m ){
124501    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
124502    rc = SQLITE_ERROR;
124503  }else{
124504    char const **aArg = 0;
124505    int iArg = 0;
124506    z = &z[n+1];
124507    while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
124508      int nNew = sizeof(char *)*(iArg+1);
124509      char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
124510      if( !aNew ){
124511        sqlite3_free(zCopy);
124512        sqlite3_free((void *)aArg);
124513        return SQLITE_NOMEM;
124514      }
124515      aArg = aNew;
124516      aArg[iArg++] = z;
124517      z[n] = '\0';
124518      sqlite3Fts3Dequote(z);
124519      z = &z[n+1];
124520    }
124521    rc = m->xCreate(iArg, aArg, ppTok);
124522    assert( rc!=SQLITE_OK || *ppTok );
124523    if( rc!=SQLITE_OK ){
124524      *pzErr = sqlite3_mprintf("unknown tokenizer");
124525    }else{
124526      (*ppTok)->pModule = m;
124527    }
124528    sqlite3_free((void *)aArg);
124529  }
124530
124531  sqlite3_free(zCopy);
124532  return rc;
124533}
124534
124535
124536#ifdef SQLITE_TEST
124537
124538/* #include <tcl.h> */
124539/* #include <string.h> */
124540
124541/*
124542** Implementation of a special SQL scalar function for testing tokenizers
124543** designed to be used in concert with the Tcl testing framework. This
124544** function must be called with two arguments:
124545**
124546**   SELECT <function-name>(<key-name>, <input-string>);
124547**   SELECT <function-name>(<key-name>, <pointer>);
124548**
124549** where <function-name> is the name passed as the second argument
124550** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
124551** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
124552**
124553** The return value is a string that may be interpreted as a Tcl
124554** list. For each token in the <input-string>, three elements are
124555** added to the returned list. The first is the token position, the
124556** second is the token text (folded, stemmed, etc.) and the third is the
124557** substring of <input-string> associated with the token. For example,
124558** using the built-in "simple" tokenizer:
124559**
124560**   SELECT fts_tokenizer_test('simple', 'I don't see how');
124561**
124562** will return the string:
124563**
124564**   "{0 i I 1 dont don't 2 see see 3 how how}"
124565**
124566*/
124567static void testFunc(
124568  sqlite3_context *context,
124569  int argc,
124570  sqlite3_value **argv
124571){
124572  Fts3Hash *pHash;
124573  sqlite3_tokenizer_module *p;
124574  sqlite3_tokenizer *pTokenizer = 0;
124575  sqlite3_tokenizer_cursor *pCsr = 0;
124576
124577  const char *zErr = 0;
124578
124579  const char *zName;
124580  int nName;
124581  const char *zInput;
124582  int nInput;
124583
124584  const char *zArg = 0;
124585
124586  const char *zToken;
124587  int nToken;
124588  int iStart;
124589  int iEnd;
124590  int iPos;
124591
124592  Tcl_Obj *pRet;
124593
124594  assert( argc==2 || argc==3 );
124595
124596  nName = sqlite3_value_bytes(argv[0]);
124597  zName = (const char *)sqlite3_value_text(argv[0]);
124598  nInput = sqlite3_value_bytes(argv[argc-1]);
124599  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
124600
124601  if( argc==3 ){
124602    zArg = (const char *)sqlite3_value_text(argv[1]);
124603  }
124604
124605  pHash = (Fts3Hash *)sqlite3_user_data(context);
124606  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
124607
124608  if( !p ){
124609    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
124610    sqlite3_result_error(context, zErr, -1);
124611    sqlite3_free(zErr);
124612    return;
124613  }
124614
124615  pRet = Tcl_NewObj();
124616  Tcl_IncrRefCount(pRet);
124617
124618  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
124619    zErr = "error in xCreate()";
124620    goto finish;
124621  }
124622  pTokenizer->pModule = p;
124623  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
124624    zErr = "error in xOpen()";
124625    goto finish;
124626  }
124627
124628  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
124629    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
124630    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
124631    zToken = &zInput[iStart];
124632    nToken = iEnd-iStart;
124633    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
124634  }
124635
124636  if( SQLITE_OK!=p->xClose(pCsr) ){
124637    zErr = "error in xClose()";
124638    goto finish;
124639  }
124640  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
124641    zErr = "error in xDestroy()";
124642    goto finish;
124643  }
124644
124645finish:
124646  if( zErr ){
124647    sqlite3_result_error(context, zErr, -1);
124648  }else{
124649    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
124650  }
124651  Tcl_DecrRefCount(pRet);
124652}
124653
124654static
124655int registerTokenizer(
124656  sqlite3 *db,
124657  char *zName,
124658  const sqlite3_tokenizer_module *p
124659){
124660  int rc;
124661  sqlite3_stmt *pStmt;
124662  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
124663
124664  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124665  if( rc!=SQLITE_OK ){
124666    return rc;
124667  }
124668
124669  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
124670  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
124671  sqlite3_step(pStmt);
124672
124673  return sqlite3_finalize(pStmt);
124674}
124675
124676static
124677int queryTokenizer(
124678  sqlite3 *db,
124679  char *zName,
124680  const sqlite3_tokenizer_module **pp
124681){
124682  int rc;
124683  sqlite3_stmt *pStmt;
124684  const char zSql[] = "SELECT fts3_tokenizer(?)";
124685
124686  *pp = 0;
124687  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
124688  if( rc!=SQLITE_OK ){
124689    return rc;
124690  }
124691
124692  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
124693  if( SQLITE_ROW==sqlite3_step(pStmt) ){
124694    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
124695      memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
124696    }
124697  }
124698
124699  return sqlite3_finalize(pStmt);
124700}
124701
124702SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
124703
124704/*
124705** Implementation of the scalar function fts3_tokenizer_internal_test().
124706** This function is used for testing only, it is not included in the
124707** build unless SQLITE_TEST is defined.
124708**
124709** The purpose of this is to test that the fts3_tokenizer() function
124710** can be used as designed by the C-code in the queryTokenizer and
124711** registerTokenizer() functions above. These two functions are repeated
124712** in the README.tokenizer file as an example, so it is important to
124713** test them.
124714**
124715** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
124716** function with no arguments. An assert() will fail if a problem is
124717** detected. i.e.:
124718**
124719**     SELECT fts3_tokenizer_internal_test();
124720**
124721*/
124722static void intTestFunc(
124723  sqlite3_context *context,
124724  int argc,
124725  sqlite3_value **argv
124726){
124727  int rc;
124728  const sqlite3_tokenizer_module *p1;
124729  const sqlite3_tokenizer_module *p2;
124730  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
124731
124732  UNUSED_PARAMETER(argc);
124733  UNUSED_PARAMETER(argv);
124734
124735  /* Test the query function */
124736  sqlite3Fts3SimpleTokenizerModule(&p1);
124737  rc = queryTokenizer(db, "simple", &p2);
124738  assert( rc==SQLITE_OK );
124739  assert( p1==p2 );
124740  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124741  assert( rc==SQLITE_ERROR );
124742  assert( p2==0 );
124743  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
124744
124745  /* Test the storage function */
124746  rc = registerTokenizer(db, "nosuchtokenizer", p1);
124747  assert( rc==SQLITE_OK );
124748  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
124749  assert( rc==SQLITE_OK );
124750  assert( p2==p1 );
124751
124752  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
124753}
124754
124755#endif
124756
124757/*
124758** Set up SQL objects in database db used to access the contents of
124759** the hash table pointed to by argument pHash. The hash table must
124760** been initialised to use string keys, and to take a private copy
124761** of the key when a value is inserted. i.e. by a call similar to:
124762**
124763**    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
124764**
124765** This function adds a scalar function (see header comment above
124766** scalarFunc() in this file for details) and, if ENABLE_TABLE is
124767** defined at compilation time, a temporary virtual table (see header
124768** comment above struct HashTableVtab) to the database schema. Both
124769** provide read/write access to the contents of *pHash.
124770**
124771** The third argument to this function, zName, is used as the name
124772** of both the scalar and, if created, the virtual table.
124773*/
124774SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
124775  sqlite3 *db,
124776  Fts3Hash *pHash,
124777  const char *zName
124778){
124779  int rc = SQLITE_OK;
124780  void *p = (void *)pHash;
124781  const int any = SQLITE_ANY;
124782
124783#ifdef SQLITE_TEST
124784  char *zTest = 0;
124785  char *zTest2 = 0;
124786  void *pdb = (void *)db;
124787  zTest = sqlite3_mprintf("%s_test", zName);
124788  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
124789  if( !zTest || !zTest2 ){
124790    rc = SQLITE_NOMEM;
124791  }
124792#endif
124793
124794  if( SQLITE_OK==rc ){
124795    rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
124796  }
124797  if( SQLITE_OK==rc ){
124798    rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
124799  }
124800#ifdef SQLITE_TEST
124801  if( SQLITE_OK==rc ){
124802    rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0);
124803  }
124804  if( SQLITE_OK==rc ){
124805    rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0);
124806  }
124807  if( SQLITE_OK==rc ){
124808    rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
124809  }
124810#endif
124811
124812#ifdef SQLITE_TEST
124813  sqlite3_free(zTest);
124814  sqlite3_free(zTest2);
124815#endif
124816
124817  return rc;
124818}
124819
124820#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
124821
124822/************** End of fts3_tokenizer.c **************************************/
124823/************** Begin file fts3_tokenizer1.c *********************************/
124824/*
124825** 2006 Oct 10
124826**
124827** The author disclaims copyright to this source code.  In place of
124828** a legal notice, here is a blessing:
124829**
124830**    May you do good and not evil.
124831**    May you find forgiveness for yourself and forgive others.
124832**    May you share freely, never taking more than you give.
124833**
124834******************************************************************************
124835**
124836** Implementation of the "simple" full-text-search tokenizer.
124837*/
124838
124839/*
124840** The code in this file is only compiled if:
124841**
124842**     * The FTS3 module is being built as an extension
124843**       (in which case SQLITE_CORE is not defined), or
124844**
124845**     * The FTS3 module is being built into the core of
124846**       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
124847*/
124848#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124849
124850/* #include <assert.h> */
124851/* #include <stdlib.h> */
124852/* #include <stdio.h> */
124853/* #include <string.h> */
124854
124855
124856typedef struct simple_tokenizer {
124857  sqlite3_tokenizer base;
124858  char delim[128];             /* flag ASCII delimiters */
124859} simple_tokenizer;
124860
124861typedef struct simple_tokenizer_cursor {
124862  sqlite3_tokenizer_cursor base;
124863  const char *pInput;          /* input we are tokenizing */
124864  int nBytes;                  /* size of the input */
124865  int iOffset;                 /* current position in pInput */
124866  int iToken;                  /* index of next token to be returned */
124867  char *pToken;                /* storage for current token */
124868  int nTokenAllocated;         /* space allocated to zToken buffer */
124869} simple_tokenizer_cursor;
124870
124871
124872static int simpleDelim(simple_tokenizer *t, unsigned char c){
124873  return c<0x80 && t->delim[c];
124874}
124875static int fts3_isalnum(int x){
124876  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
124877}
124878
124879/*
124880** Create a new tokenizer instance.
124881*/
124882static int simpleCreate(
124883  int argc, const char * const *argv,
124884  sqlite3_tokenizer **ppTokenizer
124885){
124886  simple_tokenizer *t;
124887
124888  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
124889  if( t==NULL ) return SQLITE_NOMEM;
124890  memset(t, 0, sizeof(*t));
124891
124892  /* TODO(shess) Delimiters need to remain the same from run to run,
124893  ** else we need to reindex.  One solution would be a meta-table to
124894  ** track such information in the database, then we'd only want this
124895  ** information on the initial create.
124896  */
124897  if( argc>1 ){
124898    int i, n = (int)strlen(argv[1]);
124899    for(i=0; i<n; i++){
124900      unsigned char ch = argv[1][i];
124901      /* We explicitly don't support UTF-8 delimiters for now. */
124902      if( ch>=0x80 ){
124903        sqlite3_free(t);
124904        return SQLITE_ERROR;
124905      }
124906      t->delim[ch] = 1;
124907    }
124908  } else {
124909    /* Mark non-alphanumeric ASCII characters as delimiters */
124910    int i;
124911    for(i=1; i<0x80; i++){
124912      t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
124913    }
124914  }
124915
124916  *ppTokenizer = &t->base;
124917  return SQLITE_OK;
124918}
124919
124920/*
124921** Destroy a tokenizer
124922*/
124923static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
124924  sqlite3_free(pTokenizer);
124925  return SQLITE_OK;
124926}
124927
124928/*
124929** Prepare to begin tokenizing a particular string.  The input
124930** string to be tokenized is pInput[0..nBytes-1].  A cursor
124931** used to incrementally tokenize this string is returned in
124932** *ppCursor.
124933*/
124934static int simpleOpen(
124935  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
124936  const char *pInput, int nBytes,        /* String to be tokenized */
124937  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
124938){
124939  simple_tokenizer_cursor *c;
124940
124941  UNUSED_PARAMETER(pTokenizer);
124942
124943  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
124944  if( c==NULL ) return SQLITE_NOMEM;
124945
124946  c->pInput = pInput;
124947  if( pInput==0 ){
124948    c->nBytes = 0;
124949  }else if( nBytes<0 ){
124950    c->nBytes = (int)strlen(pInput);
124951  }else{
124952    c->nBytes = nBytes;
124953  }
124954  c->iOffset = 0;                 /* start tokenizing at the beginning */
124955  c->iToken = 0;
124956  c->pToken = NULL;               /* no space allocated, yet. */
124957  c->nTokenAllocated = 0;
124958
124959  *ppCursor = &c->base;
124960  return SQLITE_OK;
124961}
124962
124963/*
124964** Close a tokenization cursor previously opened by a call to
124965** simpleOpen() above.
124966*/
124967static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
124968  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
124969  sqlite3_free(c->pToken);
124970  sqlite3_free(c);
124971  return SQLITE_OK;
124972}
124973
124974/*
124975** Extract the next token from a tokenization cursor.  The cursor must
124976** have been opened by a prior call to simpleOpen().
124977*/
124978static int simpleNext(
124979  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
124980  const char **ppToken,               /* OUT: *ppToken is the token text */
124981  int *pnBytes,                       /* OUT: Number of bytes in token */
124982  int *piStartOffset,                 /* OUT: Starting offset of token */
124983  int *piEndOffset,                   /* OUT: Ending offset of token */
124984  int *piPosition                     /* OUT: Position integer of token */
124985){
124986  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
124987  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
124988  unsigned char *p = (unsigned char *)c->pInput;
124989
124990  while( c->iOffset<c->nBytes ){
124991    int iStartOffset;
124992
124993    /* Scan past delimiter characters */
124994    while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
124995      c->iOffset++;
124996    }
124997
124998    /* Count non-delimiter characters. */
124999    iStartOffset = c->iOffset;
125000    while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
125001      c->iOffset++;
125002    }
125003
125004    if( c->iOffset>iStartOffset ){
125005      int i, n = c->iOffset-iStartOffset;
125006      if( n>c->nTokenAllocated ){
125007        char *pNew;
125008        c->nTokenAllocated = n+20;
125009        pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
125010        if( !pNew ) return SQLITE_NOMEM;
125011        c->pToken = pNew;
125012      }
125013      for(i=0; i<n; i++){
125014        /* TODO(shess) This needs expansion to handle UTF-8
125015        ** case-insensitivity.
125016        */
125017        unsigned char ch = p[iStartOffset+i];
125018        c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
125019      }
125020      *ppToken = c->pToken;
125021      *pnBytes = n;
125022      *piStartOffset = iStartOffset;
125023      *piEndOffset = c->iOffset;
125024      *piPosition = c->iToken++;
125025
125026      return SQLITE_OK;
125027    }
125028  }
125029  return SQLITE_DONE;
125030}
125031
125032/*
125033** The set of routines that implement the simple tokenizer
125034*/
125035static const sqlite3_tokenizer_module simpleTokenizerModule = {
125036  0,
125037  simpleCreate,
125038  simpleDestroy,
125039  simpleOpen,
125040  simpleClose,
125041  simpleNext,
125042  0,
125043};
125044
125045/*
125046** Allocate a new simple tokenizer.  Return a pointer to the new
125047** tokenizer in *ppModule
125048*/
125049SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
125050  sqlite3_tokenizer_module const**ppModule
125051){
125052  *ppModule = &simpleTokenizerModule;
125053}
125054
125055#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125056
125057/************** End of fts3_tokenizer1.c *************************************/
125058/************** Begin file fts3_write.c **************************************/
125059/*
125060** 2009 Oct 23
125061**
125062** The author disclaims copyright to this source code.  In place of
125063** a legal notice, here is a blessing:
125064**
125065**    May you do good and not evil.
125066**    May you find forgiveness for yourself and forgive others.
125067**    May you share freely, never taking more than you give.
125068**
125069******************************************************************************
125070**
125071** This file is part of the SQLite FTS3 extension module. Specifically,
125072** this file contains code to insert, update and delete rows from FTS3
125073** tables. It also contains code to merge FTS3 b-tree segments. Some
125074** of the sub-routines used to merge segments are also used by the query
125075** code in fts3.c.
125076*/
125077
125078#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125079
125080/* #include <string.h> */
125081/* #include <assert.h> */
125082/* #include <stdlib.h> */
125083
125084/*
125085** When full-text index nodes are loaded from disk, the buffer that they
125086** are loaded into has the following number of bytes of padding at the end
125087** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
125088** of 920 bytes is allocated for it.
125089**
125090** This means that if we have a pointer into a buffer containing node data,
125091** it is always safe to read up to two varints from it without risking an
125092** overread, even if the node data is corrupted.
125093*/
125094#define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
125095
125096/*
125097** Under certain circumstances, b-tree nodes (doclists) can be loaded into
125098** memory incrementally instead of all at once. This can be a big performance
125099** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
125100** method before retrieving all query results (as may happen, for example,
125101** if a query has a LIMIT clause).
125102**
125103** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
125104** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
125105** The code is written so that the hard lower-limit for each of these values
125106** is 1. Clearly such small values would be inefficient, but can be useful
125107** for testing purposes.
125108**
125109** If this module is built with SQLITE_TEST defined, these constants may
125110** be overridden at runtime for testing purposes. File fts3_test.c contains
125111** a Tcl interface to read and write the values.
125112*/
125113#ifdef SQLITE_TEST
125114int test_fts3_node_chunksize = (4*1024);
125115int test_fts3_node_chunk_threshold = (4*1024)*4;
125116# define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
125117# define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
125118#else
125119# define FTS3_NODE_CHUNKSIZE (4*1024)
125120# define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
125121#endif
125122
125123typedef struct PendingList PendingList;
125124typedef struct SegmentNode SegmentNode;
125125typedef struct SegmentWriter SegmentWriter;
125126
125127/*
125128** An instance of the following data structure is used to build doclists
125129** incrementally. See function fts3PendingListAppend() for details.
125130*/
125131struct PendingList {
125132  int nData;
125133  char *aData;
125134  int nSpace;
125135  sqlite3_int64 iLastDocid;
125136  sqlite3_int64 iLastCol;
125137  sqlite3_int64 iLastPos;
125138};
125139
125140
125141/*
125142** Each cursor has a (possibly empty) linked list of the following objects.
125143*/
125144struct Fts3DeferredToken {
125145  Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
125146  int iCol;                       /* Column token must occur in */
125147  Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
125148  PendingList *pList;             /* Doclist is assembled here */
125149};
125150
125151/*
125152** An instance of this structure is used to iterate through the terms on
125153** a contiguous set of segment b-tree leaf nodes. Although the details of
125154** this structure are only manipulated by code in this file, opaque handles
125155** of type Fts3SegReader* are also used by code in fts3.c to iterate through
125156** terms when querying the full-text index. See functions:
125157**
125158**   sqlite3Fts3SegReaderNew()
125159**   sqlite3Fts3SegReaderFree()
125160**   sqlite3Fts3SegReaderIterate()
125161**
125162** Methods used to manipulate Fts3SegReader structures:
125163**
125164**   fts3SegReaderNext()
125165**   fts3SegReaderFirstDocid()
125166**   fts3SegReaderNextDocid()
125167*/
125168struct Fts3SegReader {
125169  int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
125170  int bLookup;                    /* True for a lookup only */
125171
125172  sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
125173  sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
125174  sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
125175  sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
125176
125177  char *aNode;                    /* Pointer to node data (or NULL) */
125178  int nNode;                      /* Size of buffer at aNode (or 0) */
125179  int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
125180  sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
125181
125182  Fts3HashElem **ppNextElem;
125183
125184  /* Variables set by fts3SegReaderNext(). These may be read directly
125185  ** by the caller. They are valid from the time SegmentReaderNew() returns
125186  ** until SegmentReaderNext() returns something other than SQLITE_OK
125187  ** (i.e. SQLITE_DONE).
125188  */
125189  int nTerm;                      /* Number of bytes in current term */
125190  char *zTerm;                    /* Pointer to current term */
125191  int nTermAlloc;                 /* Allocated size of zTerm buffer */
125192  char *aDoclist;                 /* Pointer to doclist of current entry */
125193  int nDoclist;                   /* Size of doclist in current entry */
125194
125195  /* The following variables are used by fts3SegReaderNextDocid() to iterate
125196  ** through the current doclist (aDoclist/nDoclist).
125197  */
125198  char *pOffsetList;
125199  int nOffsetList;                /* For descending pending seg-readers only */
125200  sqlite3_int64 iDocid;
125201};
125202
125203#define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
125204#define fts3SegReaderIsRootOnly(p) ((p)->aNode==(char *)&(p)[1])
125205
125206/*
125207** An instance of this structure is used to create a segment b-tree in the
125208** database. The internal details of this type are only accessed by the
125209** following functions:
125210**
125211**   fts3SegWriterAdd()
125212**   fts3SegWriterFlush()
125213**   fts3SegWriterFree()
125214*/
125215struct SegmentWriter {
125216  SegmentNode *pTree;             /* Pointer to interior tree structure */
125217  sqlite3_int64 iFirst;           /* First slot in %_segments written */
125218  sqlite3_int64 iFree;            /* Next free slot in %_segments */
125219  char *zTerm;                    /* Pointer to previous term buffer */
125220  int nTerm;                      /* Number of bytes in zTerm */
125221  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
125222  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
125223  int nSize;                      /* Size of allocation at aData */
125224  int nData;                      /* Bytes of data in aData */
125225  char *aData;                    /* Pointer to block from malloc() */
125226};
125227
125228/*
125229** Type SegmentNode is used by the following three functions to create
125230** the interior part of the segment b+-tree structures (everything except
125231** the leaf nodes). These functions and type are only ever used by code
125232** within the fts3SegWriterXXX() family of functions described above.
125233**
125234**   fts3NodeAddTerm()
125235**   fts3NodeWrite()
125236**   fts3NodeFree()
125237**
125238** When a b+tree is written to the database (either as a result of a merge
125239** or the pending-terms table being flushed), leaves are written into the
125240** database file as soon as they are completely populated. The interior of
125241** the tree is assembled in memory and written out only once all leaves have
125242** been populated and stored. This is Ok, as the b+-tree fanout is usually
125243** very large, meaning that the interior of the tree consumes relatively
125244** little memory.
125245*/
125246struct SegmentNode {
125247  SegmentNode *pParent;           /* Parent node (or NULL for root node) */
125248  SegmentNode *pRight;            /* Pointer to right-sibling */
125249  SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
125250  int nEntry;                     /* Number of terms written to node so far */
125251  char *zTerm;                    /* Pointer to previous term buffer */
125252  int nTerm;                      /* Number of bytes in zTerm */
125253  int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
125254  char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
125255  int nData;                      /* Bytes of valid data so far */
125256  char *aData;                    /* Node data */
125257};
125258
125259/*
125260** Valid values for the second argument to fts3SqlStmt().
125261*/
125262#define SQL_DELETE_CONTENT             0
125263#define SQL_IS_EMPTY                   1
125264#define SQL_DELETE_ALL_CONTENT         2
125265#define SQL_DELETE_ALL_SEGMENTS        3
125266#define SQL_DELETE_ALL_SEGDIR          4
125267#define SQL_DELETE_ALL_DOCSIZE         5
125268#define SQL_DELETE_ALL_STAT            6
125269#define SQL_SELECT_CONTENT_BY_ROWID    7
125270#define SQL_NEXT_SEGMENT_INDEX         8
125271#define SQL_INSERT_SEGMENTS            9
125272#define SQL_NEXT_SEGMENTS_ID          10
125273#define SQL_INSERT_SEGDIR             11
125274#define SQL_SELECT_LEVEL              12
125275#define SQL_SELECT_LEVEL_RANGE        13
125276#define SQL_SELECT_LEVEL_COUNT        14
125277#define SQL_SELECT_SEGDIR_MAX_LEVEL   15
125278#define SQL_DELETE_SEGDIR_LEVEL       16
125279#define SQL_DELETE_SEGMENTS_RANGE     17
125280#define SQL_CONTENT_INSERT            18
125281#define SQL_DELETE_DOCSIZE            19
125282#define SQL_REPLACE_DOCSIZE           20
125283#define SQL_SELECT_DOCSIZE            21
125284#define SQL_SELECT_DOCTOTAL           22
125285#define SQL_REPLACE_DOCTOTAL          23
125286
125287#define SQL_SELECT_ALL_PREFIX_LEVEL   24
125288#define SQL_DELETE_ALL_TERMS_SEGDIR   25
125289
125290#define SQL_DELETE_SEGDIR_RANGE       26
125291
125292#define SQL_SELECT_ALL_LANGID         27
125293
125294/*
125295** This function is used to obtain an SQLite prepared statement handle
125296** for the statement identified by the second argument. If successful,
125297** *pp is set to the requested statement handle and SQLITE_OK returned.
125298** Otherwise, an SQLite error code is returned and *pp is set to 0.
125299**
125300** If argument apVal is not NULL, then it must point to an array with
125301** at least as many entries as the requested statement has bound
125302** parameters. The values are bound to the statements parameters before
125303** returning.
125304*/
125305static int fts3SqlStmt(
125306  Fts3Table *p,                   /* Virtual table handle */
125307  int eStmt,                      /* One of the SQL_XXX constants above */
125308  sqlite3_stmt **pp,              /* OUT: Statement handle */
125309  sqlite3_value **apVal           /* Values to bind to statement */
125310){
125311  const char *azSql[] = {
125312/* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
125313/* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
125314/* 2  */  "DELETE FROM %Q.'%q_content'",
125315/* 3  */  "DELETE FROM %Q.'%q_segments'",
125316/* 4  */  "DELETE FROM %Q.'%q_segdir'",
125317/* 5  */  "DELETE FROM %Q.'%q_docsize'",
125318/* 6  */  "DELETE FROM %Q.'%q_stat'",
125319/* 7  */  "SELECT %s WHERE rowid=?",
125320/* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
125321/* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
125322/* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
125323/* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
125324
125325          /* Return segments in order from oldest to newest.*/
125326/* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
125327            "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
125328/* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
125329            "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
125330            "ORDER BY level DESC, idx ASC",
125331
125332/* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
125333/* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
125334
125335/* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
125336/* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
125337/* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
125338/* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
125339/* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
125340/* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
125341/* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
125342/* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
125343/* 24 */  "",
125344/* 25 */  "",
125345
125346/* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
125347/* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
125348
125349  };
125350  int rc = SQLITE_OK;
125351  sqlite3_stmt *pStmt;
125352
125353  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
125354  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
125355
125356  pStmt = p->aStmt[eStmt];
125357  if( !pStmt ){
125358    char *zSql;
125359    if( eStmt==SQL_CONTENT_INSERT ){
125360      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
125361    }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
125362      zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
125363    }else{
125364      zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
125365    }
125366    if( !zSql ){
125367      rc = SQLITE_NOMEM;
125368    }else{
125369      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
125370      sqlite3_free(zSql);
125371      assert( rc==SQLITE_OK || pStmt==0 );
125372      p->aStmt[eStmt] = pStmt;
125373    }
125374  }
125375  if( apVal ){
125376    int i;
125377    int nParam = sqlite3_bind_parameter_count(pStmt);
125378    for(i=0; rc==SQLITE_OK && i<nParam; i++){
125379      rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
125380    }
125381  }
125382  *pp = pStmt;
125383  return rc;
125384}
125385
125386static int fts3SelectDocsize(
125387  Fts3Table *pTab,                /* FTS3 table handle */
125388  int eStmt,                      /* Either SQL_SELECT_DOCSIZE or DOCTOTAL */
125389  sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
125390  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
125391){
125392  sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
125393  int rc;                         /* Return code */
125394
125395  assert( eStmt==SQL_SELECT_DOCSIZE || eStmt==SQL_SELECT_DOCTOTAL );
125396
125397  rc = fts3SqlStmt(pTab, eStmt, &pStmt, 0);
125398  if( rc==SQLITE_OK ){
125399    if( eStmt==SQL_SELECT_DOCSIZE ){
125400      sqlite3_bind_int64(pStmt, 1, iDocid);
125401    }
125402    rc = sqlite3_step(pStmt);
125403    if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
125404      rc = sqlite3_reset(pStmt);
125405      if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
125406      pStmt = 0;
125407    }else{
125408      rc = SQLITE_OK;
125409    }
125410  }
125411
125412  *ppStmt = pStmt;
125413  return rc;
125414}
125415
125416SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
125417  Fts3Table *pTab,                /* Fts3 table handle */
125418  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
125419){
125420  return fts3SelectDocsize(pTab, SQL_SELECT_DOCTOTAL, 0, ppStmt);
125421}
125422
125423SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
125424  Fts3Table *pTab,                /* Fts3 table handle */
125425  sqlite3_int64 iDocid,           /* Docid to read size data for */
125426  sqlite3_stmt **ppStmt           /* OUT: Statement handle */
125427){
125428  return fts3SelectDocsize(pTab, SQL_SELECT_DOCSIZE, iDocid, ppStmt);
125429}
125430
125431/*
125432** Similar to fts3SqlStmt(). Except, after binding the parameters in
125433** array apVal[] to the SQL statement identified by eStmt, the statement
125434** is executed.
125435**
125436** Returns SQLITE_OK if the statement is successfully executed, or an
125437** SQLite error code otherwise.
125438*/
125439static void fts3SqlExec(
125440  int *pRC,                /* Result code */
125441  Fts3Table *p,            /* The FTS3 table */
125442  int eStmt,               /* Index of statement to evaluate */
125443  sqlite3_value **apVal    /* Parameters to bind */
125444){
125445  sqlite3_stmt *pStmt;
125446  int rc;
125447  if( *pRC ) return;
125448  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
125449  if( rc==SQLITE_OK ){
125450    sqlite3_step(pStmt);
125451    rc = sqlite3_reset(pStmt);
125452  }
125453  *pRC = rc;
125454}
125455
125456
125457/*
125458** This function ensures that the caller has obtained a shared-cache
125459** table-lock on the %_content table. This is required before reading
125460** data from the fts3 table. If this lock is not acquired first, then
125461** the caller may end up holding read-locks on the %_segments and %_segdir
125462** tables, but no read-lock on the %_content table. If this happens
125463** a second connection will be able to write to the fts3 table, but
125464** attempting to commit those writes might return SQLITE_LOCKED or
125465** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain
125466** write-locks on the %_segments and %_segdir ** tables).
125467**
125468** We try to avoid this because if FTS3 returns any error when committing
125469** a transaction, the whole transaction will be rolled back. And this is
125470** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
125471** still happen if the user reads data directly from the %_segments or
125472** %_segdir tables instead of going through FTS3 though.
125473**
125474** This reasoning does not apply to a content=xxx table.
125475*/
125476SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
125477  int rc;                         /* Return code */
125478  sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
125479
125480  if( p->zContentTbl==0 ){
125481    rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
125482    if( rc==SQLITE_OK ){
125483      sqlite3_bind_null(pStmt, 1);
125484      sqlite3_step(pStmt);
125485      rc = sqlite3_reset(pStmt);
125486    }
125487  }else{
125488    rc = SQLITE_OK;
125489  }
125490
125491  return rc;
125492}
125493
125494/*
125495** FTS maintains a separate indexes for each language-id (a 32-bit integer).
125496** Within each language id, a separate index is maintained to store the
125497** document terms, and each configured prefix size (configured the FTS
125498** "prefix=" option). And each index consists of multiple levels ("relative
125499** levels").
125500**
125501** All three of these values (the language id, the specific index and the
125502** level within the index) are encoded in 64-bit integer values stored
125503** in the %_segdir table on disk. This function is used to convert three
125504** separate component values into the single 64-bit integer value that
125505** can be used to query the %_segdir table.
125506**
125507** Specifically, each language-id/index combination is allocated 1024
125508** 64-bit integer level values ("absolute levels"). The main terms index
125509** for language-id 0 is allocate values 0-1023. The first prefix index
125510** (if any) for language-id 0 is allocated values 1024-2047. And so on.
125511** Language 1 indexes are allocated immediately following language 0.
125512**
125513** So, for a system with nPrefix prefix indexes configured, the block of
125514** absolute levels that corresponds to language-id iLangid and index
125515** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
125516*/
125517static sqlite3_int64 getAbsoluteLevel(
125518  Fts3Table *p,
125519  int iLangid,
125520  int iIndex,
125521  int iLevel
125522){
125523  sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
125524  assert( iLangid>=0 );
125525  assert( p->nIndex>0 );
125526  assert( iIndex>=0 && iIndex<p->nIndex );
125527
125528  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
125529  return iBase + iLevel;
125530}
125531
125532
125533/*
125534** Set *ppStmt to a statement handle that may be used to iterate through
125535** all rows in the %_segdir table, from oldest to newest. If successful,
125536** return SQLITE_OK. If an error occurs while preparing the statement,
125537** return an SQLite error code.
125538**
125539** There is only ever one instance of this SQL statement compiled for
125540** each FTS3 table.
125541**
125542** The statement returns the following columns from the %_segdir table:
125543**
125544**   0: idx
125545**   1: start_block
125546**   2: leaves_end_block
125547**   3: end_block
125548**   4: root
125549*/
125550SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
125551  Fts3Table *p,                   /* FTS3 table */
125552  int iLangid,                    /* Language being queried */
125553  int iIndex,                     /* Index for p->aIndex[] */
125554  int iLevel,                     /* Level to select (relative level) */
125555  sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
125556){
125557  int rc;
125558  sqlite3_stmt *pStmt = 0;
125559
125560  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
125561  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
125562  assert( iIndex>=0 && iIndex<p->nIndex );
125563
125564  if( iLevel<0 ){
125565    /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
125566    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
125567    if( rc==SQLITE_OK ){
125568      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
125569      sqlite3_bind_int64(pStmt, 2,
125570          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
125571      );
125572    }
125573  }else{
125574    /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
125575    rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
125576    if( rc==SQLITE_OK ){
125577      sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
125578    }
125579  }
125580  *ppStmt = pStmt;
125581  return rc;
125582}
125583
125584
125585/*
125586** Append a single varint to a PendingList buffer. SQLITE_OK is returned
125587** if successful, or an SQLite error code otherwise.
125588**
125589** This function also serves to allocate the PendingList structure itself.
125590** For example, to create a new PendingList structure containing two
125591** varints:
125592**
125593**   PendingList *p = 0;
125594**   fts3PendingListAppendVarint(&p, 1);
125595**   fts3PendingListAppendVarint(&p, 2);
125596*/
125597static int fts3PendingListAppendVarint(
125598  PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
125599  sqlite3_int64 i                 /* Value to append to data */
125600){
125601  PendingList *p = *pp;
125602
125603  /* Allocate or grow the PendingList as required. */
125604  if( !p ){
125605    p = sqlite3_malloc(sizeof(*p) + 100);
125606    if( !p ){
125607      return SQLITE_NOMEM;
125608    }
125609    p->nSpace = 100;
125610    p->aData = (char *)&p[1];
125611    p->nData = 0;
125612  }
125613  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
125614    int nNew = p->nSpace * 2;
125615    p = sqlite3_realloc(p, sizeof(*p) + nNew);
125616    if( !p ){
125617      sqlite3_free(*pp);
125618      *pp = 0;
125619      return SQLITE_NOMEM;
125620    }
125621    p->nSpace = nNew;
125622    p->aData = (char *)&p[1];
125623  }
125624
125625  /* Append the new serialized varint to the end of the list. */
125626  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
125627  p->aData[p->nData] = '\0';
125628  *pp = p;
125629  return SQLITE_OK;
125630}
125631
125632/*
125633** Add a docid/column/position entry to a PendingList structure. Non-zero
125634** is returned if the structure is sqlite3_realloced as part of adding
125635** the entry. Otherwise, zero.
125636**
125637** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
125638** Zero is always returned in this case. Otherwise, if no OOM error occurs,
125639** it is set to SQLITE_OK.
125640*/
125641static int fts3PendingListAppend(
125642  PendingList **pp,               /* IN/OUT: PendingList structure */
125643  sqlite3_int64 iDocid,           /* Docid for entry to add */
125644  sqlite3_int64 iCol,             /* Column for entry to add */
125645  sqlite3_int64 iPos,             /* Position of term for entry to add */
125646  int *pRc                        /* OUT: Return code */
125647){
125648  PendingList *p = *pp;
125649  int rc = SQLITE_OK;
125650
125651  assert( !p || p->iLastDocid<=iDocid );
125652
125653  if( !p || p->iLastDocid!=iDocid ){
125654    sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
125655    if( p ){
125656      assert( p->nData<p->nSpace );
125657      assert( p->aData[p->nData]==0 );
125658      p->nData++;
125659    }
125660    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
125661      goto pendinglistappend_out;
125662    }
125663    p->iLastCol = -1;
125664    p->iLastPos = 0;
125665    p->iLastDocid = iDocid;
125666  }
125667  if( iCol>0 && p->iLastCol!=iCol ){
125668    if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
125669     || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
125670    ){
125671      goto pendinglistappend_out;
125672    }
125673    p->iLastCol = iCol;
125674    p->iLastPos = 0;
125675  }
125676  if( iCol>=0 ){
125677    assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
125678    rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
125679    if( rc==SQLITE_OK ){
125680      p->iLastPos = iPos;
125681    }
125682  }
125683
125684 pendinglistappend_out:
125685  *pRc = rc;
125686  if( p!=*pp ){
125687    *pp = p;
125688    return 1;
125689  }
125690  return 0;
125691}
125692
125693/*
125694** Free a PendingList object allocated by fts3PendingListAppend().
125695*/
125696static void fts3PendingListDelete(PendingList *pList){
125697  sqlite3_free(pList);
125698}
125699
125700/*
125701** Add an entry to one of the pending-terms hash tables.
125702*/
125703static int fts3PendingTermsAddOne(
125704  Fts3Table *p,
125705  int iCol,
125706  int iPos,
125707  Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
125708  const char *zToken,
125709  int nToken
125710){
125711  PendingList *pList;
125712  int rc = SQLITE_OK;
125713
125714  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
125715  if( pList ){
125716    p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
125717  }
125718  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
125719    if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
125720      /* Malloc failed while inserting the new entry. This can only
125721      ** happen if there was no previous entry for this token.
125722      */
125723      assert( 0==fts3HashFind(pHash, zToken, nToken) );
125724      sqlite3_free(pList);
125725      rc = SQLITE_NOMEM;
125726    }
125727  }
125728  if( rc==SQLITE_OK ){
125729    p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
125730  }
125731  return rc;
125732}
125733
125734/*
125735** Tokenize the nul-terminated string zText and add all tokens to the
125736** pending-terms hash-table. The docid used is that currently stored in
125737** p->iPrevDocid, and the column is specified by argument iCol.
125738**
125739** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
125740*/
125741static int fts3PendingTermsAdd(
125742  Fts3Table *p,                   /* Table into which text will be inserted */
125743  int iLangid,                    /* Language id to use */
125744  const char *zText,              /* Text of document to be inserted */
125745  int iCol,                       /* Column into which text is being inserted */
125746  u32 *pnWord                     /* OUT: Number of tokens inserted */
125747){
125748  int rc;
125749  int iStart;
125750  int iEnd;
125751  int iPos;
125752  int nWord = 0;
125753
125754  char const *zToken;
125755  int nToken;
125756
125757  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
125758  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
125759  sqlite3_tokenizer_cursor *pCsr;
125760  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
125761      const char**,int*,int*,int*,int*);
125762
125763  assert( pTokenizer && pModule );
125764
125765  /* If the user has inserted a NULL value, this function may be called with
125766  ** zText==0. In this case, add zero token entries to the hash table and
125767  ** return early. */
125768  if( zText==0 ){
125769    *pnWord = 0;
125770    return SQLITE_OK;
125771  }
125772
125773  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
125774  if( rc!=SQLITE_OK ){
125775    return rc;
125776  }
125777
125778  xNext = pModule->xNext;
125779  while( SQLITE_OK==rc
125780      && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
125781  ){
125782    int i;
125783    if( iPos>=nWord ) nWord = iPos+1;
125784
125785    /* Positions cannot be negative; we use -1 as a terminator internally.
125786    ** Tokens must have a non-zero length.
125787    */
125788    if( iPos<0 || !zToken || nToken<=0 ){
125789      rc = SQLITE_ERROR;
125790      break;
125791    }
125792
125793    /* Add the term to the terms index */
125794    rc = fts3PendingTermsAddOne(
125795        p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
125796    );
125797
125798    /* Add the term to each of the prefix indexes that it is not too
125799    ** short for. */
125800    for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
125801      struct Fts3Index *pIndex = &p->aIndex[i];
125802      if( nToken<pIndex->nPrefix ) continue;
125803      rc = fts3PendingTermsAddOne(
125804          p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
125805      );
125806    }
125807  }
125808
125809  pModule->xClose(pCsr);
125810  *pnWord = nWord;
125811  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
125812}
125813
125814/*
125815** Calling this function indicates that subsequent calls to
125816** fts3PendingTermsAdd() are to add term/position-list pairs for the
125817** contents of the document with docid iDocid.
125818*/
125819static int fts3PendingTermsDocid(
125820  Fts3Table *p,                   /* Full-text table handle */
125821  int iLangid,                    /* Language id of row being written */
125822  sqlite_int64 iDocid             /* Docid of row being written */
125823){
125824  assert( iLangid>=0 );
125825
125826  /* TODO(shess) Explore whether partially flushing the buffer on
125827  ** forced-flush would provide better performance.  I suspect that if
125828  ** we ordered the doclists by size and flushed the largest until the
125829  ** buffer was half empty, that would let the less frequent terms
125830  ** generate longer doclists.
125831  */
125832  if( iDocid<=p->iPrevDocid
125833   || p->iPrevLangid!=iLangid
125834   || p->nPendingData>p->nMaxPendingData
125835  ){
125836    int rc = sqlite3Fts3PendingTermsFlush(p);
125837    if( rc!=SQLITE_OK ) return rc;
125838  }
125839  p->iPrevDocid = iDocid;
125840  p->iPrevLangid = iLangid;
125841  return SQLITE_OK;
125842}
125843
125844/*
125845** Discard the contents of the pending-terms hash tables.
125846*/
125847SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
125848  int i;
125849  for(i=0; i<p->nIndex; i++){
125850    Fts3HashElem *pElem;
125851    Fts3Hash *pHash = &p->aIndex[i].hPending;
125852    for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
125853      PendingList *pList = (PendingList *)fts3HashData(pElem);
125854      fts3PendingListDelete(pList);
125855    }
125856    fts3HashClear(pHash);
125857  }
125858  p->nPendingData = 0;
125859}
125860
125861/*
125862** This function is called by the xUpdate() method as part of an INSERT
125863** operation. It adds entries for each term in the new record to the
125864** pendingTerms hash table.
125865**
125866** Argument apVal is the same as the similarly named argument passed to
125867** fts3InsertData(). Parameter iDocid is the docid of the new row.
125868*/
125869static int fts3InsertTerms(
125870  Fts3Table *p,
125871  int iLangid,
125872  sqlite3_value **apVal,
125873  u32 *aSz
125874){
125875  int i;                          /* Iterator variable */
125876  for(i=2; i<p->nColumn+2; i++){
125877    const char *zText = (const char *)sqlite3_value_text(apVal[i]);
125878    int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
125879    if( rc!=SQLITE_OK ){
125880      return rc;
125881    }
125882    aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
125883  }
125884  return SQLITE_OK;
125885}
125886
125887/*
125888** This function is called by the xUpdate() method for an INSERT operation.
125889** The apVal parameter is passed a copy of the apVal argument passed by
125890** SQLite to the xUpdate() method. i.e:
125891**
125892**   apVal[0]                Not used for INSERT.
125893**   apVal[1]                rowid
125894**   apVal[2]                Left-most user-defined column
125895**   ...
125896**   apVal[p->nColumn+1]     Right-most user-defined column
125897**   apVal[p->nColumn+2]     Hidden column with same name as table
125898**   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
125899**   apVal[p->nColumn+4]     Hidden languageid column
125900*/
125901static int fts3InsertData(
125902  Fts3Table *p,                   /* Full-text table */
125903  sqlite3_value **apVal,          /* Array of values to insert */
125904  sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
125905){
125906  int rc;                         /* Return code */
125907  sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
125908
125909  if( p->zContentTbl ){
125910    sqlite3_value *pRowid = apVal[p->nColumn+3];
125911    if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
125912      pRowid = apVal[1];
125913    }
125914    if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
125915      return SQLITE_CONSTRAINT;
125916    }
125917    *piDocid = sqlite3_value_int64(pRowid);
125918    return SQLITE_OK;
125919  }
125920
125921  /* Locate the statement handle used to insert data into the %_content
125922  ** table. The SQL for this statement is:
125923  **
125924  **   INSERT INTO %_content VALUES(?, ?, ?, ...)
125925  **
125926  ** The statement features N '?' variables, where N is the number of user
125927  ** defined columns in the FTS3 table, plus one for the docid field.
125928  */
125929  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
125930  if( rc==SQLITE_OK && p->zLanguageid ){
125931    rc = sqlite3_bind_int(
125932        pContentInsert, p->nColumn+2,
125933        sqlite3_value_int(apVal[p->nColumn+4])
125934    );
125935  }
125936  if( rc!=SQLITE_OK ) return rc;
125937
125938  /* There is a quirk here. The users INSERT statement may have specified
125939  ** a value for the "rowid" field, for the "docid" field, or for both.
125940  ** Which is a problem, since "rowid" and "docid" are aliases for the
125941  ** same value. For example:
125942  **
125943  **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
125944  **
125945  ** In FTS3, this is an error. It is an error to specify non-NULL values
125946  ** for both docid and some other rowid alias.
125947  */
125948  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
125949    if( SQLITE_NULL==sqlite3_value_type(apVal[0])
125950     && SQLITE_NULL!=sqlite3_value_type(apVal[1])
125951    ){
125952      /* A rowid/docid conflict. */
125953      return SQLITE_ERROR;
125954    }
125955    rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
125956    if( rc!=SQLITE_OK ) return rc;
125957  }
125958
125959  /* Execute the statement to insert the record. Set *piDocid to the
125960  ** new docid value.
125961  */
125962  sqlite3_step(pContentInsert);
125963  rc = sqlite3_reset(pContentInsert);
125964
125965  *piDocid = sqlite3_last_insert_rowid(p->db);
125966  return rc;
125967}
125968
125969
125970
125971/*
125972** Remove all data from the FTS3 table. Clear the hash table containing
125973** pending terms.
125974*/
125975static int fts3DeleteAll(Fts3Table *p, int bContent){
125976  int rc = SQLITE_OK;             /* Return code */
125977
125978  /* Discard the contents of the pending-terms hash table. */
125979  sqlite3Fts3PendingTermsClear(p);
125980
125981  /* Delete everything from the shadow tables. Except, leave %_content as
125982  ** is if bContent is false.  */
125983  assert( p->zContentTbl==0 || bContent==0 );
125984  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
125985  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
125986  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
125987  if( p->bHasDocsize ){
125988    fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
125989  }
125990  if( p->bHasStat ){
125991    fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
125992  }
125993  return rc;
125994}
125995
125996/*
125997**
125998*/
125999static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
126000  int iLangid = 0;
126001  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
126002  return iLangid;
126003}
126004
126005/*
126006** The first element in the apVal[] array is assumed to contain the docid
126007** (an integer) of a row about to be deleted. Remove all terms from the
126008** full-text index.
126009*/
126010static void fts3DeleteTerms(
126011  int *pRC,               /* Result code */
126012  Fts3Table *p,           /* The FTS table to delete from */
126013  sqlite3_value *pRowid,  /* The docid to be deleted */
126014  u32 *aSz                /* Sizes of deleted document written here */
126015){
126016  int rc;
126017  sqlite3_stmt *pSelect;
126018
126019  if( *pRC ) return;
126020  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
126021  if( rc==SQLITE_OK ){
126022    if( SQLITE_ROW==sqlite3_step(pSelect) ){
126023      int i;
126024      int iLangid = langidFromSelect(p, pSelect);
126025      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
126026      for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
126027        const char *zText = (const char *)sqlite3_column_text(pSelect, i);
126028        rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
126029        aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
126030      }
126031      if( rc!=SQLITE_OK ){
126032        sqlite3_reset(pSelect);
126033        *pRC = rc;
126034        return;
126035      }
126036    }
126037    rc = sqlite3_reset(pSelect);
126038  }else{
126039    sqlite3_reset(pSelect);
126040  }
126041  *pRC = rc;
126042}
126043
126044/*
126045** Forward declaration to account for the circular dependency between
126046** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
126047*/
126048static int fts3SegmentMerge(Fts3Table *, int, int, int);
126049
126050/*
126051** This function allocates a new level iLevel index in the segdir table.
126052** Usually, indexes are allocated within a level sequentially starting
126053** with 0, so the allocated index is one greater than the value returned
126054** by:
126055**
126056**   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
126057**
126058** However, if there are already FTS3_MERGE_COUNT indexes at the requested
126059** level, they are merged into a single level (iLevel+1) segment and the
126060** allocated index is 0.
126061**
126062** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
126063** returned. Otherwise, an SQLite error code is returned.
126064*/
126065static int fts3AllocateSegdirIdx(
126066  Fts3Table *p,
126067  int iLangid,                    /* Language id */
126068  int iIndex,                     /* Index for p->aIndex */
126069  int iLevel,
126070  int *piIdx
126071){
126072  int rc;                         /* Return Code */
126073  sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
126074  int iNext = 0;                  /* Result of query pNextIdx */
126075
126076  assert( iLangid>=0 );
126077  assert( p->nIndex>=1 );
126078
126079  /* Set variable iNext to the next available segdir index at level iLevel. */
126080  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
126081  if( rc==SQLITE_OK ){
126082    sqlite3_bind_int64(
126083        pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
126084    );
126085    if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
126086      iNext = sqlite3_column_int(pNextIdx, 0);
126087    }
126088    rc = sqlite3_reset(pNextIdx);
126089  }
126090
126091  if( rc==SQLITE_OK ){
126092    /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
126093    ** full, merge all segments in level iLevel into a single iLevel+1
126094    ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
126095    ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
126096    */
126097    if( iNext>=FTS3_MERGE_COUNT ){
126098      rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
126099      *piIdx = 0;
126100    }else{
126101      *piIdx = iNext;
126102    }
126103  }
126104
126105  return rc;
126106}
126107
126108/*
126109** The %_segments table is declared as follows:
126110**
126111**   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
126112**
126113** This function reads data from a single row of the %_segments table. The
126114** specific row is identified by the iBlockid parameter. If paBlob is not
126115** NULL, then a buffer is allocated using sqlite3_malloc() and populated
126116** with the contents of the blob stored in the "block" column of the
126117** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
126118** to the size of the blob in bytes before returning.
126119**
126120** If an error occurs, or the table does not contain the specified row,
126121** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
126122** paBlob is non-NULL, then it is the responsibility of the caller to
126123** eventually free the returned buffer.
126124**
126125** This function may leave an open sqlite3_blob* handle in the
126126** Fts3Table.pSegments variable. This handle is reused by subsequent calls
126127** to this function. The handle may be closed by calling the
126128** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
126129** performance improvement, but the blob handle should always be closed
126130** before control is returned to the user (to prevent a lock being held
126131** on the database file for longer than necessary). Thus, any virtual table
126132** method (xFilter etc.) that may directly or indirectly call this function
126133** must call sqlite3Fts3SegmentsClose() before returning.
126134*/
126135SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
126136  Fts3Table *p,                   /* FTS3 table handle */
126137  sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
126138  char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
126139  int *pnBlob,                    /* OUT: Size of blob data */
126140  int *pnLoad                     /* OUT: Bytes actually loaded */
126141){
126142  int rc;                         /* Return code */
126143
126144  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
126145  assert( pnBlob);
126146
126147  if( p->pSegments ){
126148    rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
126149  }else{
126150    if( 0==p->zSegmentsTbl ){
126151      p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
126152      if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
126153    }
126154    rc = sqlite3_blob_open(
126155       p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
126156    );
126157  }
126158
126159  if( rc==SQLITE_OK ){
126160    int nByte = sqlite3_blob_bytes(p->pSegments);
126161    *pnBlob = nByte;
126162    if( paBlob ){
126163      char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
126164      if( !aByte ){
126165        rc = SQLITE_NOMEM;
126166      }else{
126167        if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
126168          nByte = FTS3_NODE_CHUNKSIZE;
126169          *pnLoad = nByte;
126170        }
126171        rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
126172        memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
126173        if( rc!=SQLITE_OK ){
126174          sqlite3_free(aByte);
126175          aByte = 0;
126176        }
126177      }
126178      *paBlob = aByte;
126179    }
126180  }
126181
126182  return rc;
126183}
126184
126185/*
126186** Close the blob handle at p->pSegments, if it is open. See comments above
126187** the sqlite3Fts3ReadBlock() function for details.
126188*/
126189SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
126190  sqlite3_blob_close(p->pSegments);
126191  p->pSegments = 0;
126192}
126193
126194static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
126195  int nRead;                      /* Number of bytes to read */
126196  int rc;                         /* Return code */
126197
126198  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
126199  rc = sqlite3_blob_read(
126200      pReader->pBlob,
126201      &pReader->aNode[pReader->nPopulate],
126202      nRead,
126203      pReader->nPopulate
126204  );
126205
126206  if( rc==SQLITE_OK ){
126207    pReader->nPopulate += nRead;
126208    memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
126209    if( pReader->nPopulate==pReader->nNode ){
126210      sqlite3_blob_close(pReader->pBlob);
126211      pReader->pBlob = 0;
126212      pReader->nPopulate = 0;
126213    }
126214  }
126215  return rc;
126216}
126217
126218static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
126219  int rc = SQLITE_OK;
126220  assert( !pReader->pBlob
126221       || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
126222  );
126223  while( pReader->pBlob && rc==SQLITE_OK
126224     &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
126225  ){
126226    rc = fts3SegReaderIncrRead(pReader);
126227  }
126228  return rc;
126229}
126230
126231/*
126232** Set an Fts3SegReader cursor to point at EOF.
126233*/
126234static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
126235  if( !fts3SegReaderIsRootOnly(pSeg) ){
126236    sqlite3_free(pSeg->aNode);
126237    sqlite3_blob_close(pSeg->pBlob);
126238    pSeg->pBlob = 0;
126239  }
126240  pSeg->aNode = 0;
126241}
126242
126243/*
126244** Move the iterator passed as the first argument to the next term in the
126245** segment. If successful, SQLITE_OK is returned. If there is no next term,
126246** SQLITE_DONE. Otherwise, an SQLite error code.
126247*/
126248static int fts3SegReaderNext(
126249  Fts3Table *p,
126250  Fts3SegReader *pReader,
126251  int bIncr
126252){
126253  int rc;                         /* Return code of various sub-routines */
126254  char *pNext;                    /* Cursor variable */
126255  int nPrefix;                    /* Number of bytes in term prefix */
126256  int nSuffix;                    /* Number of bytes in term suffix */
126257
126258  if( !pReader->aDoclist ){
126259    pNext = pReader->aNode;
126260  }else{
126261    pNext = &pReader->aDoclist[pReader->nDoclist];
126262  }
126263
126264  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
126265
126266    if( fts3SegReaderIsPending(pReader) ){
126267      Fts3HashElem *pElem = *(pReader->ppNextElem);
126268      if( pElem==0 ){
126269        pReader->aNode = 0;
126270      }else{
126271        PendingList *pList = (PendingList *)fts3HashData(pElem);
126272        pReader->zTerm = (char *)fts3HashKey(pElem);
126273        pReader->nTerm = fts3HashKeysize(pElem);
126274        pReader->nNode = pReader->nDoclist = pList->nData + 1;
126275        pReader->aNode = pReader->aDoclist = pList->aData;
126276        pReader->ppNextElem++;
126277        assert( pReader->aNode );
126278      }
126279      return SQLITE_OK;
126280    }
126281
126282    fts3SegReaderSetEof(pReader);
126283
126284    /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
126285    ** blocks have already been traversed.  */
126286    assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
126287    if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
126288      return SQLITE_OK;
126289    }
126290
126291    rc = sqlite3Fts3ReadBlock(
126292        p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
126293        (bIncr ? &pReader->nPopulate : 0)
126294    );
126295    if( rc!=SQLITE_OK ) return rc;
126296    assert( pReader->pBlob==0 );
126297    if( bIncr && pReader->nPopulate<pReader->nNode ){
126298      pReader->pBlob = p->pSegments;
126299      p->pSegments = 0;
126300    }
126301    pNext = pReader->aNode;
126302  }
126303
126304  assert( !fts3SegReaderIsPending(pReader) );
126305
126306  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
126307  if( rc!=SQLITE_OK ) return rc;
126308
126309  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
126310  ** safe (no risk of overread) even if the node data is corrupted. */
126311  pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
126312  pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
126313  if( nPrefix<0 || nSuffix<=0
126314   || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
126315  ){
126316    return FTS_CORRUPT_VTAB;
126317  }
126318
126319  if( nPrefix+nSuffix>pReader->nTermAlloc ){
126320    int nNew = (nPrefix+nSuffix)*2;
126321    char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
126322    if( !zNew ){
126323      return SQLITE_NOMEM;
126324    }
126325    pReader->zTerm = zNew;
126326    pReader->nTermAlloc = nNew;
126327  }
126328
126329  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
126330  if( rc!=SQLITE_OK ) return rc;
126331
126332  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
126333  pReader->nTerm = nPrefix+nSuffix;
126334  pNext += nSuffix;
126335  pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
126336  pReader->aDoclist = pNext;
126337  pReader->pOffsetList = 0;
126338
126339  /* Check that the doclist does not appear to extend past the end of the
126340  ** b-tree node. And that the final byte of the doclist is 0x00. If either
126341  ** of these statements is untrue, then the data structure is corrupt.
126342  */
126343  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
126344   || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
126345  ){
126346    return FTS_CORRUPT_VTAB;
126347  }
126348  return SQLITE_OK;
126349}
126350
126351/*
126352** Set the SegReader to point to the first docid in the doclist associated
126353** with the current term.
126354*/
126355static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
126356  int rc = SQLITE_OK;
126357  assert( pReader->aDoclist );
126358  assert( !pReader->pOffsetList );
126359  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
126360    u8 bEof = 0;
126361    pReader->iDocid = 0;
126362    pReader->nOffsetList = 0;
126363    sqlite3Fts3DoclistPrev(0,
126364        pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
126365        &pReader->iDocid, &pReader->nOffsetList, &bEof
126366    );
126367  }else{
126368    rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
126369    if( rc==SQLITE_OK ){
126370      int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
126371      pReader->pOffsetList = &pReader->aDoclist[n];
126372    }
126373  }
126374  return rc;
126375}
126376
126377/*
126378** Advance the SegReader to point to the next docid in the doclist
126379** associated with the current term.
126380**
126381** If arguments ppOffsetList and pnOffsetList are not NULL, then
126382** *ppOffsetList is set to point to the first column-offset list
126383** in the doclist entry (i.e. immediately past the docid varint).
126384** *pnOffsetList is set to the length of the set of column-offset
126385** lists, not including the nul-terminator byte. For example:
126386*/
126387static int fts3SegReaderNextDocid(
126388  Fts3Table *pTab,
126389  Fts3SegReader *pReader,         /* Reader to advance to next docid */
126390  char **ppOffsetList,            /* OUT: Pointer to current position-list */
126391  int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
126392){
126393  int rc = SQLITE_OK;
126394  char *p = pReader->pOffsetList;
126395  char c = 0;
126396
126397  assert( p );
126398
126399  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
126400    /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
126401    ** Pending-terms doclists are always built up in ascending order, so
126402    ** we have to iterate through them backwards here. */
126403    u8 bEof = 0;
126404    if( ppOffsetList ){
126405      *ppOffsetList = pReader->pOffsetList;
126406      *pnOffsetList = pReader->nOffsetList - 1;
126407    }
126408    sqlite3Fts3DoclistPrev(0,
126409        pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
126410        &pReader->nOffsetList, &bEof
126411    );
126412    if( bEof ){
126413      pReader->pOffsetList = 0;
126414    }else{
126415      pReader->pOffsetList = p;
126416    }
126417  }else{
126418    char *pEnd = &pReader->aDoclist[pReader->nDoclist];
126419
126420    /* Pointer p currently points at the first byte of an offset list. The
126421    ** following block advances it to point one byte past the end of
126422    ** the same offset list. */
126423    while( 1 ){
126424
126425      /* The following line of code (and the "p++" below the while() loop) is
126426      ** normally all that is required to move pointer p to the desired
126427      ** position. The exception is if this node is being loaded from disk
126428      ** incrementally and pointer "p" now points to the first byte passed
126429      ** the populated part of pReader->aNode[].
126430      */
126431      while( *p | c ) c = *p++ & 0x80;
126432      assert( *p==0 );
126433
126434      if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
126435      rc = fts3SegReaderIncrRead(pReader);
126436      if( rc!=SQLITE_OK ) return rc;
126437    }
126438    p++;
126439
126440    /* If required, populate the output variables with a pointer to and the
126441    ** size of the previous offset-list.
126442    */
126443    if( ppOffsetList ){
126444      *ppOffsetList = pReader->pOffsetList;
126445      *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
126446    }
126447
126448    while( p<pEnd && *p==0 ) p++;
126449
126450    /* If there are no more entries in the doclist, set pOffsetList to
126451    ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
126452    ** Fts3SegReader.pOffsetList to point to the next offset list before
126453    ** returning.
126454    */
126455    if( p>=pEnd ){
126456      pReader->pOffsetList = 0;
126457    }else{
126458      rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
126459      if( rc==SQLITE_OK ){
126460        sqlite3_int64 iDelta;
126461        pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
126462        if( pTab->bDescIdx ){
126463          pReader->iDocid -= iDelta;
126464        }else{
126465          pReader->iDocid += iDelta;
126466        }
126467      }
126468    }
126469  }
126470
126471  return SQLITE_OK;
126472}
126473
126474
126475SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
126476  Fts3Cursor *pCsr,
126477  Fts3MultiSegReader *pMsr,
126478  int *pnOvfl
126479){
126480  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
126481  int nOvfl = 0;
126482  int ii;
126483  int rc = SQLITE_OK;
126484  int pgsz = p->nPgsz;
126485
126486  assert( p->bHasStat );
126487  assert( pgsz>0 );
126488
126489  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
126490    Fts3SegReader *pReader = pMsr->apSegment[ii];
126491    if( !fts3SegReaderIsPending(pReader)
126492     && !fts3SegReaderIsRootOnly(pReader)
126493    ){
126494      sqlite3_int64 jj;
126495      for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
126496        int nBlob;
126497        rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
126498        if( rc!=SQLITE_OK ) break;
126499        if( (nBlob+35)>pgsz ){
126500          nOvfl += (nBlob + 34)/pgsz;
126501        }
126502      }
126503    }
126504  }
126505  *pnOvfl = nOvfl;
126506  return rc;
126507}
126508
126509/*
126510** Free all allocations associated with the iterator passed as the
126511** second argument.
126512*/
126513SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
126514  if( pReader && !fts3SegReaderIsPending(pReader) ){
126515    sqlite3_free(pReader->zTerm);
126516    if( !fts3SegReaderIsRootOnly(pReader) ){
126517      sqlite3_free(pReader->aNode);
126518      sqlite3_blob_close(pReader->pBlob);
126519    }
126520  }
126521  sqlite3_free(pReader);
126522}
126523
126524/*
126525** Allocate a new SegReader object.
126526*/
126527SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
126528  int iAge,                       /* Segment "age". */
126529  int bLookup,                    /* True for a lookup only */
126530  sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
126531  sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
126532  sqlite3_int64 iEndBlock,        /* Final block of segment */
126533  const char *zRoot,              /* Buffer containing root node */
126534  int nRoot,                      /* Size of buffer containing root node */
126535  Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
126536){
126537  Fts3SegReader *pReader;         /* Newly allocated SegReader object */
126538  int nExtra = 0;                 /* Bytes to allocate segment root node */
126539
126540  assert( iStartLeaf<=iEndLeaf );
126541  if( iStartLeaf==0 ){
126542    nExtra = nRoot + FTS3_NODE_PADDING;
126543  }
126544
126545  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
126546  if( !pReader ){
126547    return SQLITE_NOMEM;
126548  }
126549  memset(pReader, 0, sizeof(Fts3SegReader));
126550  pReader->iIdx = iAge;
126551  pReader->bLookup = bLookup;
126552  pReader->iStartBlock = iStartLeaf;
126553  pReader->iLeafEndBlock = iEndLeaf;
126554  pReader->iEndBlock = iEndBlock;
126555
126556  if( nExtra ){
126557    /* The entire segment is stored in the root node. */
126558    pReader->aNode = (char *)&pReader[1];
126559    pReader->nNode = nRoot;
126560    memcpy(pReader->aNode, zRoot, nRoot);
126561    memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
126562  }else{
126563    pReader->iCurrentBlock = iStartLeaf-1;
126564  }
126565  *ppReader = pReader;
126566  return SQLITE_OK;
126567}
126568
126569/*
126570** This is a comparison function used as a qsort() callback when sorting
126571** an array of pending terms by term. This occurs as part of flushing
126572** the contents of the pending-terms hash table to the database.
126573*/
126574static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
126575  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
126576  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
126577  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
126578  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
126579
126580  int n = (n1<n2 ? n1 : n2);
126581  int c = memcmp(z1, z2, n);
126582  if( c==0 ){
126583    c = n1 - n2;
126584  }
126585  return c;
126586}
126587
126588/*
126589** This function is used to allocate an Fts3SegReader that iterates through
126590** a subset of the terms stored in the Fts3Table.pendingTerms array.
126591**
126592** If the isPrefixIter parameter is zero, then the returned SegReader iterates
126593** through each term in the pending-terms table. Or, if isPrefixIter is
126594** non-zero, it iterates through each term and its prefixes. For example, if
126595** the pending terms hash table contains the terms "sqlite", "mysql" and
126596** "firebird", then the iterator visits the following 'terms' (in the order
126597** shown):
126598**
126599**   f fi fir fire fireb firebi firebir firebird
126600**   m my mys mysq mysql
126601**   s sq sql sqli sqlit sqlite
126602**
126603** Whereas if isPrefixIter is zero, the terms visited are:
126604**
126605**   firebird mysql sqlite
126606*/
126607SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
126608  Fts3Table *p,                   /* Virtual table handle */
126609  int iIndex,                     /* Index for p->aIndex */
126610  const char *zTerm,              /* Term to search for */
126611  int nTerm,                      /* Size of buffer zTerm */
126612  int bPrefix,                    /* True for a prefix iterator */
126613  Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
126614){
126615  Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
126616  Fts3HashElem *pE;               /* Iterator variable */
126617  Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
126618  int nElem = 0;                  /* Size of array at aElem */
126619  int rc = SQLITE_OK;             /* Return Code */
126620  Fts3Hash *pHash;
126621
126622  pHash = &p->aIndex[iIndex].hPending;
126623  if( bPrefix ){
126624    int nAlloc = 0;               /* Size of allocated array at aElem */
126625
126626    for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
126627      char *zKey = (char *)fts3HashKey(pE);
126628      int nKey = fts3HashKeysize(pE);
126629      if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
126630        if( nElem==nAlloc ){
126631          Fts3HashElem **aElem2;
126632          nAlloc += 16;
126633          aElem2 = (Fts3HashElem **)sqlite3_realloc(
126634              aElem, nAlloc*sizeof(Fts3HashElem *)
126635          );
126636          if( !aElem2 ){
126637            rc = SQLITE_NOMEM;
126638            nElem = 0;
126639            break;
126640          }
126641          aElem = aElem2;
126642        }
126643
126644        aElem[nElem++] = pE;
126645      }
126646    }
126647
126648    /* If more than one term matches the prefix, sort the Fts3HashElem
126649    ** objects in term order using qsort(). This uses the same comparison
126650    ** callback as is used when flushing terms to disk.
126651    */
126652    if( nElem>1 ){
126653      qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
126654    }
126655
126656  }else{
126657    /* The query is a simple term lookup that matches at most one term in
126658    ** the index. All that is required is a straight hash-lookup.
126659    **
126660    ** Because the stack address of pE may be accessed via the aElem pointer
126661    ** below, the "Fts3HashElem *pE" must be declared so that it is valid
126662    ** within this entire function, not just this "else{...}" block.
126663    */
126664    pE = fts3HashFindElem(pHash, zTerm, nTerm);
126665    if( pE ){
126666      aElem = &pE;
126667      nElem = 1;
126668    }
126669  }
126670
126671  if( nElem>0 ){
126672    int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
126673    pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
126674    if( !pReader ){
126675      rc = SQLITE_NOMEM;
126676    }else{
126677      memset(pReader, 0, nByte);
126678      pReader->iIdx = 0x7FFFFFFF;
126679      pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
126680      memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
126681    }
126682  }
126683
126684  if( bPrefix ){
126685    sqlite3_free(aElem);
126686  }
126687  *ppReader = pReader;
126688  return rc;
126689}
126690
126691/*
126692** Compare the entries pointed to by two Fts3SegReader structures.
126693** Comparison is as follows:
126694**
126695**   1) EOF is greater than not EOF.
126696**
126697**   2) The current terms (if any) are compared using memcmp(). If one
126698**      term is a prefix of another, the longer term is considered the
126699**      larger.
126700**
126701**   3) By segment age. An older segment is considered larger.
126702*/
126703static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126704  int rc;
126705  if( pLhs->aNode && pRhs->aNode ){
126706    int rc2 = pLhs->nTerm - pRhs->nTerm;
126707    if( rc2<0 ){
126708      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
126709    }else{
126710      rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
126711    }
126712    if( rc==0 ){
126713      rc = rc2;
126714    }
126715  }else{
126716    rc = (pLhs->aNode==0) - (pRhs->aNode==0);
126717  }
126718  if( rc==0 ){
126719    rc = pRhs->iIdx - pLhs->iIdx;
126720  }
126721  assert( rc!=0 );
126722  return rc;
126723}
126724
126725/*
126726** A different comparison function for SegReader structures. In this
126727** version, it is assumed that each SegReader points to an entry in
126728** a doclist for identical terms. Comparison is made as follows:
126729**
126730**   1) EOF (end of doclist in this case) is greater than not EOF.
126731**
126732**   2) By current docid.
126733**
126734**   3) By segment age. An older segment is considered larger.
126735*/
126736static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126737  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
126738  if( rc==0 ){
126739    if( pLhs->iDocid==pRhs->iDocid ){
126740      rc = pRhs->iIdx - pLhs->iIdx;
126741    }else{
126742      rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
126743    }
126744  }
126745  assert( pLhs->aNode && pRhs->aNode );
126746  return rc;
126747}
126748static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
126749  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
126750  if( rc==0 ){
126751    if( pLhs->iDocid==pRhs->iDocid ){
126752      rc = pRhs->iIdx - pLhs->iIdx;
126753    }else{
126754      rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
126755    }
126756  }
126757  assert( pLhs->aNode && pRhs->aNode );
126758  return rc;
126759}
126760
126761/*
126762** Compare the term that the Fts3SegReader object passed as the first argument
126763** points to with the term specified by arguments zTerm and nTerm.
126764**
126765** If the pSeg iterator is already at EOF, return 0. Otherwise, return
126766** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
126767** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
126768*/
126769static int fts3SegReaderTermCmp(
126770  Fts3SegReader *pSeg,            /* Segment reader object */
126771  const char *zTerm,              /* Term to compare to */
126772  int nTerm                       /* Size of term zTerm in bytes */
126773){
126774  int res = 0;
126775  if( pSeg->aNode ){
126776    if( pSeg->nTerm>nTerm ){
126777      res = memcmp(pSeg->zTerm, zTerm, nTerm);
126778    }else{
126779      res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
126780    }
126781    if( res==0 ){
126782      res = pSeg->nTerm-nTerm;
126783    }
126784  }
126785  return res;
126786}
126787
126788/*
126789** Argument apSegment is an array of nSegment elements. It is known that
126790** the final (nSegment-nSuspect) members are already in sorted order
126791** (according to the comparison function provided). This function shuffles
126792** the array around until all entries are in sorted order.
126793*/
126794static void fts3SegReaderSort(
126795  Fts3SegReader **apSegment,                     /* Array to sort entries of */
126796  int nSegment,                                  /* Size of apSegment array */
126797  int nSuspect,                                  /* Unsorted entry count */
126798  int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
126799){
126800  int i;                          /* Iterator variable */
126801
126802  assert( nSuspect<=nSegment );
126803
126804  if( nSuspect==nSegment ) nSuspect--;
126805  for(i=nSuspect-1; i>=0; i--){
126806    int j;
126807    for(j=i; j<(nSegment-1); j++){
126808      Fts3SegReader *pTmp;
126809      if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
126810      pTmp = apSegment[j+1];
126811      apSegment[j+1] = apSegment[j];
126812      apSegment[j] = pTmp;
126813    }
126814  }
126815
126816#ifndef NDEBUG
126817  /* Check that the list really is sorted now. */
126818  for(i=0; i<(nSuspect-1); i++){
126819    assert( xCmp(apSegment[i], apSegment[i+1])<0 );
126820  }
126821#endif
126822}
126823
126824/*
126825** Insert a record into the %_segments table.
126826*/
126827static int fts3WriteSegment(
126828  Fts3Table *p,                   /* Virtual table handle */
126829  sqlite3_int64 iBlock,           /* Block id for new block */
126830  char *z,                        /* Pointer to buffer containing block data */
126831  int n                           /* Size of buffer z in bytes */
126832){
126833  sqlite3_stmt *pStmt;
126834  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
126835  if( rc==SQLITE_OK ){
126836    sqlite3_bind_int64(pStmt, 1, iBlock);
126837    sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
126838    sqlite3_step(pStmt);
126839    rc = sqlite3_reset(pStmt);
126840  }
126841  return rc;
126842}
126843
126844/*
126845** Insert a record into the %_segdir table.
126846*/
126847static int fts3WriteSegdir(
126848  Fts3Table *p,                   /* Virtual table handle */
126849  sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
126850  int iIdx,                       /* Value for "idx" field */
126851  sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
126852  sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
126853  sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
126854  char *zRoot,                    /* Blob value for "root" field */
126855  int nRoot                       /* Number of bytes in buffer zRoot */
126856){
126857  sqlite3_stmt *pStmt;
126858  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
126859  if( rc==SQLITE_OK ){
126860    sqlite3_bind_int64(pStmt, 1, iLevel);
126861    sqlite3_bind_int(pStmt, 2, iIdx);
126862    sqlite3_bind_int64(pStmt, 3, iStartBlock);
126863    sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
126864    sqlite3_bind_int64(pStmt, 5, iEndBlock);
126865    sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
126866    sqlite3_step(pStmt);
126867    rc = sqlite3_reset(pStmt);
126868  }
126869  return rc;
126870}
126871
126872/*
126873** Return the size of the common prefix (if any) shared by zPrev and
126874** zNext, in bytes. For example,
126875**
126876**   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
126877**   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
126878**   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
126879*/
126880static int fts3PrefixCompress(
126881  const char *zPrev,              /* Buffer containing previous term */
126882  int nPrev,                      /* Size of buffer zPrev in bytes */
126883  const char *zNext,              /* Buffer containing next term */
126884  int nNext                       /* Size of buffer zNext in bytes */
126885){
126886  int n;
126887  UNUSED_PARAMETER(nNext);
126888  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
126889  return n;
126890}
126891
126892/*
126893** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
126894** (according to memcmp) than the previous term.
126895*/
126896static int fts3NodeAddTerm(
126897  Fts3Table *p,                   /* Virtual table handle */
126898  SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */
126899  int isCopyTerm,                 /* True if zTerm/nTerm is transient */
126900  const char *zTerm,              /* Pointer to buffer containing term */
126901  int nTerm                       /* Size of term in bytes */
126902){
126903  SegmentNode *pTree = *ppTree;
126904  int rc;
126905  SegmentNode *pNew;
126906
126907  /* First try to append the term to the current node. Return early if
126908  ** this is possible.
126909  */
126910  if( pTree ){
126911    int nData = pTree->nData;     /* Current size of node in bytes */
126912    int nReq = nData;             /* Required space after adding zTerm */
126913    int nPrefix;                  /* Number of bytes of prefix compression */
126914    int nSuffix;                  /* Suffix length */
126915
126916    nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
126917    nSuffix = nTerm-nPrefix;
126918
126919    nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
126920    if( nReq<=p->nNodeSize || !pTree->zTerm ){
126921
126922      if( nReq>p->nNodeSize ){
126923        /* An unusual case: this is the first term to be added to the node
126924        ** and the static node buffer (p->nNodeSize bytes) is not large
126925        ** enough. Use a separately malloced buffer instead This wastes
126926        ** p->nNodeSize bytes, but since this scenario only comes about when
126927        ** the database contain two terms that share a prefix of almost 2KB,
126928        ** this is not expected to be a serious problem.
126929        */
126930        assert( pTree->aData==(char *)&pTree[1] );
126931        pTree->aData = (char *)sqlite3_malloc(nReq);
126932        if( !pTree->aData ){
126933          return SQLITE_NOMEM;
126934        }
126935      }
126936
126937      if( pTree->zTerm ){
126938        /* There is no prefix-length field for first term in a node */
126939        nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
126940      }
126941
126942      nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
126943      memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
126944      pTree->nData = nData + nSuffix;
126945      pTree->nEntry++;
126946
126947      if( isCopyTerm ){
126948        if( pTree->nMalloc<nTerm ){
126949          char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
126950          if( !zNew ){
126951            return SQLITE_NOMEM;
126952          }
126953          pTree->nMalloc = nTerm*2;
126954          pTree->zMalloc = zNew;
126955        }
126956        pTree->zTerm = pTree->zMalloc;
126957        memcpy(pTree->zTerm, zTerm, nTerm);
126958        pTree->nTerm = nTerm;
126959      }else{
126960        pTree->zTerm = (char *)zTerm;
126961        pTree->nTerm = nTerm;
126962      }
126963      return SQLITE_OK;
126964    }
126965  }
126966
126967  /* If control flows to here, it was not possible to append zTerm to the
126968  ** current node. Create a new node (a right-sibling of the current node).
126969  ** If this is the first node in the tree, the term is added to it.
126970  **
126971  ** Otherwise, the term is not added to the new node, it is left empty for
126972  ** now. Instead, the term is inserted into the parent of pTree. If pTree
126973  ** has no parent, one is created here.
126974  */
126975  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
126976  if( !pNew ){
126977    return SQLITE_NOMEM;
126978  }
126979  memset(pNew, 0, sizeof(SegmentNode));
126980  pNew->nData = 1 + FTS3_VARINT_MAX;
126981  pNew->aData = (char *)&pNew[1];
126982
126983  if( pTree ){
126984    SegmentNode *pParent = pTree->pParent;
126985    rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
126986    if( pTree->pParent==0 ){
126987      pTree->pParent = pParent;
126988    }
126989    pTree->pRight = pNew;
126990    pNew->pLeftmost = pTree->pLeftmost;
126991    pNew->pParent = pParent;
126992    pNew->zMalloc = pTree->zMalloc;
126993    pNew->nMalloc = pTree->nMalloc;
126994    pTree->zMalloc = 0;
126995  }else{
126996    pNew->pLeftmost = pNew;
126997    rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
126998  }
126999
127000  *ppTree = pNew;
127001  return rc;
127002}
127003
127004/*
127005** Helper function for fts3NodeWrite().
127006*/
127007static int fts3TreeFinishNode(
127008  SegmentNode *pTree,
127009  int iHeight,
127010  sqlite3_int64 iLeftChild
127011){
127012  int nStart;
127013  assert( iHeight>=1 && iHeight<128 );
127014  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
127015  pTree->aData[nStart] = (char)iHeight;
127016  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
127017  return nStart;
127018}
127019
127020/*
127021** Write the buffer for the segment node pTree and all of its peers to the
127022** database. Then call this function recursively to write the parent of
127023** pTree and its peers to the database.
127024**
127025** Except, if pTree is a root node, do not write it to the database. Instead,
127026** set output variables *paRoot and *pnRoot to contain the root node.
127027**
127028** If successful, SQLITE_OK is returned and output variable *piLast is
127029** set to the largest blockid written to the database (or zero if no
127030** blocks were written to the db). Otherwise, an SQLite error code is
127031** returned.
127032*/
127033static int fts3NodeWrite(
127034  Fts3Table *p,                   /* Virtual table handle */
127035  SegmentNode *pTree,             /* SegmentNode handle */
127036  int iHeight,                    /* Height of this node in tree */
127037  sqlite3_int64 iLeaf,            /* Block id of first leaf node */
127038  sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
127039  sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
127040  char **paRoot,                  /* OUT: Data for root node */
127041  int *pnRoot                     /* OUT: Size of root node in bytes */
127042){
127043  int rc = SQLITE_OK;
127044
127045  if( !pTree->pParent ){
127046    /* Root node of the tree. */
127047    int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
127048    *piLast = iFree-1;
127049    *pnRoot = pTree->nData - nStart;
127050    *paRoot = &pTree->aData[nStart];
127051  }else{
127052    SegmentNode *pIter;
127053    sqlite3_int64 iNextFree = iFree;
127054    sqlite3_int64 iNextLeaf = iLeaf;
127055    for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
127056      int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
127057      int nWrite = pIter->nData - nStart;
127058
127059      rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
127060      iNextFree++;
127061      iNextLeaf += (pIter->nEntry+1);
127062    }
127063    if( rc==SQLITE_OK ){
127064      assert( iNextLeaf==iFree );
127065      rc = fts3NodeWrite(
127066          p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
127067      );
127068    }
127069  }
127070
127071  return rc;
127072}
127073
127074/*
127075** Free all memory allocations associated with the tree pTree.
127076*/
127077static void fts3NodeFree(SegmentNode *pTree){
127078  if( pTree ){
127079    SegmentNode *p = pTree->pLeftmost;
127080    fts3NodeFree(p->pParent);
127081    while( p ){
127082      SegmentNode *pRight = p->pRight;
127083      if( p->aData!=(char *)&p[1] ){
127084        sqlite3_free(p->aData);
127085      }
127086      assert( pRight==0 || p->zMalloc==0 );
127087      sqlite3_free(p->zMalloc);
127088      sqlite3_free(p);
127089      p = pRight;
127090    }
127091  }
127092}
127093
127094/*
127095** Add a term to the segment being constructed by the SegmentWriter object
127096** *ppWriter. When adding the first term to a segment, *ppWriter should
127097** be passed NULL. This function will allocate a new SegmentWriter object
127098** and return it via the input/output variable *ppWriter in this case.
127099**
127100** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
127101*/
127102static int fts3SegWriterAdd(
127103  Fts3Table *p,                   /* Virtual table handle */
127104  SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */
127105  int isCopyTerm,                 /* True if buffer zTerm must be copied */
127106  const char *zTerm,              /* Pointer to buffer containing term */
127107  int nTerm,                      /* Size of term in bytes */
127108  const char *aDoclist,           /* Pointer to buffer containing doclist */
127109  int nDoclist                    /* Size of doclist in bytes */
127110){
127111  int nPrefix;                    /* Size of term prefix in bytes */
127112  int nSuffix;                    /* Size of term suffix in bytes */
127113  int nReq;                       /* Number of bytes required on leaf page */
127114  int nData;
127115  SegmentWriter *pWriter = *ppWriter;
127116
127117  if( !pWriter ){
127118    int rc;
127119    sqlite3_stmt *pStmt;
127120
127121    /* Allocate the SegmentWriter structure */
127122    pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
127123    if( !pWriter ) return SQLITE_NOMEM;
127124    memset(pWriter, 0, sizeof(SegmentWriter));
127125    *ppWriter = pWriter;
127126
127127    /* Allocate a buffer in which to accumulate data */
127128    pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
127129    if( !pWriter->aData ) return SQLITE_NOMEM;
127130    pWriter->nSize = p->nNodeSize;
127131
127132    /* Find the next free blockid in the %_segments table */
127133    rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
127134    if( rc!=SQLITE_OK ) return rc;
127135    if( SQLITE_ROW==sqlite3_step(pStmt) ){
127136      pWriter->iFree = sqlite3_column_int64(pStmt, 0);
127137      pWriter->iFirst = pWriter->iFree;
127138    }
127139    rc = sqlite3_reset(pStmt);
127140    if( rc!=SQLITE_OK ) return rc;
127141  }
127142  nData = pWriter->nData;
127143
127144  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
127145  nSuffix = nTerm-nPrefix;
127146
127147  /* Figure out how many bytes are required by this new entry */
127148  nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
127149    sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
127150    nSuffix +                               /* Term suffix */
127151    sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
127152    nDoclist;                               /* Doclist data */
127153
127154  if( nData>0 && nData+nReq>p->nNodeSize ){
127155    int rc;
127156
127157    /* The current leaf node is full. Write it out to the database. */
127158    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
127159    if( rc!=SQLITE_OK ) return rc;
127160
127161    /* Add the current term to the interior node tree. The term added to
127162    ** the interior tree must:
127163    **
127164    **   a) be greater than the largest term on the leaf node just written
127165    **      to the database (still available in pWriter->zTerm), and
127166    **
127167    **   b) be less than or equal to the term about to be added to the new
127168    **      leaf node (zTerm/nTerm).
127169    **
127170    ** In other words, it must be the prefix of zTerm 1 byte longer than
127171    ** the common prefix (if any) of zTerm and pWriter->zTerm.
127172    */
127173    assert( nPrefix<nTerm );
127174    rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
127175    if( rc!=SQLITE_OK ) return rc;
127176
127177    nData = 0;
127178    pWriter->nTerm = 0;
127179
127180    nPrefix = 0;
127181    nSuffix = nTerm;
127182    nReq = 1 +                              /* varint containing prefix size */
127183      sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
127184      nTerm +                               /* Term suffix */
127185      sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
127186      nDoclist;                             /* Doclist data */
127187  }
127188
127189  /* If the buffer currently allocated is too small for this entry, realloc
127190  ** the buffer to make it large enough.
127191  */
127192  if( nReq>pWriter->nSize ){
127193    char *aNew = sqlite3_realloc(pWriter->aData, nReq);
127194    if( !aNew ) return SQLITE_NOMEM;
127195    pWriter->aData = aNew;
127196    pWriter->nSize = nReq;
127197  }
127198  assert( nData+nReq<=pWriter->nSize );
127199
127200  /* Append the prefix-compressed term and doclist to the buffer. */
127201  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
127202  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
127203  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
127204  nData += nSuffix;
127205  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
127206  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
127207  pWriter->nData = nData + nDoclist;
127208
127209  /* Save the current term so that it can be used to prefix-compress the next.
127210  ** If the isCopyTerm parameter is true, then the buffer pointed to by
127211  ** zTerm is transient, so take a copy of the term data. Otherwise, just
127212  ** store a copy of the pointer.
127213  */
127214  if( isCopyTerm ){
127215    if( nTerm>pWriter->nMalloc ){
127216      char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
127217      if( !zNew ){
127218        return SQLITE_NOMEM;
127219      }
127220      pWriter->nMalloc = nTerm*2;
127221      pWriter->zMalloc = zNew;
127222      pWriter->zTerm = zNew;
127223    }
127224    assert( pWriter->zTerm==pWriter->zMalloc );
127225    memcpy(pWriter->zTerm, zTerm, nTerm);
127226  }else{
127227    pWriter->zTerm = (char *)zTerm;
127228  }
127229  pWriter->nTerm = nTerm;
127230
127231  return SQLITE_OK;
127232}
127233
127234/*
127235** Flush all data associated with the SegmentWriter object pWriter to the
127236** database. This function must be called after all terms have been added
127237** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
127238** returned. Otherwise, an SQLite error code.
127239*/
127240static int fts3SegWriterFlush(
127241  Fts3Table *p,                   /* Virtual table handle */
127242  SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
127243  sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
127244  int iIdx                        /* Value for 'idx' column of %_segdir */
127245){
127246  int rc;                         /* Return code */
127247  if( pWriter->pTree ){
127248    sqlite3_int64 iLast = 0;      /* Largest block id written to database */
127249    sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
127250    char *zRoot = NULL;           /* Pointer to buffer containing root node */
127251    int nRoot = 0;                /* Size of buffer zRoot */
127252
127253    iLastLeaf = pWriter->iFree;
127254    rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
127255    if( rc==SQLITE_OK ){
127256      rc = fts3NodeWrite(p, pWriter->pTree, 1,
127257          pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
127258    }
127259    if( rc==SQLITE_OK ){
127260      rc = fts3WriteSegdir(
127261          p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
127262    }
127263  }else{
127264    /* The entire tree fits on the root node. Write it to the segdir table. */
127265    rc = fts3WriteSegdir(
127266        p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
127267  }
127268  return rc;
127269}
127270
127271/*
127272** Release all memory held by the SegmentWriter object passed as the
127273** first argument.
127274*/
127275static void fts3SegWriterFree(SegmentWriter *pWriter){
127276  if( pWriter ){
127277    sqlite3_free(pWriter->aData);
127278    sqlite3_free(pWriter->zMalloc);
127279    fts3NodeFree(pWriter->pTree);
127280    sqlite3_free(pWriter);
127281  }
127282}
127283
127284/*
127285** The first value in the apVal[] array is assumed to contain an integer.
127286** This function tests if there exist any documents with docid values that
127287** are different from that integer. i.e. if deleting the document with docid
127288** pRowid would mean the FTS3 table were empty.
127289**
127290** If successful, *pisEmpty is set to true if the table is empty except for
127291** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
127292** error occurs, an SQLite error code is returned.
127293*/
127294static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
127295  sqlite3_stmt *pStmt;
127296  int rc;
127297  if( p->zContentTbl ){
127298    /* If using the content=xxx option, assume the table is never empty */
127299    *pisEmpty = 0;
127300    rc = SQLITE_OK;
127301  }else{
127302    rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
127303    if( rc==SQLITE_OK ){
127304      if( SQLITE_ROW==sqlite3_step(pStmt) ){
127305        *pisEmpty = sqlite3_column_int(pStmt, 0);
127306      }
127307      rc = sqlite3_reset(pStmt);
127308    }
127309  }
127310  return rc;
127311}
127312
127313/*
127314** Set *pnMax to the largest segment level in the database for the index
127315** iIndex.
127316**
127317** Segment levels are stored in the 'level' column of the %_segdir table.
127318**
127319** Return SQLITE_OK if successful, or an SQLite error code if not.
127320*/
127321static int fts3SegmentMaxLevel(
127322  Fts3Table *p,
127323  int iLangid,
127324  int iIndex,
127325  sqlite3_int64 *pnMax
127326){
127327  sqlite3_stmt *pStmt;
127328  int rc;
127329  assert( iIndex>=0 && iIndex<p->nIndex );
127330
127331  /* Set pStmt to the compiled version of:
127332  **
127333  **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
127334  **
127335  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
127336  */
127337  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
127338  if( rc!=SQLITE_OK ) return rc;
127339  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
127340  sqlite3_bind_int64(pStmt, 2,
127341      getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
127342  );
127343  if( SQLITE_ROW==sqlite3_step(pStmt) ){
127344    *pnMax = sqlite3_column_int64(pStmt, 0);
127345  }
127346  return sqlite3_reset(pStmt);
127347}
127348
127349/*
127350** This function is used after merging multiple segments into a single large
127351** segment to delete the old, now redundant, segment b-trees. Specifically,
127352** it:
127353**
127354**   1) Deletes all %_segments entries for the segments associated with
127355**      each of the SegReader objects in the array passed as the third
127356**      argument, and
127357**
127358**   2) deletes all %_segdir entries with level iLevel, or all %_segdir
127359**      entries regardless of level if (iLevel<0).
127360**
127361** SQLITE_OK is returned if successful, otherwise an SQLite error code.
127362*/
127363static int fts3DeleteSegdir(
127364  Fts3Table *p,                   /* Virtual table handle */
127365  int iLangid,                    /* Language id */
127366  int iIndex,                     /* Index for p->aIndex */
127367  int iLevel,                     /* Level of %_segdir entries to delete */
127368  Fts3SegReader **apSegment,      /* Array of SegReader objects */
127369  int nReader                     /* Size of array apSegment */
127370){
127371  int rc;                         /* Return Code */
127372  int i;                          /* Iterator variable */
127373  sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
127374
127375  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
127376  for(i=0; rc==SQLITE_OK && i<nReader; i++){
127377    Fts3SegReader *pSegment = apSegment[i];
127378    if( pSegment->iStartBlock ){
127379      sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
127380      sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
127381      sqlite3_step(pDelete);
127382      rc = sqlite3_reset(pDelete);
127383    }
127384  }
127385  if( rc!=SQLITE_OK ){
127386    return rc;
127387  }
127388
127389  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
127390  if( iLevel==FTS3_SEGCURSOR_ALL ){
127391    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
127392    if( rc==SQLITE_OK ){
127393      sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
127394      sqlite3_bind_int64(pDelete, 2,
127395          getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
127396      );
127397    }
127398  }else{
127399    rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
127400    if( rc==SQLITE_OK ){
127401      sqlite3_bind_int64(
127402          pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
127403      );
127404    }
127405  }
127406
127407  if( rc==SQLITE_OK ){
127408    sqlite3_step(pDelete);
127409    rc = sqlite3_reset(pDelete);
127410  }
127411
127412  return rc;
127413}
127414
127415/*
127416** When this function is called, buffer *ppList (size *pnList bytes) contains
127417** a position list that may (or may not) feature multiple columns. This
127418** function adjusts the pointer *ppList and the length *pnList so that they
127419** identify the subset of the position list that corresponds to column iCol.
127420**
127421** If there are no entries in the input position list for column iCol, then
127422** *pnList is set to zero before returning.
127423*/
127424static void fts3ColumnFilter(
127425  int iCol,                       /* Column to filter on */
127426  char **ppList,                  /* IN/OUT: Pointer to position list */
127427  int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
127428){
127429  char *pList = *ppList;
127430  int nList = *pnList;
127431  char *pEnd = &pList[nList];
127432  int iCurrent = 0;
127433  char *p = pList;
127434
127435  assert( iCol>=0 );
127436  while( 1 ){
127437    char c = 0;
127438    while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
127439
127440    if( iCol==iCurrent ){
127441      nList = (int)(p - pList);
127442      break;
127443    }
127444
127445    nList -= (int)(p - pList);
127446    pList = p;
127447    if( nList==0 ){
127448      break;
127449    }
127450    p = &pList[1];
127451    p += sqlite3Fts3GetVarint32(p, &iCurrent);
127452  }
127453
127454  *ppList = pList;
127455  *pnList = nList;
127456}
127457
127458/*
127459** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
127460** existing data). Grow the buffer if required.
127461**
127462** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
127463** trying to resize the buffer, return SQLITE_NOMEM.
127464*/
127465static int fts3MsrBufferData(
127466  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
127467  char *pList,
127468  int nList
127469){
127470  if( nList>pMsr->nBuffer ){
127471    char *pNew;
127472    pMsr->nBuffer = nList*2;
127473    pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
127474    if( !pNew ) return SQLITE_NOMEM;
127475    pMsr->aBuffer = pNew;
127476  }
127477
127478  memcpy(pMsr->aBuffer, pList, nList);
127479  return SQLITE_OK;
127480}
127481
127482SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
127483  Fts3Table *p,                   /* Virtual table handle */
127484  Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
127485  sqlite3_int64 *piDocid,         /* OUT: Docid value */
127486  char **paPoslist,               /* OUT: Pointer to position list */
127487  int *pnPoslist                  /* OUT: Size of position list in bytes */
127488){
127489  int nMerge = pMsr->nAdvance;
127490  Fts3SegReader **apSegment = pMsr->apSegment;
127491  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
127492    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
127493  );
127494
127495  if( nMerge==0 ){
127496    *paPoslist = 0;
127497    return SQLITE_OK;
127498  }
127499
127500  while( 1 ){
127501    Fts3SegReader *pSeg;
127502    pSeg = pMsr->apSegment[0];
127503
127504    if( pSeg->pOffsetList==0 ){
127505      *paPoslist = 0;
127506      break;
127507    }else{
127508      int rc;
127509      char *pList;
127510      int nList;
127511      int j;
127512      sqlite3_int64 iDocid = apSegment[0]->iDocid;
127513
127514      rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
127515      j = 1;
127516      while( rc==SQLITE_OK
127517        && j<nMerge
127518        && apSegment[j]->pOffsetList
127519        && apSegment[j]->iDocid==iDocid
127520      ){
127521        rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
127522        j++;
127523      }
127524      if( rc!=SQLITE_OK ) return rc;
127525      fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
127526
127527      if( pMsr->iColFilter>=0 ){
127528        fts3ColumnFilter(pMsr->iColFilter, &pList, &nList);
127529      }
127530
127531      if( nList>0 ){
127532        if( fts3SegReaderIsPending(apSegment[0]) ){
127533          rc = fts3MsrBufferData(pMsr, pList, nList+1);
127534          if( rc!=SQLITE_OK ) return rc;
127535          *paPoslist = pMsr->aBuffer;
127536          assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
127537        }else{
127538          *paPoslist = pList;
127539        }
127540        *piDocid = iDocid;
127541        *pnPoslist = nList;
127542        break;
127543      }
127544    }
127545  }
127546
127547  return SQLITE_OK;
127548}
127549
127550static int fts3SegReaderStart(
127551  Fts3Table *p,                   /* Virtual table handle */
127552  Fts3MultiSegReader *pCsr,       /* Cursor object */
127553  const char *zTerm,              /* Term searched for (or NULL) */
127554  int nTerm                       /* Length of zTerm in bytes */
127555){
127556  int i;
127557  int nSeg = pCsr->nSegment;
127558
127559  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
127560  ** for, then advance each segment iterator until it points to a term of
127561  ** equal or greater value than the specified term. This prevents many
127562  ** unnecessary merge/sort operations for the case where single segment
127563  ** b-tree leaf nodes contain more than one term.
127564  */
127565  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
127566    int res = 0;
127567    Fts3SegReader *pSeg = pCsr->apSegment[i];
127568    do {
127569      int rc = fts3SegReaderNext(p, pSeg, 0);
127570      if( rc!=SQLITE_OK ) return rc;
127571    }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
127572
127573    if( pSeg->bLookup && res!=0 ){
127574      fts3SegReaderSetEof(pSeg);
127575    }
127576  }
127577  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
127578
127579  return SQLITE_OK;
127580}
127581
127582SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
127583  Fts3Table *p,                   /* Virtual table handle */
127584  Fts3MultiSegReader *pCsr,       /* Cursor object */
127585  Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
127586){
127587  pCsr->pFilter = pFilter;
127588  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
127589}
127590
127591SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
127592  Fts3Table *p,                   /* Virtual table handle */
127593  Fts3MultiSegReader *pCsr,       /* Cursor object */
127594  int iCol,                       /* Column to match on. */
127595  const char *zTerm,              /* Term to iterate through a doclist for */
127596  int nTerm                       /* Number of bytes in zTerm */
127597){
127598  int i;
127599  int rc;
127600  int nSegment = pCsr->nSegment;
127601  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
127602    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
127603  );
127604
127605  assert( pCsr->pFilter==0 );
127606  assert( zTerm && nTerm>0 );
127607
127608  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
127609  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
127610  if( rc!=SQLITE_OK ) return rc;
127611
127612  /* Determine how many of the segments actually point to zTerm/nTerm. */
127613  for(i=0; i<nSegment; i++){
127614    Fts3SegReader *pSeg = pCsr->apSegment[i];
127615    if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
127616      break;
127617    }
127618  }
127619  pCsr->nAdvance = i;
127620
127621  /* Advance each of the segments to point to the first docid. */
127622  for(i=0; i<pCsr->nAdvance; i++){
127623    rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
127624    if( rc!=SQLITE_OK ) return rc;
127625  }
127626  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
127627
127628  assert( iCol<0 || iCol<p->nColumn );
127629  pCsr->iColFilter = iCol;
127630
127631  return SQLITE_OK;
127632}
127633
127634/*
127635** This function is called on a MultiSegReader that has been started using
127636** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
127637** have been made. Calling this function puts the MultiSegReader in such
127638** a state that if the next two calls are:
127639**
127640**   sqlite3Fts3SegReaderStart()
127641**   sqlite3Fts3SegReaderStep()
127642**
127643** then the entire doclist for the term is available in
127644** MultiSegReader.aDoclist/nDoclist.
127645*/
127646SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
127647  int i;                          /* Used to iterate through segment-readers */
127648
127649  assert( pCsr->zTerm==0 );
127650  assert( pCsr->nTerm==0 );
127651  assert( pCsr->aDoclist==0 );
127652  assert( pCsr->nDoclist==0 );
127653
127654  pCsr->nAdvance = 0;
127655  pCsr->bRestart = 1;
127656  for(i=0; i<pCsr->nSegment; i++){
127657    pCsr->apSegment[i]->pOffsetList = 0;
127658    pCsr->apSegment[i]->nOffsetList = 0;
127659    pCsr->apSegment[i]->iDocid = 0;
127660  }
127661
127662  return SQLITE_OK;
127663}
127664
127665
127666SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
127667  Fts3Table *p,                   /* Virtual table handle */
127668  Fts3MultiSegReader *pCsr        /* Cursor object */
127669){
127670  int rc = SQLITE_OK;
127671
127672  int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
127673  int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
127674  int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
127675  int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
127676  int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
127677  int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
127678
127679  Fts3SegReader **apSegment = pCsr->apSegment;
127680  int nSegment = pCsr->nSegment;
127681  Fts3SegFilter *pFilter = pCsr->pFilter;
127682  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
127683    p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
127684  );
127685
127686  if( pCsr->nSegment==0 ) return SQLITE_OK;
127687
127688  do {
127689    int nMerge;
127690    int i;
127691
127692    /* Advance the first pCsr->nAdvance entries in the apSegment[] array
127693    ** forward. Then sort the list in order of current term again.
127694    */
127695    for(i=0; i<pCsr->nAdvance; i++){
127696      Fts3SegReader *pSeg = apSegment[i];
127697      if( pSeg->bLookup ){
127698        fts3SegReaderSetEof(pSeg);
127699      }else{
127700        rc = fts3SegReaderNext(p, pSeg, 0);
127701      }
127702      if( rc!=SQLITE_OK ) return rc;
127703    }
127704    fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
127705    pCsr->nAdvance = 0;
127706
127707    /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
127708    assert( rc==SQLITE_OK );
127709    if( apSegment[0]->aNode==0 ) break;
127710
127711    pCsr->nTerm = apSegment[0]->nTerm;
127712    pCsr->zTerm = apSegment[0]->zTerm;
127713
127714    /* If this is a prefix-search, and if the term that apSegment[0] points
127715    ** to does not share a suffix with pFilter->zTerm/nTerm, then all
127716    ** required callbacks have been made. In this case exit early.
127717    **
127718    ** Similarly, if this is a search for an exact match, and the first term
127719    ** of segment apSegment[0] is not a match, exit early.
127720    */
127721    if( pFilter->zTerm && !isScan ){
127722      if( pCsr->nTerm<pFilter->nTerm
127723       || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
127724       || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
127725      ){
127726        break;
127727      }
127728    }
127729
127730    nMerge = 1;
127731    while( nMerge<nSegment
127732        && apSegment[nMerge]->aNode
127733        && apSegment[nMerge]->nTerm==pCsr->nTerm
127734        && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
127735    ){
127736      nMerge++;
127737    }
127738
127739    assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
127740    if( nMerge==1
127741     && !isIgnoreEmpty
127742     && !isFirst
127743     && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
127744    ){
127745      pCsr->nDoclist = apSegment[0]->nDoclist;
127746      if( fts3SegReaderIsPending(apSegment[0]) ){
127747        rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
127748        pCsr->aDoclist = pCsr->aBuffer;
127749      }else{
127750        pCsr->aDoclist = apSegment[0]->aDoclist;
127751      }
127752      if( rc==SQLITE_OK ) rc = SQLITE_ROW;
127753    }else{
127754      int nDoclist = 0;           /* Size of doclist */
127755      sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
127756
127757      /* The current term of the first nMerge entries in the array
127758      ** of Fts3SegReader objects is the same. The doclists must be merged
127759      ** and a single term returned with the merged doclist.
127760      */
127761      for(i=0; i<nMerge; i++){
127762        fts3SegReaderFirstDocid(p, apSegment[i]);
127763      }
127764      fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
127765      while( apSegment[0]->pOffsetList ){
127766        int j;                    /* Number of segments that share a docid */
127767        char *pList;
127768        int nList;
127769        int nByte;
127770        sqlite3_int64 iDocid = apSegment[0]->iDocid;
127771        fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
127772        j = 1;
127773        while( j<nMerge
127774            && apSegment[j]->pOffsetList
127775            && apSegment[j]->iDocid==iDocid
127776        ){
127777          fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
127778          j++;
127779        }
127780
127781        if( isColFilter ){
127782          fts3ColumnFilter(pFilter->iCol, &pList, &nList);
127783        }
127784
127785        if( !isIgnoreEmpty || nList>0 ){
127786
127787          /* Calculate the 'docid' delta value to write into the merged
127788          ** doclist. */
127789          sqlite3_int64 iDelta;
127790          if( p->bDescIdx && nDoclist>0 ){
127791            iDelta = iPrev - iDocid;
127792          }else{
127793            iDelta = iDocid - iPrev;
127794          }
127795          assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
127796          assert( nDoclist>0 || iDelta==iDocid );
127797
127798          nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
127799          if( nDoclist+nByte>pCsr->nBuffer ){
127800            char *aNew;
127801            pCsr->nBuffer = (nDoclist+nByte)*2;
127802            aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
127803            if( !aNew ){
127804              return SQLITE_NOMEM;
127805            }
127806            pCsr->aBuffer = aNew;
127807          }
127808
127809          if( isFirst ){
127810            char *a = &pCsr->aBuffer[nDoclist];
127811            int nWrite;
127812
127813            nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
127814            if( nWrite ){
127815              iPrev = iDocid;
127816              nDoclist += nWrite;
127817            }
127818          }else{
127819            nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
127820            iPrev = iDocid;
127821            if( isRequirePos ){
127822              memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
127823              nDoclist += nList;
127824              pCsr->aBuffer[nDoclist++] = '\0';
127825            }
127826          }
127827        }
127828
127829        fts3SegReaderSort(apSegment, nMerge, j, xCmp);
127830      }
127831      if( nDoclist>0 ){
127832        pCsr->aDoclist = pCsr->aBuffer;
127833        pCsr->nDoclist = nDoclist;
127834        rc = SQLITE_ROW;
127835      }
127836    }
127837    pCsr->nAdvance = nMerge;
127838  }while( rc==SQLITE_OK );
127839
127840  return rc;
127841}
127842
127843
127844SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
127845  Fts3MultiSegReader *pCsr       /* Cursor object */
127846){
127847  if( pCsr ){
127848    int i;
127849    for(i=0; i<pCsr->nSegment; i++){
127850      sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
127851    }
127852    sqlite3_free(pCsr->apSegment);
127853    sqlite3_free(pCsr->aBuffer);
127854
127855    pCsr->nSegment = 0;
127856    pCsr->apSegment = 0;
127857    pCsr->aBuffer = 0;
127858  }
127859}
127860
127861/*
127862** Merge all level iLevel segments in the database into a single
127863** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
127864** single segment with a level equal to the numerically largest level
127865** currently present in the database.
127866**
127867** If this function is called with iLevel<0, but there is only one
127868** segment in the database, SQLITE_DONE is returned immediately.
127869** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
127870** an SQLite error code is returned.
127871*/
127872static int fts3SegmentMerge(
127873  Fts3Table *p,
127874  int iLangid,                    /* Language id to merge */
127875  int iIndex,                     /* Index in p->aIndex[] to merge */
127876  int iLevel                      /* Level to merge */
127877){
127878  int rc;                         /* Return code */
127879  int iIdx = 0;                   /* Index of new segment */
127880  sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
127881  SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
127882  Fts3SegFilter filter;           /* Segment term filter condition */
127883  Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
127884  int bIgnoreEmpty = 0;           /* True to ignore empty segments */
127885
127886  assert( iLevel==FTS3_SEGCURSOR_ALL
127887       || iLevel==FTS3_SEGCURSOR_PENDING
127888       || iLevel>=0
127889  );
127890  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
127891  assert( iIndex>=0 && iIndex<p->nIndex );
127892
127893  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
127894  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
127895
127896  if( iLevel==FTS3_SEGCURSOR_ALL ){
127897    /* This call is to merge all segments in the database to a single
127898    ** segment. The level of the new segment is equal to the the numerically
127899    ** greatest segment level currently present in the database for this
127900    ** index. The idx of the new segment is always 0.  */
127901    if( csr.nSegment==1 ){
127902      rc = SQLITE_DONE;
127903      goto finished;
127904    }
127905    rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
127906    bIgnoreEmpty = 1;
127907
127908  }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
127909    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
127910    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
127911  }else{
127912    /* This call is to merge all segments at level iLevel. find the next
127913    ** available segment index at level iLevel+1. The call to
127914    ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
127915    ** a single iLevel+2 segment if necessary.  */
127916    rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
127917    iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
127918  }
127919  if( rc!=SQLITE_OK ) goto finished;
127920  assert( csr.nSegment>0 );
127921  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
127922  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
127923
127924  memset(&filter, 0, sizeof(Fts3SegFilter));
127925  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
127926  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
127927
127928  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
127929  while( SQLITE_OK==rc ){
127930    rc = sqlite3Fts3SegReaderStep(p, &csr);
127931    if( rc!=SQLITE_ROW ) break;
127932    rc = fts3SegWriterAdd(p, &pWriter, 1,
127933        csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
127934  }
127935  if( rc!=SQLITE_OK ) goto finished;
127936  assert( pWriter );
127937
127938  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
127939    rc = fts3DeleteSegdir(
127940        p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
127941    );
127942    if( rc!=SQLITE_OK ) goto finished;
127943  }
127944  rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
127945
127946 finished:
127947  fts3SegWriterFree(pWriter);
127948  sqlite3Fts3SegReaderFinish(&csr);
127949  return rc;
127950}
127951
127952
127953/*
127954** Flush the contents of pendingTerms to level 0 segments.
127955*/
127956SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
127957  int rc = SQLITE_OK;
127958  int i;
127959  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
127960    rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
127961    if( rc==SQLITE_DONE ) rc = SQLITE_OK;
127962  }
127963  sqlite3Fts3PendingTermsClear(p);
127964  return rc;
127965}
127966
127967/*
127968** Encode N integers as varints into a blob.
127969*/
127970static void fts3EncodeIntArray(
127971  int N,             /* The number of integers to encode */
127972  u32 *a,            /* The integer values */
127973  char *zBuf,        /* Write the BLOB here */
127974  int *pNBuf         /* Write number of bytes if zBuf[] used here */
127975){
127976  int i, j;
127977  for(i=j=0; i<N; i++){
127978    j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
127979  }
127980  *pNBuf = j;
127981}
127982
127983/*
127984** Decode a blob of varints into N integers
127985*/
127986static void fts3DecodeIntArray(
127987  int N,             /* The number of integers to decode */
127988  u32 *a,            /* Write the integer values */
127989  const char *zBuf,  /* The BLOB containing the varints */
127990  int nBuf           /* size of the BLOB */
127991){
127992  int i, j;
127993  UNUSED_PARAMETER(nBuf);
127994  for(i=j=0; i<N; i++){
127995    sqlite3_int64 x;
127996    j += sqlite3Fts3GetVarint(&zBuf[j], &x);
127997    assert(j<=nBuf);
127998    a[i] = (u32)(x & 0xffffffff);
127999  }
128000}
128001
128002/*
128003** Insert the sizes (in tokens) for each column of the document
128004** with docid equal to p->iPrevDocid.  The sizes are encoded as
128005** a blob of varints.
128006*/
128007static void fts3InsertDocsize(
128008  int *pRC,                       /* Result code */
128009  Fts3Table *p,                   /* Table into which to insert */
128010  u32 *aSz                        /* Sizes of each column, in tokens */
128011){
128012  char *pBlob;             /* The BLOB encoding of the document size */
128013  int nBlob;               /* Number of bytes in the BLOB */
128014  sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
128015  int rc;                  /* Result code from subfunctions */
128016
128017  if( *pRC ) return;
128018  pBlob = sqlite3_malloc( 10*p->nColumn );
128019  if( pBlob==0 ){
128020    *pRC = SQLITE_NOMEM;
128021    return;
128022  }
128023  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
128024  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
128025  if( rc ){
128026    sqlite3_free(pBlob);
128027    *pRC = rc;
128028    return;
128029  }
128030  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
128031  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
128032  sqlite3_step(pStmt);
128033  *pRC = sqlite3_reset(pStmt);
128034}
128035
128036/*
128037** Record 0 of the %_stat table contains a blob consisting of N varints,
128038** where N is the number of user defined columns in the fts3 table plus
128039** two. If nCol is the number of user defined columns, then values of the
128040** varints are set as follows:
128041**
128042**   Varint 0:       Total number of rows in the table.
128043**
128044**   Varint 1..nCol: For each column, the total number of tokens stored in
128045**                   the column for all rows of the table.
128046**
128047**   Varint 1+nCol:  The total size, in bytes, of all text values in all
128048**                   columns of all rows of the table.
128049**
128050*/
128051static void fts3UpdateDocTotals(
128052  int *pRC,                       /* The result code */
128053  Fts3Table *p,                   /* Table being updated */
128054  u32 *aSzIns,                    /* Size increases */
128055  u32 *aSzDel,                    /* Size decreases */
128056  int nChng                       /* Change in the number of documents */
128057){
128058  char *pBlob;             /* Storage for BLOB written into %_stat */
128059  int nBlob;               /* Size of BLOB written into %_stat */
128060  u32 *a;                  /* Array of integers that becomes the BLOB */
128061  sqlite3_stmt *pStmt;     /* Statement for reading and writing */
128062  int i;                   /* Loop counter */
128063  int rc;                  /* Result code from subfunctions */
128064
128065  const int nStat = p->nColumn+2;
128066
128067  if( *pRC ) return;
128068  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
128069  if( a==0 ){
128070    *pRC = SQLITE_NOMEM;
128071    return;
128072  }
128073  pBlob = (char*)&a[nStat];
128074  rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
128075  if( rc ){
128076    sqlite3_free(a);
128077    *pRC = rc;
128078    return;
128079  }
128080  if( sqlite3_step(pStmt)==SQLITE_ROW ){
128081    fts3DecodeIntArray(nStat, a,
128082         sqlite3_column_blob(pStmt, 0),
128083         sqlite3_column_bytes(pStmt, 0));
128084  }else{
128085    memset(a, 0, sizeof(u32)*(nStat) );
128086  }
128087  sqlite3_reset(pStmt);
128088  if( nChng<0 && a[0]<(u32)(-nChng) ){
128089    a[0] = 0;
128090  }else{
128091    a[0] += nChng;
128092  }
128093  for(i=0; i<p->nColumn+1; i++){
128094    u32 x = a[i+1];
128095    if( x+aSzIns[i] < aSzDel[i] ){
128096      x = 0;
128097    }else{
128098      x = x + aSzIns[i] - aSzDel[i];
128099    }
128100    a[i+1] = x;
128101  }
128102  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
128103  rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
128104  if( rc ){
128105    sqlite3_free(a);
128106    *pRC = rc;
128107    return;
128108  }
128109  sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
128110  sqlite3_step(pStmt);
128111  *pRC = sqlite3_reset(pStmt);
128112  sqlite3_free(a);
128113}
128114
128115/*
128116** Merge the entire database so that there is one segment for each
128117** iIndex/iLangid combination.
128118*/
128119static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
128120  int bSeenDone = 0;
128121  int rc;
128122  sqlite3_stmt *pAllLangid = 0;
128123
128124  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
128125  if( rc==SQLITE_OK ){
128126    int rc2;
128127    sqlite3_bind_int(pAllLangid, 1, p->nIndex);
128128    while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
128129      int i;
128130      int iLangid = sqlite3_column_int(pAllLangid, 0);
128131      for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
128132        rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
128133        if( rc==SQLITE_DONE ){
128134          bSeenDone = 1;
128135          rc = SQLITE_OK;
128136        }
128137      }
128138    }
128139    rc2 = sqlite3_reset(pAllLangid);
128140    if( rc==SQLITE_OK ) rc = rc2;
128141  }
128142
128143  sqlite3Fts3SegmentsClose(p);
128144  sqlite3Fts3PendingTermsClear(p);
128145
128146  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
128147}
128148
128149/*
128150** This function is called when the user executes the following statement:
128151**
128152**     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
128153**
128154** The entire FTS index is discarded and rebuilt. If the table is one
128155** created using the content=xxx option, then the new index is based on
128156** the current contents of the xxx table. Otherwise, it is rebuilt based
128157** on the contents of the %_content table.
128158*/
128159static int fts3DoRebuild(Fts3Table *p){
128160  int rc;                         /* Return Code */
128161
128162  rc = fts3DeleteAll(p, 0);
128163  if( rc==SQLITE_OK ){
128164    u32 *aSz = 0;
128165    u32 *aSzIns = 0;
128166    u32 *aSzDel = 0;
128167    sqlite3_stmt *pStmt = 0;
128168    int nEntry = 0;
128169
128170    /* Compose and prepare an SQL statement to loop through the content table */
128171    char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
128172    if( !zSql ){
128173      rc = SQLITE_NOMEM;
128174    }else{
128175      rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
128176      sqlite3_free(zSql);
128177    }
128178
128179    if( rc==SQLITE_OK ){
128180      int nByte = sizeof(u32) * (p->nColumn+1)*3;
128181      aSz = (u32 *)sqlite3_malloc(nByte);
128182      if( aSz==0 ){
128183        rc = SQLITE_NOMEM;
128184      }else{
128185        memset(aSz, 0, nByte);
128186        aSzIns = &aSz[p->nColumn+1];
128187        aSzDel = &aSzIns[p->nColumn+1];
128188      }
128189    }
128190
128191    while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
128192      int iCol;
128193      int iLangid = langidFromSelect(p, pStmt);
128194      rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
128195      aSz[p->nColumn] = 0;
128196      for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
128197        const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
128198        rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
128199        aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
128200      }
128201      if( p->bHasDocsize ){
128202        fts3InsertDocsize(&rc, p, aSz);
128203      }
128204      if( rc!=SQLITE_OK ){
128205        sqlite3_finalize(pStmt);
128206        pStmt = 0;
128207      }else{
128208        nEntry++;
128209        for(iCol=0; iCol<=p->nColumn; iCol++){
128210          aSzIns[iCol] += aSz[iCol];
128211        }
128212      }
128213    }
128214    if( p->bHasStat ){
128215      fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
128216    }
128217    sqlite3_free(aSz);
128218
128219    if( pStmt ){
128220      int rc2 = sqlite3_finalize(pStmt);
128221      if( rc==SQLITE_OK ){
128222        rc = rc2;
128223      }
128224    }
128225  }
128226
128227  return rc;
128228}
128229
128230/*
128231** Handle a 'special' INSERT of the form:
128232**
128233**   "INSERT INTO tbl(tbl) VALUES(<expr>)"
128234**
128235** Argument pVal contains the result of <expr>. Currently the only
128236** meaningful value to insert is the text 'optimize'.
128237*/
128238static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
128239  int rc;                         /* Return Code */
128240  const char *zVal = (const char *)sqlite3_value_text(pVal);
128241  int nVal = sqlite3_value_bytes(pVal);
128242
128243  if( !zVal ){
128244    return SQLITE_NOMEM;
128245  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
128246    rc = fts3DoOptimize(p, 0);
128247  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
128248    rc = fts3DoRebuild(p);
128249#ifdef SQLITE_TEST
128250  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
128251    p->nNodeSize = atoi(&zVal[9]);
128252    rc = SQLITE_OK;
128253  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
128254    p->nMaxPendingData = atoi(&zVal[11]);
128255    rc = SQLITE_OK;
128256#endif
128257  }else{
128258    rc = SQLITE_ERROR;
128259  }
128260
128261  return rc;
128262}
128263
128264/*
128265** Delete all cached deferred doclists. Deferred doclists are cached
128266** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
128267*/
128268SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
128269  Fts3DeferredToken *pDef;
128270  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
128271    fts3PendingListDelete(pDef->pList);
128272    pDef->pList = 0;
128273  }
128274}
128275
128276/*
128277** Free all entries in the pCsr->pDeffered list. Entries are added to
128278** this list using sqlite3Fts3DeferToken().
128279*/
128280SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
128281  Fts3DeferredToken *pDef;
128282  Fts3DeferredToken *pNext;
128283  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
128284    pNext = pDef->pNext;
128285    fts3PendingListDelete(pDef->pList);
128286    sqlite3_free(pDef);
128287  }
128288  pCsr->pDeferred = 0;
128289}
128290
128291/*
128292** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
128293** based on the row that pCsr currently points to.
128294**
128295** A deferred-doclist is like any other doclist with position information
128296** included, except that it only contains entries for a single row of the
128297** table, not for all rows.
128298*/
128299SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
128300  int rc = SQLITE_OK;             /* Return code */
128301  if( pCsr->pDeferred ){
128302    int i;                        /* Used to iterate through table columns */
128303    sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
128304    Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
128305
128306    Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
128307    sqlite3_tokenizer *pT = p->pTokenizer;
128308    sqlite3_tokenizer_module const *pModule = pT->pModule;
128309
128310    assert( pCsr->isRequireSeek==0 );
128311    iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
128312
128313    for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
128314      const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
128315      sqlite3_tokenizer_cursor *pTC = 0;
128316
128317      rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
128318      while( rc==SQLITE_OK ){
128319        char const *zToken;       /* Buffer containing token */
128320        int nToken;               /* Number of bytes in token */
128321        int iDum1, iDum2;         /* Dummy variables */
128322        int iPos;                 /* Position of token in zText */
128323
128324        rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
128325        for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
128326          Fts3PhraseToken *pPT = pDef->pToken;
128327          if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
128328           && (pPT->bFirst==0 || iPos==0)
128329           && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
128330           && (0==memcmp(zToken, pPT->z, pPT->n))
128331          ){
128332            fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
128333          }
128334        }
128335      }
128336      if( pTC ) pModule->xClose(pTC);
128337      if( rc==SQLITE_DONE ) rc = SQLITE_OK;
128338    }
128339
128340    for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
128341      if( pDef->pList ){
128342        rc = fts3PendingListAppendVarint(&pDef->pList, 0);
128343      }
128344    }
128345  }
128346
128347  return rc;
128348}
128349
128350SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
128351  Fts3DeferredToken *p,
128352  char **ppData,
128353  int *pnData
128354){
128355  char *pRet;
128356  int nSkip;
128357  sqlite3_int64 dummy;
128358
128359  *ppData = 0;
128360  *pnData = 0;
128361
128362  if( p->pList==0 ){
128363    return SQLITE_OK;
128364  }
128365
128366  pRet = (char *)sqlite3_malloc(p->pList->nData);
128367  if( !pRet ) return SQLITE_NOMEM;
128368
128369  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
128370  *pnData = p->pList->nData - nSkip;
128371  *ppData = pRet;
128372
128373  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
128374  return SQLITE_OK;
128375}
128376
128377/*
128378** Add an entry for token pToken to the pCsr->pDeferred list.
128379*/
128380SQLITE_PRIVATE int sqlite3Fts3DeferToken(
128381  Fts3Cursor *pCsr,               /* Fts3 table cursor */
128382  Fts3PhraseToken *pToken,        /* Token to defer */
128383  int iCol                        /* Column that token must appear in (or -1) */
128384){
128385  Fts3DeferredToken *pDeferred;
128386  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
128387  if( !pDeferred ){
128388    return SQLITE_NOMEM;
128389  }
128390  memset(pDeferred, 0, sizeof(*pDeferred));
128391  pDeferred->pToken = pToken;
128392  pDeferred->pNext = pCsr->pDeferred;
128393  pDeferred->iCol = iCol;
128394  pCsr->pDeferred = pDeferred;
128395
128396  assert( pToken->pDeferred==0 );
128397  pToken->pDeferred = pDeferred;
128398
128399  return SQLITE_OK;
128400}
128401
128402/*
128403** SQLite value pRowid contains the rowid of a row that may or may not be
128404** present in the FTS3 table. If it is, delete it and adjust the contents
128405** of subsiduary data structures accordingly.
128406*/
128407static int fts3DeleteByRowid(
128408  Fts3Table *p,
128409  sqlite3_value *pRowid,
128410  int *pnDoc,
128411  u32 *aSzDel
128412){
128413  int isEmpty = 0;
128414  int rc = fts3IsEmpty(p, pRowid, &isEmpty);
128415  if( rc==SQLITE_OK ){
128416    if( isEmpty ){
128417      /* Deleting this row means the whole table is empty. In this case
128418      ** delete the contents of all three tables and throw away any
128419      ** data in the pendingTerms hash table.  */
128420      rc = fts3DeleteAll(p, 1);
128421      *pnDoc = *pnDoc - 1;
128422    }else{
128423      fts3DeleteTerms(&rc, p, pRowid, aSzDel);
128424      if( p->zContentTbl==0 ){
128425        fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
128426        if( sqlite3_changes(p->db) ) *pnDoc = *pnDoc - 1;
128427      }else{
128428        *pnDoc = *pnDoc - 1;
128429      }
128430      if( p->bHasDocsize ){
128431        fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
128432      }
128433    }
128434  }
128435
128436  return rc;
128437}
128438
128439/*
128440** This function does the work for the xUpdate method of FTS3 virtual
128441** tables. The schema of the virtual table being:
128442**
128443**     CREATE TABLE <table name>(
128444**       <user COLUMns>,
128445**       <table name> HIDDEN,
128446**       docid HIDDEN,
128447**       <langid> HIDDEN
128448**     );
128449**
128450**
128451*/
128452SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
128453  sqlite3_vtab *pVtab,            /* FTS3 vtab object */
128454  int nArg,                       /* Size of argument array */
128455  sqlite3_value **apVal,          /* Array of arguments */
128456  sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
128457){
128458  Fts3Table *p = (Fts3Table *)pVtab;
128459  int rc = SQLITE_OK;             /* Return Code */
128460  int isRemove = 0;               /* True for an UPDATE or DELETE */
128461  u32 *aSzIns = 0;                /* Sizes of inserted documents */
128462  u32 *aSzDel;                    /* Sizes of deleted documents */
128463  int nChng = 0;                  /* Net change in number of documents */
128464  int bInsertDone = 0;
128465
128466  assert( p->pSegments==0 );
128467  assert(
128468      nArg==1                     /* DELETE operations */
128469   || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
128470  );
128471
128472  /* Check for a "special" INSERT operation. One of the form:
128473  **
128474  **   INSERT INTO xyz(xyz) VALUES('command');
128475  */
128476  if( nArg>1
128477   && sqlite3_value_type(apVal[0])==SQLITE_NULL
128478   && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
128479  ){
128480    rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
128481    goto update_out;
128482  }
128483
128484  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
128485    rc = SQLITE_CONSTRAINT;
128486    goto update_out;
128487  }
128488
128489  /* Allocate space to hold the change in document sizes */
128490  aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*(p->nColumn+1)*2 );
128491  if( aSzIns==0 ){
128492    rc = SQLITE_NOMEM;
128493    goto update_out;
128494  }
128495  aSzDel = &aSzIns[p->nColumn+1];
128496  memset(aSzIns, 0, sizeof(aSzIns[0])*(p->nColumn+1)*2);
128497
128498  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
128499  ** value, then this operation requires constraint handling.
128500  **
128501  ** If the on-conflict mode is REPLACE, this means that the existing row
128502  ** should be deleted from the database before inserting the new row. Or,
128503  ** if the on-conflict mode is other than REPLACE, then this method must
128504  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
128505  ** modify the database file.
128506  */
128507  if( nArg>1 && p->zContentTbl==0 ){
128508    /* Find the value object that holds the new rowid value. */
128509    sqlite3_value *pNewRowid = apVal[3+p->nColumn];
128510    if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
128511      pNewRowid = apVal[1];
128512    }
128513
128514    if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
128515        sqlite3_value_type(apVal[0])==SQLITE_NULL
128516     || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
128517    )){
128518      /* The new rowid is not NULL (in this case the rowid will be
128519      ** automatically assigned and there is no chance of a conflict), and
128520      ** the statement is either an INSERT or an UPDATE that modifies the
128521      ** rowid column. So if the conflict mode is REPLACE, then delete any
128522      ** existing row with rowid=pNewRowid.
128523      **
128524      ** Or, if the conflict mode is not REPLACE, insert the new record into
128525      ** the %_content table. If we hit the duplicate rowid constraint (or any
128526      ** other error) while doing so, return immediately.
128527      **
128528      ** This branch may also run if pNewRowid contains a value that cannot
128529      ** be losslessly converted to an integer. In this case, the eventual
128530      ** call to fts3InsertData() (either just below or further on in this
128531      ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
128532      ** invoked, it will delete zero rows (since no row will have
128533      ** docid=$pNewRowid if $pNewRowid is not an integer value).
128534      */
128535      if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
128536        rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
128537      }else{
128538        rc = fts3InsertData(p, apVal, pRowid);
128539        bInsertDone = 1;
128540      }
128541    }
128542  }
128543  if( rc!=SQLITE_OK ){
128544    goto update_out;
128545  }
128546
128547  /* If this is a DELETE or UPDATE operation, remove the old record. */
128548  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
128549    assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
128550    rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
128551    isRemove = 1;
128552  }
128553
128554  /* If this is an INSERT or UPDATE operation, insert the new record. */
128555  if( nArg>1 && rc==SQLITE_OK ){
128556    int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
128557    if( bInsertDone==0 ){
128558      rc = fts3InsertData(p, apVal, pRowid);
128559      if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
128560        rc = FTS_CORRUPT_VTAB;
128561      }
128562    }
128563    if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
128564      rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
128565    }
128566    if( rc==SQLITE_OK ){
128567      assert( p->iPrevDocid==*pRowid );
128568      rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
128569    }
128570    if( p->bHasDocsize ){
128571      fts3InsertDocsize(&rc, p, aSzIns);
128572    }
128573    nChng++;
128574  }
128575
128576  if( p->bHasStat ){
128577    fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
128578  }
128579
128580 update_out:
128581  sqlite3_free(aSzIns);
128582  sqlite3Fts3SegmentsClose(p);
128583  return rc;
128584}
128585
128586/*
128587** Flush any data in the pending-terms hash table to disk. If successful,
128588** merge all segments in the database (including the new segment, if
128589** there was any data to flush) into a single segment.
128590*/
128591SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
128592  int rc;
128593  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
128594  if( rc==SQLITE_OK ){
128595    rc = fts3DoOptimize(p, 1);
128596    if( rc==SQLITE_OK || rc==SQLITE_DONE ){
128597      int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
128598      if( rc2!=SQLITE_OK ) rc = rc2;
128599    }else{
128600      sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
128601      sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
128602    }
128603  }
128604  sqlite3Fts3SegmentsClose(p);
128605  return rc;
128606}
128607
128608#endif
128609
128610/************** End of fts3_write.c ******************************************/
128611/************** Begin file fts3_snippet.c ************************************/
128612/*
128613** 2009 Oct 23
128614**
128615** The author disclaims copyright to this source code.  In place of
128616** a legal notice, here is a blessing:
128617**
128618**    May you do good and not evil.
128619**    May you find forgiveness for yourself and forgive others.
128620**    May you share freely, never taking more than you give.
128621**
128622******************************************************************************
128623*/
128624
128625#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128626
128627/* #include <string.h> */
128628/* #include <assert.h> */
128629
128630/*
128631** Characters that may appear in the second argument to matchinfo().
128632*/
128633#define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
128634#define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
128635#define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
128636#define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
128637#define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
128638#define FTS3_MATCHINFO_LCS       's'        /* nCol values */
128639#define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
128640
128641/*
128642** The default value for the second argument to matchinfo().
128643*/
128644#define FTS3_MATCHINFO_DEFAULT   "pcx"
128645
128646
128647/*
128648** Used as an fts3ExprIterate() context when loading phrase doclists to
128649** Fts3Expr.aDoclist[]/nDoclist.
128650*/
128651typedef struct LoadDoclistCtx LoadDoclistCtx;
128652struct LoadDoclistCtx {
128653  Fts3Cursor *pCsr;               /* FTS3 Cursor */
128654  int nPhrase;                    /* Number of phrases seen so far */
128655  int nToken;                     /* Number of tokens seen so far */
128656};
128657
128658/*
128659** The following types are used as part of the implementation of the
128660** fts3BestSnippet() routine.
128661*/
128662typedef struct SnippetIter SnippetIter;
128663typedef struct SnippetPhrase SnippetPhrase;
128664typedef struct SnippetFragment SnippetFragment;
128665
128666struct SnippetIter {
128667  Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
128668  int iCol;                       /* Extract snippet from this column */
128669  int nSnippet;                   /* Requested snippet length (in tokens) */
128670  int nPhrase;                    /* Number of phrases in query */
128671  SnippetPhrase *aPhrase;         /* Array of size nPhrase */
128672  int iCurrent;                   /* First token of current snippet */
128673};
128674
128675struct SnippetPhrase {
128676  int nToken;                     /* Number of tokens in phrase */
128677  char *pList;                    /* Pointer to start of phrase position list */
128678  int iHead;                      /* Next value in position list */
128679  char *pHead;                    /* Position list data following iHead */
128680  int iTail;                      /* Next value in trailing position list */
128681  char *pTail;                    /* Position list data following iTail */
128682};
128683
128684struct SnippetFragment {
128685  int iCol;                       /* Column snippet is extracted from */
128686  int iPos;                       /* Index of first token in snippet */
128687  u64 covered;                    /* Mask of query phrases covered */
128688  u64 hlmask;                     /* Mask of snippet terms to highlight */
128689};
128690
128691/*
128692** This type is used as an fts3ExprIterate() context object while
128693** accumulating the data returned by the matchinfo() function.
128694*/
128695typedef struct MatchInfo MatchInfo;
128696struct MatchInfo {
128697  Fts3Cursor *pCursor;            /* FTS3 Cursor */
128698  int nCol;                       /* Number of columns in table */
128699  int nPhrase;                    /* Number of matchable phrases in query */
128700  sqlite3_int64 nDoc;             /* Number of docs in database */
128701  u32 *aMatchinfo;                /* Pre-allocated buffer */
128702};
128703
128704
128705
128706/*
128707** The snippet() and offsets() functions both return text values. An instance
128708** of the following structure is used to accumulate those values while the
128709** functions are running. See fts3StringAppend() for details.
128710*/
128711typedef struct StrBuffer StrBuffer;
128712struct StrBuffer {
128713  char *z;                        /* Pointer to buffer containing string */
128714  int n;                          /* Length of z in bytes (excl. nul-term) */
128715  int nAlloc;                     /* Allocated size of buffer z in bytes */
128716};
128717
128718
128719/*
128720** This function is used to help iterate through a position-list. A position
128721** list is a list of unique integers, sorted from smallest to largest. Each
128722** element of the list is represented by an FTS3 varint that takes the value
128723** of the difference between the current element and the previous one plus
128724** two. For example, to store the position-list:
128725**
128726**     4 9 113
128727**
128728** the three varints:
128729**
128730**     6 7 106
128731**
128732** are encoded.
128733**
128734** When this function is called, *pp points to the start of an element of
128735** the list. *piPos contains the value of the previous entry in the list.
128736** After it returns, *piPos contains the value of the next element of the
128737** list and *pp is advanced to the following varint.
128738*/
128739static void fts3GetDeltaPosition(char **pp, int *piPos){
128740  int iVal;
128741  *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
128742  *piPos += (iVal-2);
128743}
128744
128745/*
128746** Helper function for fts3ExprIterate() (see below).
128747*/
128748static int fts3ExprIterate2(
128749  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
128750  int *piPhrase,                  /* Pointer to phrase counter */
128751  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
128752  void *pCtx                      /* Second argument to pass to callback */
128753){
128754  int rc;                         /* Return code */
128755  int eType = pExpr->eType;       /* Type of expression node pExpr */
128756
128757  if( eType!=FTSQUERY_PHRASE ){
128758    assert( pExpr->pLeft && pExpr->pRight );
128759    rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
128760    if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
128761      rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
128762    }
128763  }else{
128764    rc = x(pExpr, *piPhrase, pCtx);
128765    (*piPhrase)++;
128766  }
128767  return rc;
128768}
128769
128770/*
128771** Iterate through all phrase nodes in an FTS3 query, except those that
128772** are part of a sub-tree that is the right-hand-side of a NOT operator.
128773** For each phrase node found, the supplied callback function is invoked.
128774**
128775** If the callback function returns anything other than SQLITE_OK,
128776** the iteration is abandoned and the error code returned immediately.
128777** Otherwise, SQLITE_OK is returned after a callback has been made for
128778** all eligible phrase nodes.
128779*/
128780static int fts3ExprIterate(
128781  Fts3Expr *pExpr,                /* Expression to iterate phrases of */
128782  int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
128783  void *pCtx                      /* Second argument to pass to callback */
128784){
128785  int iPhrase = 0;                /* Variable used as the phrase counter */
128786  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
128787}
128788
128789/*
128790** This is an fts3ExprIterate() callback used while loading the doclists
128791** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
128792** fts3ExprLoadDoclists().
128793*/
128794static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
128795  int rc = SQLITE_OK;
128796  Fts3Phrase *pPhrase = pExpr->pPhrase;
128797  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
128798
128799  UNUSED_PARAMETER(iPhrase);
128800
128801  p->nPhrase++;
128802  p->nToken += pPhrase->nToken;
128803
128804  return rc;
128805}
128806
128807/*
128808** Load the doclists for each phrase in the query associated with FTS3 cursor
128809** pCsr.
128810**
128811** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
128812** phrases in the expression (all phrases except those directly or
128813** indirectly descended from the right-hand-side of a NOT operator). If
128814** pnToken is not NULL, then it is set to the number of tokens in all
128815** matchable phrases of the expression.
128816*/
128817static int fts3ExprLoadDoclists(
128818  Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
128819  int *pnPhrase,                  /* OUT: Number of phrases in query */
128820  int *pnToken                    /* OUT: Number of tokens in query */
128821){
128822  int rc;                         /* Return Code */
128823  LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
128824  sCtx.pCsr = pCsr;
128825  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
128826  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
128827  if( pnToken ) *pnToken = sCtx.nToken;
128828  return rc;
128829}
128830
128831static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
128832  (*(int *)ctx)++;
128833  UNUSED_PARAMETER(pExpr);
128834  UNUSED_PARAMETER(iPhrase);
128835  return SQLITE_OK;
128836}
128837static int fts3ExprPhraseCount(Fts3Expr *pExpr){
128838  int nPhrase = 0;
128839  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
128840  return nPhrase;
128841}
128842
128843/*
128844** Advance the position list iterator specified by the first two
128845** arguments so that it points to the first element with a value greater
128846** than or equal to parameter iNext.
128847*/
128848static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
128849  char *pIter = *ppIter;
128850  if( pIter ){
128851    int iIter = *piIter;
128852
128853    while( iIter<iNext ){
128854      if( 0==(*pIter & 0xFE) ){
128855        iIter = -1;
128856        pIter = 0;
128857        break;
128858      }
128859      fts3GetDeltaPosition(&pIter, &iIter);
128860    }
128861
128862    *piIter = iIter;
128863    *ppIter = pIter;
128864  }
128865}
128866
128867/*
128868** Advance the snippet iterator to the next candidate snippet.
128869*/
128870static int fts3SnippetNextCandidate(SnippetIter *pIter){
128871  int i;                          /* Loop counter */
128872
128873  if( pIter->iCurrent<0 ){
128874    /* The SnippetIter object has just been initialized. The first snippet
128875    ** candidate always starts at offset 0 (even if this candidate has a
128876    ** score of 0.0).
128877    */
128878    pIter->iCurrent = 0;
128879
128880    /* Advance the 'head' iterator of each phrase to the first offset that
128881    ** is greater than or equal to (iNext+nSnippet).
128882    */
128883    for(i=0; i<pIter->nPhrase; i++){
128884      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128885      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
128886    }
128887  }else{
128888    int iStart;
128889    int iEnd = 0x7FFFFFFF;
128890
128891    for(i=0; i<pIter->nPhrase; i++){
128892      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128893      if( pPhrase->pHead && pPhrase->iHead<iEnd ){
128894        iEnd = pPhrase->iHead;
128895      }
128896    }
128897    if( iEnd==0x7FFFFFFF ){
128898      return 1;
128899    }
128900
128901    pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
128902    for(i=0; i<pIter->nPhrase; i++){
128903      SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128904      fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
128905      fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
128906    }
128907  }
128908
128909  return 0;
128910}
128911
128912/*
128913** Retrieve information about the current candidate snippet of snippet
128914** iterator pIter.
128915*/
128916static void fts3SnippetDetails(
128917  SnippetIter *pIter,             /* Snippet iterator */
128918  u64 mCovered,                   /* Bitmask of phrases already covered */
128919  int *piToken,                   /* OUT: First token of proposed snippet */
128920  int *piScore,                   /* OUT: "Score" for this snippet */
128921  u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
128922  u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
128923){
128924  int iStart = pIter->iCurrent;   /* First token of snippet */
128925  int iScore = 0;                 /* Score of this snippet */
128926  int i;                          /* Loop counter */
128927  u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
128928  u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
128929
128930  for(i=0; i<pIter->nPhrase; i++){
128931    SnippetPhrase *pPhrase = &pIter->aPhrase[i];
128932    if( pPhrase->pTail ){
128933      char *pCsr = pPhrase->pTail;
128934      int iCsr = pPhrase->iTail;
128935
128936      while( iCsr<(iStart+pIter->nSnippet) ){
128937        int j;
128938        u64 mPhrase = (u64)1 << i;
128939        u64 mPos = (u64)1 << (iCsr - iStart);
128940        assert( iCsr>=iStart );
128941        if( (mCover|mCovered)&mPhrase ){
128942          iScore++;
128943        }else{
128944          iScore += 1000;
128945        }
128946        mCover |= mPhrase;
128947
128948        for(j=0; j<pPhrase->nToken; j++){
128949          mHighlight |= (mPos>>j);
128950        }
128951
128952        if( 0==(*pCsr & 0x0FE) ) break;
128953        fts3GetDeltaPosition(&pCsr, &iCsr);
128954      }
128955    }
128956  }
128957
128958  /* Set the output variables before returning. */
128959  *piToken = iStart;
128960  *piScore = iScore;
128961  *pmCover = mCover;
128962  *pmHighlight = mHighlight;
128963}
128964
128965/*
128966** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
128967** Each invocation populates an element of the SnippetIter.aPhrase[] array.
128968*/
128969static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
128970  SnippetIter *p = (SnippetIter *)ctx;
128971  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
128972  char *pCsr;
128973
128974  pPhrase->nToken = pExpr->pPhrase->nToken;
128975
128976  pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
128977  if( pCsr ){
128978    int iFirst = 0;
128979    pPhrase->pList = pCsr;
128980    fts3GetDeltaPosition(&pCsr, &iFirst);
128981    assert( iFirst>=0 );
128982    pPhrase->pHead = pCsr;
128983    pPhrase->pTail = pCsr;
128984    pPhrase->iHead = iFirst;
128985    pPhrase->iTail = iFirst;
128986  }else{
128987    assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
128988  }
128989
128990  return SQLITE_OK;
128991}
128992
128993/*
128994** Select the fragment of text consisting of nFragment contiguous tokens
128995** from column iCol that represent the "best" snippet. The best snippet
128996** is the snippet with the highest score, where scores are calculated
128997** by adding:
128998**
128999**   (a) +1 point for each occurence of a matchable phrase in the snippet.
129000**
129001**   (b) +1000 points for the first occurence of each matchable phrase in
129002**       the snippet for which the corresponding mCovered bit is not set.
129003**
129004** The selected snippet parameters are stored in structure *pFragment before
129005** returning. The score of the selected snippet is stored in *piScore
129006** before returning.
129007*/
129008static int fts3BestSnippet(
129009  int nSnippet,                   /* Desired snippet length */
129010  Fts3Cursor *pCsr,               /* Cursor to create snippet for */
129011  int iCol,                       /* Index of column to create snippet from */
129012  u64 mCovered,                   /* Mask of phrases already covered */
129013  u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
129014  SnippetFragment *pFragment,     /* OUT: Best snippet found */
129015  int *piScore                    /* OUT: Score of snippet pFragment */
129016){
129017  int rc;                         /* Return Code */
129018  int nList;                      /* Number of phrases in expression */
129019  SnippetIter sIter;              /* Iterates through snippet candidates */
129020  int nByte;                      /* Number of bytes of space to allocate */
129021  int iBestScore = -1;            /* Best snippet score found so far */
129022  int i;                          /* Loop counter */
129023
129024  memset(&sIter, 0, sizeof(sIter));
129025
129026  /* Iterate through the phrases in the expression to count them. The same
129027  ** callback makes sure the doclists are loaded for each phrase.
129028  */
129029  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
129030  if( rc!=SQLITE_OK ){
129031    return rc;
129032  }
129033
129034  /* Now that it is known how many phrases there are, allocate and zero
129035  ** the required space using malloc().
129036  */
129037  nByte = sizeof(SnippetPhrase) * nList;
129038  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
129039  if( !sIter.aPhrase ){
129040    return SQLITE_NOMEM;
129041  }
129042  memset(sIter.aPhrase, 0, nByte);
129043
129044  /* Initialize the contents of the SnippetIter object. Then iterate through
129045  ** the set of phrases in the expression to populate the aPhrase[] array.
129046  */
129047  sIter.pCsr = pCsr;
129048  sIter.iCol = iCol;
129049  sIter.nSnippet = nSnippet;
129050  sIter.nPhrase = nList;
129051  sIter.iCurrent = -1;
129052  (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
129053
129054  /* Set the *pmSeen output variable. */
129055  for(i=0; i<nList; i++){
129056    if( sIter.aPhrase[i].pHead ){
129057      *pmSeen |= (u64)1 << i;
129058    }
129059  }
129060
129061  /* Loop through all candidate snippets. Store the best snippet in
129062  ** *pFragment. Store its associated 'score' in iBestScore.
129063  */
129064  pFragment->iCol = iCol;
129065  while( !fts3SnippetNextCandidate(&sIter) ){
129066    int iPos;
129067    int iScore;
129068    u64 mCover;
129069    u64 mHighlight;
129070    fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
129071    assert( iScore>=0 );
129072    if( iScore>iBestScore ){
129073      pFragment->iPos = iPos;
129074      pFragment->hlmask = mHighlight;
129075      pFragment->covered = mCover;
129076      iBestScore = iScore;
129077    }
129078  }
129079
129080  sqlite3_free(sIter.aPhrase);
129081  *piScore = iBestScore;
129082  return SQLITE_OK;
129083}
129084
129085
129086/*
129087** Append a string to the string-buffer passed as the first argument.
129088**
129089** If nAppend is negative, then the length of the string zAppend is
129090** determined using strlen().
129091*/
129092static int fts3StringAppend(
129093  StrBuffer *pStr,                /* Buffer to append to */
129094  const char *zAppend,            /* Pointer to data to append to buffer */
129095  int nAppend                     /* Size of zAppend in bytes (or -1) */
129096){
129097  if( nAppend<0 ){
129098    nAppend = (int)strlen(zAppend);
129099  }
129100
129101  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
129102  ** to grow the buffer until so that it is big enough to accomadate the
129103  ** appended data.
129104  */
129105  if( pStr->n+nAppend+1>=pStr->nAlloc ){
129106    int nAlloc = pStr->nAlloc+nAppend+100;
129107    char *zNew = sqlite3_realloc(pStr->z, nAlloc);
129108    if( !zNew ){
129109      return SQLITE_NOMEM;
129110    }
129111    pStr->z = zNew;
129112    pStr->nAlloc = nAlloc;
129113  }
129114
129115  /* Append the data to the string buffer. */
129116  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
129117  pStr->n += nAppend;
129118  pStr->z[pStr->n] = '\0';
129119
129120  return SQLITE_OK;
129121}
129122
129123/*
129124** The fts3BestSnippet() function often selects snippets that end with a
129125** query term. That is, the final term of the snippet is always a term
129126** that requires highlighting. For example, if 'X' is a highlighted term
129127** and '.' is a non-highlighted term, BestSnippet() may select:
129128**
129129**     ........X.....X
129130**
129131** This function "shifts" the beginning of the snippet forward in the
129132** document so that there are approximately the same number of
129133** non-highlighted terms to the right of the final highlighted term as there
129134** are to the left of the first highlighted term. For example, to this:
129135**
129136**     ....X.....X....
129137**
129138** This is done as part of extracting the snippet text, not when selecting
129139** the snippet. Snippet selection is done based on doclists only, so there
129140** is no way for fts3BestSnippet() to know whether or not the document
129141** actually contains terms that follow the final highlighted term.
129142*/
129143static int fts3SnippetShift(
129144  Fts3Table *pTab,                /* FTS3 table snippet comes from */
129145  int iLangid,                    /* Language id to use in tokenizing */
129146  int nSnippet,                   /* Number of tokens desired for snippet */
129147  const char *zDoc,               /* Document text to extract snippet from */
129148  int nDoc,                       /* Size of buffer zDoc in bytes */
129149  int *piPos,                     /* IN/OUT: First token of snippet */
129150  u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
129151){
129152  u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
129153
129154  if( hlmask ){
129155    int nLeft;                    /* Tokens to the left of first highlight */
129156    int nRight;                   /* Tokens to the right of last highlight */
129157    int nDesired;                 /* Ideal number of tokens to shift forward */
129158
129159    for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
129160    for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
129161    nDesired = (nLeft-nRight)/2;
129162
129163    /* Ideally, the start of the snippet should be pushed forward in the
129164    ** document nDesired tokens. This block checks if there are actually
129165    ** nDesired tokens to the right of the snippet. If so, *piPos and
129166    ** *pHlMask are updated to shift the snippet nDesired tokens to the
129167    ** right. Otherwise, the snippet is shifted by the number of tokens
129168    ** available.
129169    */
129170    if( nDesired>0 ){
129171      int nShift;                 /* Number of tokens to shift snippet by */
129172      int iCurrent = 0;           /* Token counter */
129173      int rc;                     /* Return Code */
129174      sqlite3_tokenizer_module *pMod;
129175      sqlite3_tokenizer_cursor *pC;
129176      pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
129177
129178      /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
129179      ** or more tokens in zDoc/nDoc.
129180      */
129181      rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
129182      if( rc!=SQLITE_OK ){
129183        return rc;
129184      }
129185      while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
129186        const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
129187        rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
129188      }
129189      pMod->xClose(pC);
129190      if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
129191
129192      nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
129193      assert( nShift<=nDesired );
129194      if( nShift>0 ){
129195        *piPos += nShift;
129196        *pHlmask = hlmask >> nShift;
129197      }
129198    }
129199  }
129200  return SQLITE_OK;
129201}
129202
129203/*
129204** Extract the snippet text for fragment pFragment from cursor pCsr and
129205** append it to string buffer pOut.
129206*/
129207static int fts3SnippetText(
129208  Fts3Cursor *pCsr,               /* FTS3 Cursor */
129209  SnippetFragment *pFragment,     /* Snippet to extract */
129210  int iFragment,                  /* Fragment number */
129211  int isLast,                     /* True for final fragment in snippet */
129212  int nSnippet,                   /* Number of tokens in extracted snippet */
129213  const char *zOpen,              /* String inserted before highlighted term */
129214  const char *zClose,             /* String inserted after highlighted term */
129215  const char *zEllipsis,          /* String inserted between snippets */
129216  StrBuffer *pOut                 /* Write output here */
129217){
129218  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129219  int rc;                         /* Return code */
129220  const char *zDoc;               /* Document text to extract snippet from */
129221  int nDoc;                       /* Size of zDoc in bytes */
129222  int iCurrent = 0;               /* Current token number of document */
129223  int iEnd = 0;                   /* Byte offset of end of current token */
129224  int isShiftDone = 0;            /* True after snippet is shifted */
129225  int iPos = pFragment->iPos;     /* First token of snippet */
129226  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
129227  int iCol = pFragment->iCol+1;   /* Query column to extract text from */
129228  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
129229  sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
129230  const char *ZDUMMY;             /* Dummy argument used with tokenizer */
129231  int DUMMY1;                     /* Dummy argument used with tokenizer */
129232
129233  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
129234  if( zDoc==0 ){
129235    if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
129236      return SQLITE_NOMEM;
129237    }
129238    return SQLITE_OK;
129239  }
129240  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
129241
129242  /* Open a token cursor on the document. */
129243  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
129244  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
129245  if( rc!=SQLITE_OK ){
129246    return rc;
129247  }
129248
129249  while( rc==SQLITE_OK ){
129250    int iBegin;                   /* Offset in zDoc of start of token */
129251    int iFin;                     /* Offset in zDoc of end of token */
129252    int isHighlight;              /* True for highlighted terms */
129253
129254    rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
129255    if( rc!=SQLITE_OK ){
129256      if( rc==SQLITE_DONE ){
129257        /* Special case - the last token of the snippet is also the last token
129258        ** of the column. Append any punctuation that occurred between the end
129259        ** of the previous token and the end of the document to the output.
129260        ** Then break out of the loop. */
129261        rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
129262      }
129263      break;
129264    }
129265    if( iCurrent<iPos ){ continue; }
129266
129267    if( !isShiftDone ){
129268      int n = nDoc - iBegin;
129269      rc = fts3SnippetShift(
129270          pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
129271      );
129272      isShiftDone = 1;
129273
129274      /* Now that the shift has been done, check if the initial "..." are
129275      ** required. They are required if (a) this is not the first fragment,
129276      ** or (b) this fragment does not begin at position 0 of its column.
129277      */
129278      if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
129279        rc = fts3StringAppend(pOut, zEllipsis, -1);
129280      }
129281      if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
129282    }
129283
129284    if( iCurrent>=(iPos+nSnippet) ){
129285      if( isLast ){
129286        rc = fts3StringAppend(pOut, zEllipsis, -1);
129287      }
129288      break;
129289    }
129290
129291    /* Set isHighlight to true if this term should be highlighted. */
129292    isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
129293
129294    if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
129295    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
129296    if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
129297    if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
129298
129299    iEnd = iFin;
129300  }
129301
129302  pMod->xClose(pC);
129303  return rc;
129304}
129305
129306
129307/*
129308** This function is used to count the entries in a column-list (a
129309** delta-encoded list of term offsets within a single column of a single
129310** row). When this function is called, *ppCollist should point to the
129311** beginning of the first varint in the column-list (the varint that
129312** contains the position of the first matching term in the column data).
129313** Before returning, *ppCollist is set to point to the first byte after
129314** the last varint in the column-list (either the 0x00 signifying the end
129315** of the position-list, or the 0x01 that precedes the column number of
129316** the next column in the position-list).
129317**
129318** The number of elements in the column-list is returned.
129319*/
129320static int fts3ColumnlistCount(char **ppCollist){
129321  char *pEnd = *ppCollist;
129322  char c = 0;
129323  int nEntry = 0;
129324
129325  /* A column-list is terminated by either a 0x01 or 0x00. */
129326  while( 0xFE & (*pEnd | c) ){
129327    c = *pEnd++ & 0x80;
129328    if( !c ) nEntry++;
129329  }
129330
129331  *ppCollist = pEnd;
129332  return nEntry;
129333}
129334
129335/*
129336** fts3ExprIterate() callback used to collect the "global" matchinfo stats
129337** for a single query.
129338**
129339** fts3ExprIterate() callback to load the 'global' elements of a
129340** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
129341** of the matchinfo array that are constant for all rows returned by the
129342** current query.
129343**
129344** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
129345** function populates Matchinfo.aMatchinfo[] as follows:
129346**
129347**   for(iCol=0; iCol<nCol; iCol++){
129348**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
129349**     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
129350**   }
129351**
129352** where X is the number of matches for phrase iPhrase is column iCol of all
129353** rows of the table. Y is the number of rows for which column iCol contains
129354** at least one instance of phrase iPhrase.
129355**
129356** If the phrase pExpr consists entirely of deferred tokens, then all X and
129357** Y values are set to nDoc, where nDoc is the number of documents in the
129358** file system. This is done because the full-text index doclist is required
129359** to calculate these values properly, and the full-text index doclist is
129360** not available for deferred tokens.
129361*/
129362static int fts3ExprGlobalHitsCb(
129363  Fts3Expr *pExpr,                /* Phrase expression node */
129364  int iPhrase,                    /* Phrase number (numbered from zero) */
129365  void *pCtx                      /* Pointer to MatchInfo structure */
129366){
129367  MatchInfo *p = (MatchInfo *)pCtx;
129368  return sqlite3Fts3EvalPhraseStats(
129369      p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
129370  );
129371}
129372
129373/*
129374** fts3ExprIterate() callback used to collect the "local" part of the
129375** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
129376** array that are different for each row returned by the query.
129377*/
129378static int fts3ExprLocalHitsCb(
129379  Fts3Expr *pExpr,                /* Phrase expression node */
129380  int iPhrase,                    /* Phrase number */
129381  void *pCtx                      /* Pointer to MatchInfo structure */
129382){
129383  MatchInfo *p = (MatchInfo *)pCtx;
129384  int iStart = iPhrase * p->nCol * 3;
129385  int i;
129386
129387  for(i=0; i<p->nCol; i++){
129388    char *pCsr;
129389    pCsr = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i);
129390    if( pCsr ){
129391      p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
129392    }else{
129393      p->aMatchinfo[iStart+i*3] = 0;
129394    }
129395  }
129396
129397  return SQLITE_OK;
129398}
129399
129400static int fts3MatchinfoCheck(
129401  Fts3Table *pTab,
129402  char cArg,
129403  char **pzErr
129404){
129405  if( (cArg==FTS3_MATCHINFO_NPHRASE)
129406   || (cArg==FTS3_MATCHINFO_NCOL)
129407   || (cArg==FTS3_MATCHINFO_NDOC && pTab->bHasStat)
129408   || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bHasStat)
129409   || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
129410   || (cArg==FTS3_MATCHINFO_LCS)
129411   || (cArg==FTS3_MATCHINFO_HITS)
129412  ){
129413    return SQLITE_OK;
129414  }
129415  *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
129416  return SQLITE_ERROR;
129417}
129418
129419static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
129420  int nVal;                       /* Number of integers output by cArg */
129421
129422  switch( cArg ){
129423    case FTS3_MATCHINFO_NDOC:
129424    case FTS3_MATCHINFO_NPHRASE:
129425    case FTS3_MATCHINFO_NCOL:
129426      nVal = 1;
129427      break;
129428
129429    case FTS3_MATCHINFO_AVGLENGTH:
129430    case FTS3_MATCHINFO_LENGTH:
129431    case FTS3_MATCHINFO_LCS:
129432      nVal = pInfo->nCol;
129433      break;
129434
129435    default:
129436      assert( cArg==FTS3_MATCHINFO_HITS );
129437      nVal = pInfo->nCol * pInfo->nPhrase * 3;
129438      break;
129439  }
129440
129441  return nVal;
129442}
129443
129444static int fts3MatchinfoSelectDoctotal(
129445  Fts3Table *pTab,
129446  sqlite3_stmt **ppStmt,
129447  sqlite3_int64 *pnDoc,
129448  const char **paLen
129449){
129450  sqlite3_stmt *pStmt;
129451  const char *a;
129452  sqlite3_int64 nDoc;
129453
129454  if( !*ppStmt ){
129455    int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
129456    if( rc!=SQLITE_OK ) return rc;
129457  }
129458  pStmt = *ppStmt;
129459  assert( sqlite3_data_count(pStmt)==1 );
129460
129461  a = sqlite3_column_blob(pStmt, 0);
129462  a += sqlite3Fts3GetVarint(a, &nDoc);
129463  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
129464  *pnDoc = (u32)nDoc;
129465
129466  if( paLen ) *paLen = a;
129467  return SQLITE_OK;
129468}
129469
129470/*
129471** An instance of the following structure is used to store state while
129472** iterating through a multi-column position-list corresponding to the
129473** hits for a single phrase on a single row in order to calculate the
129474** values for a matchinfo() FTS3_MATCHINFO_LCS request.
129475*/
129476typedef struct LcsIterator LcsIterator;
129477struct LcsIterator {
129478  Fts3Expr *pExpr;                /* Pointer to phrase expression */
129479  int iPosOffset;                 /* Tokens count up to end of this phrase */
129480  char *pRead;                    /* Cursor used to iterate through aDoclist */
129481  int iPos;                       /* Current position */
129482};
129483
129484/*
129485** If LcsIterator.iCol is set to the following value, the iterator has
129486** finished iterating through all offsets for all columns.
129487*/
129488#define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
129489
129490static int fts3MatchinfoLcsCb(
129491  Fts3Expr *pExpr,                /* Phrase expression node */
129492  int iPhrase,                    /* Phrase number (numbered from zero) */
129493  void *pCtx                      /* Pointer to MatchInfo structure */
129494){
129495  LcsIterator *aIter = (LcsIterator *)pCtx;
129496  aIter[iPhrase].pExpr = pExpr;
129497  return SQLITE_OK;
129498}
129499
129500/*
129501** Advance the iterator passed as an argument to the next position. Return
129502** 1 if the iterator is at EOF or if it now points to the start of the
129503** position list for the next column.
129504*/
129505static int fts3LcsIteratorAdvance(LcsIterator *pIter){
129506  char *pRead = pIter->pRead;
129507  sqlite3_int64 iRead;
129508  int rc = 0;
129509
129510  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
129511  if( iRead==0 || iRead==1 ){
129512    pRead = 0;
129513    rc = 1;
129514  }else{
129515    pIter->iPos += (int)(iRead-2);
129516  }
129517
129518  pIter->pRead = pRead;
129519  return rc;
129520}
129521
129522/*
129523** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
129524**
129525** If the call is successful, the longest-common-substring lengths for each
129526** column are written into the first nCol elements of the pInfo->aMatchinfo[]
129527** array before returning. SQLITE_OK is returned in this case.
129528**
129529** Otherwise, if an error occurs, an SQLite error code is returned and the
129530** data written to the first nCol elements of pInfo->aMatchinfo[] is
129531** undefined.
129532*/
129533static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
129534  LcsIterator *aIter;
129535  int i;
129536  int iCol;
129537  int nToken = 0;
129538
129539  /* Allocate and populate the array of LcsIterator objects. The array
129540  ** contains one element for each matchable phrase in the query.
129541  **/
129542  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
129543  if( !aIter ) return SQLITE_NOMEM;
129544  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
129545  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
129546
129547  for(i=0; i<pInfo->nPhrase; i++){
129548    LcsIterator *pIter = &aIter[i];
129549    nToken -= pIter->pExpr->pPhrase->nToken;
129550    pIter->iPosOffset = nToken;
129551  }
129552
129553  for(iCol=0; iCol<pInfo->nCol; iCol++){
129554    int nLcs = 0;                 /* LCS value for this column */
129555    int nLive = 0;                /* Number of iterators in aIter not at EOF */
129556
129557    for(i=0; i<pInfo->nPhrase; i++){
129558      LcsIterator *pIt = &aIter[i];
129559      pIt->pRead = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol);
129560      if( pIt->pRead ){
129561        pIt->iPos = pIt->iPosOffset;
129562        fts3LcsIteratorAdvance(&aIter[i]);
129563        nLive++;
129564      }
129565    }
129566
129567    while( nLive>0 ){
129568      LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
129569      int nThisLcs = 0;           /* LCS for the current iterator positions */
129570
129571      for(i=0; i<pInfo->nPhrase; i++){
129572        LcsIterator *pIter = &aIter[i];
129573        if( pIter->pRead==0 ){
129574          /* This iterator is already at EOF for this column. */
129575          nThisLcs = 0;
129576        }else{
129577          if( pAdv==0 || pIter->iPos<pAdv->iPos ){
129578            pAdv = pIter;
129579          }
129580          if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
129581            nThisLcs++;
129582          }else{
129583            nThisLcs = 1;
129584          }
129585          if( nThisLcs>nLcs ) nLcs = nThisLcs;
129586        }
129587      }
129588      if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
129589    }
129590
129591    pInfo->aMatchinfo[iCol] = nLcs;
129592  }
129593
129594  sqlite3_free(aIter);
129595  return SQLITE_OK;
129596}
129597
129598/*
129599** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
129600** be returned by the matchinfo() function. Argument zArg contains the
129601** format string passed as the second argument to matchinfo (or the
129602** default value "pcx" if no second argument was specified). The format
129603** string has already been validated and the pInfo->aMatchinfo[] array
129604** is guaranteed to be large enough for the output.
129605**
129606** If bGlobal is true, then populate all fields of the matchinfo() output.
129607** If it is false, then assume that those fields that do not change between
129608** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
129609** have already been populated.
129610**
129611** Return SQLITE_OK if successful, or an SQLite error code if an error
129612** occurs. If a value other than SQLITE_OK is returned, the state the
129613** pInfo->aMatchinfo[] buffer is left in is undefined.
129614*/
129615static int fts3MatchinfoValues(
129616  Fts3Cursor *pCsr,               /* FTS3 cursor object */
129617  int bGlobal,                    /* True to grab the global stats */
129618  MatchInfo *pInfo,               /* Matchinfo context object */
129619  const char *zArg                /* Matchinfo format string */
129620){
129621  int rc = SQLITE_OK;
129622  int i;
129623  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129624  sqlite3_stmt *pSelect = 0;
129625
129626  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
129627
129628    switch( zArg[i] ){
129629      case FTS3_MATCHINFO_NPHRASE:
129630        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
129631        break;
129632
129633      case FTS3_MATCHINFO_NCOL:
129634        if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
129635        break;
129636
129637      case FTS3_MATCHINFO_NDOC:
129638        if( bGlobal ){
129639          sqlite3_int64 nDoc = 0;
129640          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
129641          pInfo->aMatchinfo[0] = (u32)nDoc;
129642        }
129643        break;
129644
129645      case FTS3_MATCHINFO_AVGLENGTH:
129646        if( bGlobal ){
129647          sqlite3_int64 nDoc;     /* Number of rows in table */
129648          const char *a;          /* Aggregate column length array */
129649
129650          rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
129651          if( rc==SQLITE_OK ){
129652            int iCol;
129653            for(iCol=0; iCol<pInfo->nCol; iCol++){
129654              u32 iVal;
129655              sqlite3_int64 nToken;
129656              a += sqlite3Fts3GetVarint(a, &nToken);
129657              iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
129658              pInfo->aMatchinfo[iCol] = iVal;
129659            }
129660          }
129661        }
129662        break;
129663
129664      case FTS3_MATCHINFO_LENGTH: {
129665        sqlite3_stmt *pSelectDocsize = 0;
129666        rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
129667        if( rc==SQLITE_OK ){
129668          int iCol;
129669          const char *a = sqlite3_column_blob(pSelectDocsize, 0);
129670          for(iCol=0; iCol<pInfo->nCol; iCol++){
129671            sqlite3_int64 nToken;
129672            a += sqlite3Fts3GetVarint(a, &nToken);
129673            pInfo->aMatchinfo[iCol] = (u32)nToken;
129674          }
129675        }
129676        sqlite3_reset(pSelectDocsize);
129677        break;
129678      }
129679
129680      case FTS3_MATCHINFO_LCS:
129681        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
129682        if( rc==SQLITE_OK ){
129683          rc = fts3MatchinfoLcs(pCsr, pInfo);
129684        }
129685        break;
129686
129687      default: {
129688        Fts3Expr *pExpr;
129689        assert( zArg[i]==FTS3_MATCHINFO_HITS );
129690        pExpr = pCsr->pExpr;
129691        rc = fts3ExprLoadDoclists(pCsr, 0, 0);
129692        if( rc!=SQLITE_OK ) break;
129693        if( bGlobal ){
129694          if( pCsr->pDeferred ){
129695            rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
129696            if( rc!=SQLITE_OK ) break;
129697          }
129698          rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
129699          if( rc!=SQLITE_OK ) break;
129700        }
129701        (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
129702        break;
129703      }
129704    }
129705
129706    pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
129707  }
129708
129709  sqlite3_reset(pSelect);
129710  return rc;
129711}
129712
129713
129714/*
129715** Populate pCsr->aMatchinfo[] with data for the current row. The
129716** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
129717*/
129718static int fts3GetMatchinfo(
129719  Fts3Cursor *pCsr,               /* FTS3 Cursor object */
129720  const char *zArg                /* Second argument to matchinfo() function */
129721){
129722  MatchInfo sInfo;
129723  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129724  int rc = SQLITE_OK;
129725  int bGlobal = 0;                /* Collect 'global' stats as well as local */
129726
129727  memset(&sInfo, 0, sizeof(MatchInfo));
129728  sInfo.pCursor = pCsr;
129729  sInfo.nCol = pTab->nColumn;
129730
129731  /* If there is cached matchinfo() data, but the format string for the
129732  ** cache does not match the format string for this request, discard
129733  ** the cached data. */
129734  if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
129735    assert( pCsr->aMatchinfo );
129736    sqlite3_free(pCsr->aMatchinfo);
129737    pCsr->zMatchinfo = 0;
129738    pCsr->aMatchinfo = 0;
129739  }
129740
129741  /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
129742  ** matchinfo function has been called for this query. In this case
129743  ** allocate the array used to accumulate the matchinfo data and
129744  ** initialize those elements that are constant for every row.
129745  */
129746  if( pCsr->aMatchinfo==0 ){
129747    int nMatchinfo = 0;           /* Number of u32 elements in match-info */
129748    int nArg;                     /* Bytes in zArg */
129749    int i;                        /* Used to iterate through zArg */
129750
129751    /* Determine the number of phrases in the query */
129752    pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
129753    sInfo.nPhrase = pCsr->nPhrase;
129754
129755    /* Determine the number of integers in the buffer returned by this call. */
129756    for(i=0; zArg[i]; i++){
129757      nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
129758    }
129759
129760    /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
129761    nArg = (int)strlen(zArg);
129762    pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
129763    if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
129764
129765    pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
129766    pCsr->nMatchinfo = nMatchinfo;
129767    memcpy(pCsr->zMatchinfo, zArg, nArg+1);
129768    memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
129769    pCsr->isMatchinfoNeeded = 1;
129770    bGlobal = 1;
129771  }
129772
129773  sInfo.aMatchinfo = pCsr->aMatchinfo;
129774  sInfo.nPhrase = pCsr->nPhrase;
129775  if( pCsr->isMatchinfoNeeded ){
129776    rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
129777    pCsr->isMatchinfoNeeded = 0;
129778  }
129779
129780  return rc;
129781}
129782
129783/*
129784** Implementation of snippet() function.
129785*/
129786SQLITE_PRIVATE void sqlite3Fts3Snippet(
129787  sqlite3_context *pCtx,          /* SQLite function call context */
129788  Fts3Cursor *pCsr,               /* Cursor object */
129789  const char *zStart,             /* Snippet start text - "<b>" */
129790  const char *zEnd,               /* Snippet end text - "</b>" */
129791  const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
129792  int iCol,                       /* Extract snippet from this column */
129793  int nToken                      /* Approximate number of tokens in snippet */
129794){
129795  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129796  int rc = SQLITE_OK;
129797  int i;
129798  StrBuffer res = {0, 0, 0};
129799
129800  /* The returned text includes up to four fragments of text extracted from
129801  ** the data in the current row. The first iteration of the for(...) loop
129802  ** below attempts to locate a single fragment of text nToken tokens in
129803  ** size that contains at least one instance of all phrases in the query
129804  ** expression that appear in the current row. If such a fragment of text
129805  ** cannot be found, the second iteration of the loop attempts to locate
129806  ** a pair of fragments, and so on.
129807  */
129808  int nSnippet = 0;               /* Number of fragments in this snippet */
129809  SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
129810  int nFToken = -1;               /* Number of tokens in each fragment */
129811
129812  if( !pCsr->pExpr ){
129813    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
129814    return;
129815  }
129816
129817  for(nSnippet=1; 1; nSnippet++){
129818
129819    int iSnip;                    /* Loop counter 0..nSnippet-1 */
129820    u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
129821    u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
129822
129823    if( nToken>=0 ){
129824      nFToken = (nToken+nSnippet-1) / nSnippet;
129825    }else{
129826      nFToken = -1 * nToken;
129827    }
129828
129829    for(iSnip=0; iSnip<nSnippet; iSnip++){
129830      int iBestScore = -1;        /* Best score of columns checked so far */
129831      int iRead;                  /* Used to iterate through columns */
129832      SnippetFragment *pFragment = &aSnippet[iSnip];
129833
129834      memset(pFragment, 0, sizeof(*pFragment));
129835
129836      /* Loop through all columns of the table being considered for snippets.
129837      ** If the iCol argument to this function was negative, this means all
129838      ** columns of the FTS3 table. Otherwise, only column iCol is considered.
129839      */
129840      for(iRead=0; iRead<pTab->nColumn; iRead++){
129841        SnippetFragment sF = {0, 0, 0, 0};
129842        int iS;
129843        if( iCol>=0 && iRead!=iCol ) continue;
129844
129845        /* Find the best snippet of nFToken tokens in column iRead. */
129846        rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
129847        if( rc!=SQLITE_OK ){
129848          goto snippet_out;
129849        }
129850        if( iS>iBestScore ){
129851          *pFragment = sF;
129852          iBestScore = iS;
129853        }
129854      }
129855
129856      mCovered |= pFragment->covered;
129857    }
129858
129859    /* If all query phrases seen by fts3BestSnippet() are present in at least
129860    ** one of the nSnippet snippet fragments, break out of the loop.
129861    */
129862    assert( (mCovered&mSeen)==mCovered );
129863    if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
129864  }
129865
129866  assert( nFToken>0 );
129867
129868  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
129869    rc = fts3SnippetText(pCsr, &aSnippet[i],
129870        i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
129871    );
129872  }
129873
129874 snippet_out:
129875  sqlite3Fts3SegmentsClose(pTab);
129876  if( rc!=SQLITE_OK ){
129877    sqlite3_result_error_code(pCtx, rc);
129878    sqlite3_free(res.z);
129879  }else{
129880    sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
129881  }
129882}
129883
129884
129885typedef struct TermOffset TermOffset;
129886typedef struct TermOffsetCtx TermOffsetCtx;
129887
129888struct TermOffset {
129889  char *pList;                    /* Position-list */
129890  int iPos;                       /* Position just read from pList */
129891  int iOff;                       /* Offset of this term from read positions */
129892};
129893
129894struct TermOffsetCtx {
129895  Fts3Cursor *pCsr;
129896  int iCol;                       /* Column of table to populate aTerm for */
129897  int iTerm;
129898  sqlite3_int64 iDocid;
129899  TermOffset *aTerm;
129900};
129901
129902/*
129903** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
129904*/
129905static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
129906  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
129907  int nTerm;                      /* Number of tokens in phrase */
129908  int iTerm;                      /* For looping through nTerm phrase terms */
129909  char *pList;                    /* Pointer to position list for phrase */
129910  int iPos = 0;                   /* First position in position-list */
129911
129912  UNUSED_PARAMETER(iPhrase);
129913  pList = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol);
129914  nTerm = pExpr->pPhrase->nToken;
129915  if( pList ){
129916    fts3GetDeltaPosition(&pList, &iPos);
129917    assert( iPos>=0 );
129918  }
129919
129920  for(iTerm=0; iTerm<nTerm; iTerm++){
129921    TermOffset *pT = &p->aTerm[p->iTerm++];
129922    pT->iOff = nTerm-iTerm-1;
129923    pT->pList = pList;
129924    pT->iPos = iPos;
129925  }
129926
129927  return SQLITE_OK;
129928}
129929
129930/*
129931** Implementation of offsets() function.
129932*/
129933SQLITE_PRIVATE void sqlite3Fts3Offsets(
129934  sqlite3_context *pCtx,          /* SQLite function call context */
129935  Fts3Cursor *pCsr                /* Cursor object */
129936){
129937  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
129938  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
129939  const char *ZDUMMY;             /* Dummy argument used with xNext() */
129940  int NDUMMY;                     /* Dummy argument used with xNext() */
129941  int rc;                         /* Return Code */
129942  int nToken;                     /* Number of tokens in query */
129943  int iCol;                       /* Column currently being processed */
129944  StrBuffer res = {0, 0, 0};      /* Result string */
129945  TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
129946
129947  if( !pCsr->pExpr ){
129948    sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
129949    return;
129950  }
129951
129952  memset(&sCtx, 0, sizeof(sCtx));
129953  assert( pCsr->isRequireSeek==0 );
129954
129955  /* Count the number of terms in the query */
129956  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
129957  if( rc!=SQLITE_OK ) goto offsets_out;
129958
129959  /* Allocate the array of TermOffset iterators. */
129960  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
129961  if( 0==sCtx.aTerm ){
129962    rc = SQLITE_NOMEM;
129963    goto offsets_out;
129964  }
129965  sCtx.iDocid = pCsr->iPrevId;
129966  sCtx.pCsr = pCsr;
129967
129968  /* Loop through the table columns, appending offset information to
129969  ** string-buffer res for each column.
129970  */
129971  for(iCol=0; iCol<pTab->nColumn; iCol++){
129972    sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
129973    int iStart;
129974    int iEnd;
129975    int iCurrent;
129976    const char *zDoc;
129977    int nDoc;
129978
129979    /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
129980    ** no way that this operation can fail, so the return code from
129981    ** fts3ExprIterate() can be discarded.
129982    */
129983    sCtx.iCol = iCol;
129984    sCtx.iTerm = 0;
129985    (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
129986
129987    /* Retreive the text stored in column iCol. If an SQL NULL is stored
129988    ** in column iCol, jump immediately to the next iteration of the loop.
129989    ** If an OOM occurs while retrieving the data (this can happen if SQLite
129990    ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
129991    ** to the caller.
129992    */
129993    zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
129994    nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
129995    if( zDoc==0 ){
129996      if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
129997        continue;
129998      }
129999      rc = SQLITE_NOMEM;
130000      goto offsets_out;
130001    }
130002
130003    /* Initialize a tokenizer iterator to iterate through column iCol. */
130004    rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
130005        zDoc, nDoc, &pC
130006    );
130007    if( rc!=SQLITE_OK ) goto offsets_out;
130008
130009    rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
130010    while( rc==SQLITE_OK ){
130011      int i;                      /* Used to loop through terms */
130012      int iMinPos = 0x7FFFFFFF;   /* Position of next token */
130013      TermOffset *pTerm = 0;      /* TermOffset associated with next token */
130014
130015      for(i=0; i<nToken; i++){
130016        TermOffset *pT = &sCtx.aTerm[i];
130017        if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
130018          iMinPos = pT->iPos-pT->iOff;
130019          pTerm = pT;
130020        }
130021      }
130022
130023      if( !pTerm ){
130024        /* All offsets for this column have been gathered. */
130025        rc = SQLITE_DONE;
130026      }else{
130027        assert( iCurrent<=iMinPos );
130028        if( 0==(0xFE&*pTerm->pList) ){
130029          pTerm->pList = 0;
130030        }else{
130031          fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
130032        }
130033        while( rc==SQLITE_OK && iCurrent<iMinPos ){
130034          rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
130035        }
130036        if( rc==SQLITE_OK ){
130037          char aBuffer[64];
130038          sqlite3_snprintf(sizeof(aBuffer), aBuffer,
130039              "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
130040          );
130041          rc = fts3StringAppend(&res, aBuffer, -1);
130042        }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
130043          rc = FTS_CORRUPT_VTAB;
130044        }
130045      }
130046    }
130047    if( rc==SQLITE_DONE ){
130048      rc = SQLITE_OK;
130049    }
130050
130051    pMod->xClose(pC);
130052    if( rc!=SQLITE_OK ) goto offsets_out;
130053  }
130054
130055 offsets_out:
130056  sqlite3_free(sCtx.aTerm);
130057  assert( rc!=SQLITE_DONE );
130058  sqlite3Fts3SegmentsClose(pTab);
130059  if( rc!=SQLITE_OK ){
130060    sqlite3_result_error_code(pCtx,  rc);
130061    sqlite3_free(res.z);
130062  }else{
130063    sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
130064  }
130065  return;
130066}
130067
130068/*
130069** Implementation of matchinfo() function.
130070*/
130071SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
130072  sqlite3_context *pContext,      /* Function call context */
130073  Fts3Cursor *pCsr,               /* FTS3 table cursor */
130074  const char *zArg                /* Second arg to matchinfo() function */
130075){
130076  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
130077  int rc;
130078  int i;
130079  const char *zFormat;
130080
130081  if( zArg ){
130082    for(i=0; zArg[i]; i++){
130083      char *zErr = 0;
130084      if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
130085        sqlite3_result_error(pContext, zErr, -1);
130086        sqlite3_free(zErr);
130087        return;
130088      }
130089    }
130090    zFormat = zArg;
130091  }else{
130092    zFormat = FTS3_MATCHINFO_DEFAULT;
130093  }
130094
130095  if( !pCsr->pExpr ){
130096    sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
130097    return;
130098  }
130099
130100  /* Retrieve matchinfo() data. */
130101  rc = fts3GetMatchinfo(pCsr, zFormat);
130102  sqlite3Fts3SegmentsClose(pTab);
130103
130104  if( rc!=SQLITE_OK ){
130105    sqlite3_result_error_code(pContext, rc);
130106  }else{
130107    int n = pCsr->nMatchinfo * sizeof(u32);
130108    sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
130109  }
130110}
130111
130112#endif
130113
130114/************** End of fts3_snippet.c ****************************************/
130115/************** Begin file rtree.c *******************************************/
130116/*
130117** 2001 September 15
130118**
130119** The author disclaims copyright to this source code.  In place of
130120** a legal notice, here is a blessing:
130121**
130122**    May you do good and not evil.
130123**    May you find forgiveness for yourself and forgive others.
130124**    May you share freely, never taking more than you give.
130125**
130126*************************************************************************
130127** This file contains code for implementations of the r-tree and r*-tree
130128** algorithms packaged as an SQLite virtual table module.
130129*/
130130
130131/*
130132** Database Format of R-Tree Tables
130133** --------------------------------
130134**
130135** The data structure for a single virtual r-tree table is stored in three
130136** native SQLite tables declared as follows. In each case, the '%' character
130137** in the table name is replaced with the user-supplied name of the r-tree
130138** table.
130139**
130140**   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
130141**   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
130142**   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
130143**
130144** The data for each node of the r-tree structure is stored in the %_node
130145** table. For each node that is not the root node of the r-tree, there is
130146** an entry in the %_parent table associating the node with its parent.
130147** And for each row of data in the table, there is an entry in the %_rowid
130148** table that maps from the entries rowid to the id of the node that it
130149** is stored on.
130150**
130151** The root node of an r-tree always exists, even if the r-tree table is
130152** empty. The nodeno of the root node is always 1. All other nodes in the
130153** table must be the same size as the root node. The content of each node
130154** is formatted as follows:
130155**
130156**   1. If the node is the root node (node 1), then the first 2 bytes
130157**      of the node contain the tree depth as a big-endian integer.
130158**      For non-root nodes, the first 2 bytes are left unused.
130159**
130160**   2. The next 2 bytes contain the number of entries currently
130161**      stored in the node.
130162**
130163**   3. The remainder of the node contains the node entries. Each entry
130164**      consists of a single 8-byte integer followed by an even number
130165**      of 4-byte coordinates. For leaf nodes the integer is the rowid
130166**      of a record. For internal nodes it is the node number of a
130167**      child page.
130168*/
130169
130170#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
130171
130172/*
130173** This file contains an implementation of a couple of different variants
130174** of the r-tree algorithm. See the README file for further details. The
130175** same data-structure is used for all, but the algorithms for insert and
130176** delete operations vary. The variants used are selected at compile time
130177** by defining the following symbols:
130178*/
130179
130180/* Either, both or none of the following may be set to activate
130181** r*tree variant algorithms.
130182*/
130183#define VARIANT_RSTARTREE_CHOOSESUBTREE 0
130184#define VARIANT_RSTARTREE_REINSERT      1
130185
130186/*
130187** Exactly one of the following must be set to 1.
130188*/
130189#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
130190#define VARIANT_GUTTMAN_LINEAR_SPLIT    0
130191#define VARIANT_RSTARTREE_SPLIT         1
130192
130193#define VARIANT_GUTTMAN_SPLIT \
130194        (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
130195
130196#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
130197  #define PickNext QuadraticPickNext
130198  #define PickSeeds QuadraticPickSeeds
130199  #define AssignCells splitNodeGuttman
130200#endif
130201#if VARIANT_GUTTMAN_LINEAR_SPLIT
130202  #define PickNext LinearPickNext
130203  #define PickSeeds LinearPickSeeds
130204  #define AssignCells splitNodeGuttman
130205#endif
130206#if VARIANT_RSTARTREE_SPLIT
130207  #define AssignCells splitNodeStartree
130208#endif
130209
130210#if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
130211# define NDEBUG 1
130212#endif
130213
130214#ifndef SQLITE_CORE
130215  SQLITE_EXTENSION_INIT1
130216#else
130217#endif
130218
130219/* #include <string.h> */
130220/* #include <assert.h> */
130221
130222#ifndef SQLITE_AMALGAMATION
130223#include "sqlite3rtree.h"
130224typedef sqlite3_int64 i64;
130225typedef unsigned char u8;
130226typedef unsigned int u32;
130227#endif
130228
130229/*  The following macro is used to suppress compiler warnings.
130230*/
130231#ifndef UNUSED_PARAMETER
130232# define UNUSED_PARAMETER(x) (void)(x)
130233#endif
130234
130235typedef struct Rtree Rtree;
130236typedef struct RtreeCursor RtreeCursor;
130237typedef struct RtreeNode RtreeNode;
130238typedef struct RtreeCell RtreeCell;
130239typedef struct RtreeConstraint RtreeConstraint;
130240typedef struct RtreeMatchArg RtreeMatchArg;
130241typedef struct RtreeGeomCallback RtreeGeomCallback;
130242typedef union RtreeCoord RtreeCoord;
130243
130244/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
130245#define RTREE_MAX_DIMENSIONS 5
130246
130247/* Size of hash table Rtree.aHash. This hash table is not expected to
130248** ever contain very many entries, so a fixed number of buckets is
130249** used.
130250*/
130251#define HASHSIZE 128
130252
130253/*
130254** An rtree virtual-table object.
130255*/
130256struct Rtree {
130257  sqlite3_vtab base;
130258  sqlite3 *db;                /* Host database connection */
130259  int iNodeSize;              /* Size in bytes of each node in the node table */
130260  int nDim;                   /* Number of dimensions */
130261  int nBytesPerCell;          /* Bytes consumed per cell */
130262  int iDepth;                 /* Current depth of the r-tree structure */
130263  char *zDb;                  /* Name of database containing r-tree table */
130264  char *zName;                /* Name of r-tree table */
130265  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
130266  int nBusy;                  /* Current number of users of this structure */
130267
130268  /* List of nodes removed during a CondenseTree operation. List is
130269  ** linked together via the pointer normally used for hash chains -
130270  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
130271  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
130272  */
130273  RtreeNode *pDeleted;
130274  int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
130275
130276  /* Statements to read/write/delete a record from xxx_node */
130277  sqlite3_stmt *pReadNode;
130278  sqlite3_stmt *pWriteNode;
130279  sqlite3_stmt *pDeleteNode;
130280
130281  /* Statements to read/write/delete a record from xxx_rowid */
130282  sqlite3_stmt *pReadRowid;
130283  sqlite3_stmt *pWriteRowid;
130284  sqlite3_stmt *pDeleteRowid;
130285
130286  /* Statements to read/write/delete a record from xxx_parent */
130287  sqlite3_stmt *pReadParent;
130288  sqlite3_stmt *pWriteParent;
130289  sqlite3_stmt *pDeleteParent;
130290
130291  int eCoordType;
130292};
130293
130294/* Possible values for eCoordType: */
130295#define RTREE_COORD_REAL32 0
130296#define RTREE_COORD_INT32  1
130297
130298/*
130299** The minimum number of cells allowed for a node is a third of the
130300** maximum. In Gutman's notation:
130301**
130302**     m = M/3
130303**
130304** If an R*-tree "Reinsert" operation is required, the same number of
130305** cells are removed from the overfull node and reinserted into the tree.
130306*/
130307#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
130308#define RTREE_REINSERT(p) RTREE_MINCELLS(p)
130309#define RTREE_MAXCELLS 51
130310
130311/*
130312** The smallest possible node-size is (512-64)==448 bytes. And the largest
130313** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
130314** Therefore all non-root nodes must contain at least 3 entries. Since
130315** 2^40 is greater than 2^64, an r-tree structure always has a depth of
130316** 40 or less.
130317*/
130318#define RTREE_MAX_DEPTH 40
130319
130320/*
130321** An rtree cursor object.
130322*/
130323struct RtreeCursor {
130324  sqlite3_vtab_cursor base;
130325  RtreeNode *pNode;                 /* Node cursor is currently pointing at */
130326  int iCell;                        /* Index of current cell in pNode */
130327  int iStrategy;                    /* Copy of idxNum search parameter */
130328  int nConstraint;                  /* Number of entries in aConstraint */
130329  RtreeConstraint *aConstraint;     /* Search constraints. */
130330};
130331
130332union RtreeCoord {
130333  float f;
130334  int i;
130335};
130336
130337/*
130338** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
130339** formatted as a double. This macro assumes that local variable pRtree points
130340** to the Rtree structure associated with the RtreeCoord.
130341*/
130342#define DCOORD(coord) (                           \
130343  (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
130344    ((double)coord.f) :                           \
130345    ((double)coord.i)                             \
130346)
130347
130348/*
130349** A search constraint.
130350*/
130351struct RtreeConstraint {
130352  int iCoord;                     /* Index of constrained coordinate */
130353  int op;                         /* Constraining operation */
130354  double rValue;                  /* Constraint value. */
130355  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
130356  sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
130357};
130358
130359/* Possible values for RtreeConstraint.op */
130360#define RTREE_EQ    0x41
130361#define RTREE_LE    0x42
130362#define RTREE_LT    0x43
130363#define RTREE_GE    0x44
130364#define RTREE_GT    0x45
130365#define RTREE_MATCH 0x46
130366
130367/*
130368** An rtree structure node.
130369*/
130370struct RtreeNode {
130371  RtreeNode *pParent;               /* Parent node */
130372  i64 iNode;
130373  int nRef;
130374  int isDirty;
130375  u8 *zData;
130376  RtreeNode *pNext;                 /* Next node in this hash chain */
130377};
130378#define NCELL(pNode) readInt16(&(pNode)->zData[2])
130379
130380/*
130381** Structure to store a deserialized rtree record.
130382*/
130383struct RtreeCell {
130384  i64 iRowid;
130385  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
130386};
130387
130388
130389/*
130390** Value for the first field of every RtreeMatchArg object. The MATCH
130391** operator tests that the first field of a blob operand matches this
130392** value to avoid operating on invalid blobs (which could cause a segfault).
130393*/
130394#define RTREE_GEOMETRY_MAGIC 0x891245AB
130395
130396/*
130397** An instance of this structure must be supplied as a blob argument to
130398** the right-hand-side of an SQL MATCH operator used to constrain an
130399** r-tree query.
130400*/
130401struct RtreeMatchArg {
130402  u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
130403  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
130404  void *pContext;
130405  int nParam;
130406  double aParam[1];
130407};
130408
130409/*
130410** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
130411** a single instance of the following structure is allocated. It is used
130412** as the context for the user-function created by by s_r_g_c(). The object
130413** is eventually deleted by the destructor mechanism provided by
130414** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
130415** the geometry callback function).
130416*/
130417struct RtreeGeomCallback {
130418  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *);
130419  void *pContext;
130420};
130421
130422#ifndef MAX
130423# define MAX(x,y) ((x) < (y) ? (y) : (x))
130424#endif
130425#ifndef MIN
130426# define MIN(x,y) ((x) > (y) ? (y) : (x))
130427#endif
130428
130429/*
130430** Functions to deserialize a 16 bit integer, 32 bit real number and
130431** 64 bit integer. The deserialized value is returned.
130432*/
130433static int readInt16(u8 *p){
130434  return (p[0]<<8) + p[1];
130435}
130436static void readCoord(u8 *p, RtreeCoord *pCoord){
130437  u32 i = (
130438    (((u32)p[0]) << 24) +
130439    (((u32)p[1]) << 16) +
130440    (((u32)p[2]) <<  8) +
130441    (((u32)p[3]) <<  0)
130442  );
130443  *(u32 *)pCoord = i;
130444}
130445static i64 readInt64(u8 *p){
130446  return (
130447    (((i64)p[0]) << 56) +
130448    (((i64)p[1]) << 48) +
130449    (((i64)p[2]) << 40) +
130450    (((i64)p[3]) << 32) +
130451    (((i64)p[4]) << 24) +
130452    (((i64)p[5]) << 16) +
130453    (((i64)p[6]) <<  8) +
130454    (((i64)p[7]) <<  0)
130455  );
130456}
130457
130458/*
130459** Functions to serialize a 16 bit integer, 32 bit real number and
130460** 64 bit integer. The value returned is the number of bytes written
130461** to the argument buffer (always 2, 4 and 8 respectively).
130462*/
130463static int writeInt16(u8 *p, int i){
130464  p[0] = (i>> 8)&0xFF;
130465  p[1] = (i>> 0)&0xFF;
130466  return 2;
130467}
130468static int writeCoord(u8 *p, RtreeCoord *pCoord){
130469  u32 i;
130470  assert( sizeof(RtreeCoord)==4 );
130471  assert( sizeof(u32)==4 );
130472  i = *(u32 *)pCoord;
130473  p[0] = (i>>24)&0xFF;
130474  p[1] = (i>>16)&0xFF;
130475  p[2] = (i>> 8)&0xFF;
130476  p[3] = (i>> 0)&0xFF;
130477  return 4;
130478}
130479static int writeInt64(u8 *p, i64 i){
130480  p[0] = (i>>56)&0xFF;
130481  p[1] = (i>>48)&0xFF;
130482  p[2] = (i>>40)&0xFF;
130483  p[3] = (i>>32)&0xFF;
130484  p[4] = (i>>24)&0xFF;
130485  p[5] = (i>>16)&0xFF;
130486  p[6] = (i>> 8)&0xFF;
130487  p[7] = (i>> 0)&0xFF;
130488  return 8;
130489}
130490
130491/*
130492** Increment the reference count of node p.
130493*/
130494static void nodeReference(RtreeNode *p){
130495  if( p ){
130496    p->nRef++;
130497  }
130498}
130499
130500/*
130501** Clear the content of node p (set all bytes to 0x00).
130502*/
130503static void nodeZero(Rtree *pRtree, RtreeNode *p){
130504  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
130505  p->isDirty = 1;
130506}
130507
130508/*
130509** Given a node number iNode, return the corresponding key to use
130510** in the Rtree.aHash table.
130511*/
130512static int nodeHash(i64 iNode){
130513  return (
130514    (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
130515    (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
130516  ) % HASHSIZE;
130517}
130518
130519/*
130520** Search the node hash table for node iNode. If found, return a pointer
130521** to it. Otherwise, return 0.
130522*/
130523static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
130524  RtreeNode *p;
130525  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
130526  return p;
130527}
130528
130529/*
130530** Add node pNode to the node hash table.
130531*/
130532static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
130533  int iHash;
130534  assert( pNode->pNext==0 );
130535  iHash = nodeHash(pNode->iNode);
130536  pNode->pNext = pRtree->aHash[iHash];
130537  pRtree->aHash[iHash] = pNode;
130538}
130539
130540/*
130541** Remove node pNode from the node hash table.
130542*/
130543static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
130544  RtreeNode **pp;
130545  if( pNode->iNode!=0 ){
130546    pp = &pRtree->aHash[nodeHash(pNode->iNode)];
130547    for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
130548    *pp = pNode->pNext;
130549    pNode->pNext = 0;
130550  }
130551}
130552
130553/*
130554** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
130555** indicating that node has not yet been assigned a node number. It is
130556** assigned a node number when nodeWrite() is called to write the
130557** node contents out to the database.
130558*/
130559static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
130560  RtreeNode *pNode;
130561  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
130562  if( pNode ){
130563    memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
130564    pNode->zData = (u8 *)&pNode[1];
130565    pNode->nRef = 1;
130566    pNode->pParent = pParent;
130567    pNode->isDirty = 1;
130568    nodeReference(pParent);
130569  }
130570  return pNode;
130571}
130572
130573/*
130574** Obtain a reference to an r-tree node.
130575*/
130576static int
130577nodeAcquire(
130578  Rtree *pRtree,             /* R-tree structure */
130579  i64 iNode,                 /* Node number to load */
130580  RtreeNode *pParent,        /* Either the parent node or NULL */
130581  RtreeNode **ppNode         /* OUT: Acquired node */
130582){
130583  int rc;
130584  int rc2 = SQLITE_OK;
130585  RtreeNode *pNode;
130586
130587  /* Check if the requested node is already in the hash table. If so,
130588  ** increase its reference count and return it.
130589  */
130590  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
130591    assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
130592    if( pParent && !pNode->pParent ){
130593      nodeReference(pParent);
130594      pNode->pParent = pParent;
130595    }
130596    pNode->nRef++;
130597    *ppNode = pNode;
130598    return SQLITE_OK;
130599  }
130600
130601  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
130602  rc = sqlite3_step(pRtree->pReadNode);
130603  if( rc==SQLITE_ROW ){
130604    const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
130605    if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
130606      pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
130607      if( !pNode ){
130608        rc2 = SQLITE_NOMEM;
130609      }else{
130610        pNode->pParent = pParent;
130611        pNode->zData = (u8 *)&pNode[1];
130612        pNode->nRef = 1;
130613        pNode->iNode = iNode;
130614        pNode->isDirty = 0;
130615        pNode->pNext = 0;
130616        memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
130617        nodeReference(pParent);
130618      }
130619    }
130620  }
130621  rc = sqlite3_reset(pRtree->pReadNode);
130622  if( rc==SQLITE_OK ) rc = rc2;
130623
130624  /* If the root node was just loaded, set pRtree->iDepth to the height
130625  ** of the r-tree structure. A height of zero means all data is stored on
130626  ** the root node. A height of one means the children of the root node
130627  ** are the leaves, and so on. If the depth as specified on the root node
130628  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
130629  */
130630  if( pNode && iNode==1 ){
130631    pRtree->iDepth = readInt16(pNode->zData);
130632    if( pRtree->iDepth>RTREE_MAX_DEPTH ){
130633      rc = SQLITE_CORRUPT_VTAB;
130634    }
130635  }
130636
130637  /* If no error has occurred so far, check if the "number of entries"
130638  ** field on the node is too large. If so, set the return code to
130639  ** SQLITE_CORRUPT_VTAB.
130640  */
130641  if( pNode && rc==SQLITE_OK ){
130642    if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
130643      rc = SQLITE_CORRUPT_VTAB;
130644    }
130645  }
130646
130647  if( rc==SQLITE_OK ){
130648    if( pNode!=0 ){
130649      nodeHashInsert(pRtree, pNode);
130650    }else{
130651      rc = SQLITE_CORRUPT_VTAB;
130652    }
130653    *ppNode = pNode;
130654  }else{
130655    sqlite3_free(pNode);
130656    *ppNode = 0;
130657  }
130658
130659  return rc;
130660}
130661
130662/*
130663** Overwrite cell iCell of node pNode with the contents of pCell.
130664*/
130665static void nodeOverwriteCell(
130666  Rtree *pRtree,
130667  RtreeNode *pNode,
130668  RtreeCell *pCell,
130669  int iCell
130670){
130671  int ii;
130672  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
130673  p += writeInt64(p, pCell->iRowid);
130674  for(ii=0; ii<(pRtree->nDim*2); ii++){
130675    p += writeCoord(p, &pCell->aCoord[ii]);
130676  }
130677  pNode->isDirty = 1;
130678}
130679
130680/*
130681** Remove cell the cell with index iCell from node pNode.
130682*/
130683static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
130684  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
130685  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
130686  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
130687  memmove(pDst, pSrc, nByte);
130688  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
130689  pNode->isDirty = 1;
130690}
130691
130692/*
130693** Insert the contents of cell pCell into node pNode. If the insert
130694** is successful, return SQLITE_OK.
130695**
130696** If there is not enough free space in pNode, return SQLITE_FULL.
130697*/
130698static int
130699nodeInsertCell(
130700  Rtree *pRtree,
130701  RtreeNode *pNode,
130702  RtreeCell *pCell
130703){
130704  int nCell;                    /* Current number of cells in pNode */
130705  int nMaxCell;                 /* Maximum number of cells for pNode */
130706
130707  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
130708  nCell = NCELL(pNode);
130709
130710  assert( nCell<=nMaxCell );
130711  if( nCell<nMaxCell ){
130712    nodeOverwriteCell(pRtree, pNode, pCell, nCell);
130713    writeInt16(&pNode->zData[2], nCell+1);
130714    pNode->isDirty = 1;
130715  }
130716
130717  return (nCell==nMaxCell);
130718}
130719
130720/*
130721** If the node is dirty, write it out to the database.
130722*/
130723static int
130724nodeWrite(Rtree *pRtree, RtreeNode *pNode){
130725  int rc = SQLITE_OK;
130726  if( pNode->isDirty ){
130727    sqlite3_stmt *p = pRtree->pWriteNode;
130728    if( pNode->iNode ){
130729      sqlite3_bind_int64(p, 1, pNode->iNode);
130730    }else{
130731      sqlite3_bind_null(p, 1);
130732    }
130733    sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
130734    sqlite3_step(p);
130735    pNode->isDirty = 0;
130736    rc = sqlite3_reset(p);
130737    if( pNode->iNode==0 && rc==SQLITE_OK ){
130738      pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
130739      nodeHashInsert(pRtree, pNode);
130740    }
130741  }
130742  return rc;
130743}
130744
130745/*
130746** Release a reference to a node. If the node is dirty and the reference
130747** count drops to zero, the node data is written to the database.
130748*/
130749static int
130750nodeRelease(Rtree *pRtree, RtreeNode *pNode){
130751  int rc = SQLITE_OK;
130752  if( pNode ){
130753    assert( pNode->nRef>0 );
130754    pNode->nRef--;
130755    if( pNode->nRef==0 ){
130756      if( pNode->iNode==1 ){
130757        pRtree->iDepth = -1;
130758      }
130759      if( pNode->pParent ){
130760        rc = nodeRelease(pRtree, pNode->pParent);
130761      }
130762      if( rc==SQLITE_OK ){
130763        rc = nodeWrite(pRtree, pNode);
130764      }
130765      nodeHashDelete(pRtree, pNode);
130766      sqlite3_free(pNode);
130767    }
130768  }
130769  return rc;
130770}
130771
130772/*
130773** Return the 64-bit integer value associated with cell iCell of
130774** node pNode. If pNode is a leaf node, this is a rowid. If it is
130775** an internal node, then the 64-bit integer is a child page number.
130776*/
130777static i64 nodeGetRowid(
130778  Rtree *pRtree,
130779  RtreeNode *pNode,
130780  int iCell
130781){
130782  assert( iCell<NCELL(pNode) );
130783  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
130784}
130785
130786/*
130787** Return coordinate iCoord from cell iCell in node pNode.
130788*/
130789static void nodeGetCoord(
130790  Rtree *pRtree,
130791  RtreeNode *pNode,
130792  int iCell,
130793  int iCoord,
130794  RtreeCoord *pCoord           /* Space to write result to */
130795){
130796  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
130797}
130798
130799/*
130800** Deserialize cell iCell of node pNode. Populate the structure pointed
130801** to by pCell with the results.
130802*/
130803static void nodeGetCell(
130804  Rtree *pRtree,
130805  RtreeNode *pNode,
130806  int iCell,
130807  RtreeCell *pCell
130808){
130809  int ii;
130810  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
130811  for(ii=0; ii<pRtree->nDim*2; ii++){
130812    nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
130813  }
130814}
130815
130816
130817/* Forward declaration for the function that does the work of
130818** the virtual table module xCreate() and xConnect() methods.
130819*/
130820static int rtreeInit(
130821  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
130822);
130823
130824/*
130825** Rtree virtual table module xCreate method.
130826*/
130827static int rtreeCreate(
130828  sqlite3 *db,
130829  void *pAux,
130830  int argc, const char *const*argv,
130831  sqlite3_vtab **ppVtab,
130832  char **pzErr
130833){
130834  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
130835}
130836
130837/*
130838** Rtree virtual table module xConnect method.
130839*/
130840static int rtreeConnect(
130841  sqlite3 *db,
130842  void *pAux,
130843  int argc, const char *const*argv,
130844  sqlite3_vtab **ppVtab,
130845  char **pzErr
130846){
130847  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
130848}
130849
130850/*
130851** Increment the r-tree reference count.
130852*/
130853static void rtreeReference(Rtree *pRtree){
130854  pRtree->nBusy++;
130855}
130856
130857/*
130858** Decrement the r-tree reference count. When the reference count reaches
130859** zero the structure is deleted.
130860*/
130861static void rtreeRelease(Rtree *pRtree){
130862  pRtree->nBusy--;
130863  if( pRtree->nBusy==0 ){
130864    sqlite3_finalize(pRtree->pReadNode);
130865    sqlite3_finalize(pRtree->pWriteNode);
130866    sqlite3_finalize(pRtree->pDeleteNode);
130867    sqlite3_finalize(pRtree->pReadRowid);
130868    sqlite3_finalize(pRtree->pWriteRowid);
130869    sqlite3_finalize(pRtree->pDeleteRowid);
130870    sqlite3_finalize(pRtree->pReadParent);
130871    sqlite3_finalize(pRtree->pWriteParent);
130872    sqlite3_finalize(pRtree->pDeleteParent);
130873    sqlite3_free(pRtree);
130874  }
130875}
130876
130877/*
130878** Rtree virtual table module xDisconnect method.
130879*/
130880static int rtreeDisconnect(sqlite3_vtab *pVtab){
130881  rtreeRelease((Rtree *)pVtab);
130882  return SQLITE_OK;
130883}
130884
130885/*
130886** Rtree virtual table module xDestroy method.
130887*/
130888static int rtreeDestroy(sqlite3_vtab *pVtab){
130889  Rtree *pRtree = (Rtree *)pVtab;
130890  int rc;
130891  char *zCreate = sqlite3_mprintf(
130892    "DROP TABLE '%q'.'%q_node';"
130893    "DROP TABLE '%q'.'%q_rowid';"
130894    "DROP TABLE '%q'.'%q_parent';",
130895    pRtree->zDb, pRtree->zName,
130896    pRtree->zDb, pRtree->zName,
130897    pRtree->zDb, pRtree->zName
130898  );
130899  if( !zCreate ){
130900    rc = SQLITE_NOMEM;
130901  }else{
130902    rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
130903    sqlite3_free(zCreate);
130904  }
130905  if( rc==SQLITE_OK ){
130906    rtreeRelease(pRtree);
130907  }
130908
130909  return rc;
130910}
130911
130912/*
130913** Rtree virtual table module xOpen method.
130914*/
130915static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
130916  int rc = SQLITE_NOMEM;
130917  RtreeCursor *pCsr;
130918
130919  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
130920  if( pCsr ){
130921    memset(pCsr, 0, sizeof(RtreeCursor));
130922    pCsr->base.pVtab = pVTab;
130923    rc = SQLITE_OK;
130924  }
130925  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
130926
130927  return rc;
130928}
130929
130930
130931/*
130932** Free the RtreeCursor.aConstraint[] array and its contents.
130933*/
130934static void freeCursorConstraints(RtreeCursor *pCsr){
130935  if( pCsr->aConstraint ){
130936    int i;                        /* Used to iterate through constraint array */
130937    for(i=0; i<pCsr->nConstraint; i++){
130938      sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
130939      if( pGeom ){
130940        if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
130941        sqlite3_free(pGeom);
130942      }
130943    }
130944    sqlite3_free(pCsr->aConstraint);
130945    pCsr->aConstraint = 0;
130946  }
130947}
130948
130949/*
130950** Rtree virtual table module xClose method.
130951*/
130952static int rtreeClose(sqlite3_vtab_cursor *cur){
130953  Rtree *pRtree = (Rtree *)(cur->pVtab);
130954  int rc;
130955  RtreeCursor *pCsr = (RtreeCursor *)cur;
130956  freeCursorConstraints(pCsr);
130957  rc = nodeRelease(pRtree, pCsr->pNode);
130958  sqlite3_free(pCsr);
130959  return rc;
130960}
130961
130962/*
130963** Rtree virtual table module xEof method.
130964**
130965** Return non-zero if the cursor does not currently point to a valid
130966** record (i.e if the scan has finished), or zero otherwise.
130967*/
130968static int rtreeEof(sqlite3_vtab_cursor *cur){
130969  RtreeCursor *pCsr = (RtreeCursor *)cur;
130970  return (pCsr->pNode==0);
130971}
130972
130973/*
130974** The r-tree constraint passed as the second argument to this function is
130975** guaranteed to be a MATCH constraint.
130976*/
130977static int testRtreeGeom(
130978  Rtree *pRtree,                  /* R-Tree object */
130979  RtreeConstraint *pConstraint,   /* MATCH constraint to test */
130980  RtreeCell *pCell,               /* Cell to test */
130981  int *pbRes                      /* OUT: Test result */
130982){
130983  int i;
130984  double aCoord[RTREE_MAX_DIMENSIONS*2];
130985  int nCoord = pRtree->nDim*2;
130986
130987  assert( pConstraint->op==RTREE_MATCH );
130988  assert( pConstraint->pGeom );
130989
130990  for(i=0; i<nCoord; i++){
130991    aCoord[i] = DCOORD(pCell->aCoord[i]);
130992  }
130993  return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
130994}
130995
130996/*
130997** Cursor pCursor currently points to a cell in a non-leaf page.
130998** Set *pbEof to true if the sub-tree headed by the cell is filtered
130999** (excluded) by the constraints in the pCursor->aConstraint[]
131000** array, or false otherwise.
131001**
131002** Return SQLITE_OK if successful or an SQLite error code if an error
131003** occurs within a geometry callback.
131004*/
131005static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
131006  RtreeCell cell;
131007  int ii;
131008  int bRes = 0;
131009  int rc = SQLITE_OK;
131010
131011  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
131012  for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
131013    RtreeConstraint *p = &pCursor->aConstraint[ii];
131014    double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
131015    double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
131016
131017    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
131018        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
131019    );
131020
131021    switch( p->op ){
131022      case RTREE_LE: case RTREE_LT:
131023        bRes = p->rValue<cell_min;
131024        break;
131025
131026      case RTREE_GE: case RTREE_GT:
131027        bRes = p->rValue>cell_max;
131028        break;
131029
131030      case RTREE_EQ:
131031        bRes = (p->rValue>cell_max || p->rValue<cell_min);
131032        break;
131033
131034      default: {
131035        assert( p->op==RTREE_MATCH );
131036        rc = testRtreeGeom(pRtree, p, &cell, &bRes);
131037        bRes = !bRes;
131038        break;
131039      }
131040    }
131041  }
131042
131043  *pbEof = bRes;
131044  return rc;
131045}
131046
131047/*
131048** Test if the cell that cursor pCursor currently points to
131049** would be filtered (excluded) by the constraints in the
131050** pCursor->aConstraint[] array. If so, set *pbEof to true before
131051** returning. If the cell is not filtered (excluded) by the constraints,
131052** set pbEof to zero.
131053**
131054** Return SQLITE_OK if successful or an SQLite error code if an error
131055** occurs within a geometry callback.
131056**
131057** This function assumes that the cell is part of a leaf node.
131058*/
131059static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
131060  RtreeCell cell;
131061  int ii;
131062  *pbEof = 0;
131063
131064  nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
131065  for(ii=0; ii<pCursor->nConstraint; ii++){
131066    RtreeConstraint *p = &pCursor->aConstraint[ii];
131067    double coord = DCOORD(cell.aCoord[p->iCoord]);
131068    int res;
131069    assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
131070        || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
131071    );
131072    switch( p->op ){
131073      case RTREE_LE: res = (coord<=p->rValue); break;
131074      case RTREE_LT: res = (coord<p->rValue);  break;
131075      case RTREE_GE: res = (coord>=p->rValue); break;
131076      case RTREE_GT: res = (coord>p->rValue);  break;
131077      case RTREE_EQ: res = (coord==p->rValue); break;
131078      default: {
131079        int rc;
131080        assert( p->op==RTREE_MATCH );
131081        rc = testRtreeGeom(pRtree, p, &cell, &res);
131082        if( rc!=SQLITE_OK ){
131083          return rc;
131084        }
131085        break;
131086      }
131087    }
131088
131089    if( !res ){
131090      *pbEof = 1;
131091      return SQLITE_OK;
131092    }
131093  }
131094
131095  return SQLITE_OK;
131096}
131097
131098/*
131099** Cursor pCursor currently points at a node that heads a sub-tree of
131100** height iHeight (if iHeight==0, then the node is a leaf). Descend
131101** to point to the left-most cell of the sub-tree that matches the
131102** configured constraints.
131103*/
131104static int descendToCell(
131105  Rtree *pRtree,
131106  RtreeCursor *pCursor,
131107  int iHeight,
131108  int *pEof                 /* OUT: Set to true if cannot descend */
131109){
131110  int isEof;
131111  int rc;
131112  int ii;
131113  RtreeNode *pChild;
131114  sqlite3_int64 iRowid;
131115
131116  RtreeNode *pSavedNode = pCursor->pNode;
131117  int iSavedCell = pCursor->iCell;
131118
131119  assert( iHeight>=0 );
131120
131121  if( iHeight==0 ){
131122    rc = testRtreeEntry(pRtree, pCursor, &isEof);
131123  }else{
131124    rc = testRtreeCell(pRtree, pCursor, &isEof);
131125  }
131126  if( rc!=SQLITE_OK || isEof || iHeight==0 ){
131127    goto descend_to_cell_out;
131128  }
131129
131130  iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
131131  rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
131132  if( rc!=SQLITE_OK ){
131133    goto descend_to_cell_out;
131134  }
131135
131136  nodeRelease(pRtree, pCursor->pNode);
131137  pCursor->pNode = pChild;
131138  isEof = 1;
131139  for(ii=0; isEof && ii<NCELL(pChild); ii++){
131140    pCursor->iCell = ii;
131141    rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
131142    if( rc!=SQLITE_OK ){
131143      goto descend_to_cell_out;
131144    }
131145  }
131146
131147  if( isEof ){
131148    assert( pCursor->pNode==pChild );
131149    nodeReference(pSavedNode);
131150    nodeRelease(pRtree, pChild);
131151    pCursor->pNode = pSavedNode;
131152    pCursor->iCell = iSavedCell;
131153  }
131154
131155descend_to_cell_out:
131156  *pEof = isEof;
131157  return rc;
131158}
131159
131160/*
131161** One of the cells in node pNode is guaranteed to have a 64-bit
131162** integer value equal to iRowid. Return the index of this cell.
131163*/
131164static int nodeRowidIndex(
131165  Rtree *pRtree,
131166  RtreeNode *pNode,
131167  i64 iRowid,
131168  int *piIndex
131169){
131170  int ii;
131171  int nCell = NCELL(pNode);
131172  for(ii=0; ii<nCell; ii++){
131173    if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
131174      *piIndex = ii;
131175      return SQLITE_OK;
131176    }
131177  }
131178  return SQLITE_CORRUPT_VTAB;
131179}
131180
131181/*
131182** Return the index of the cell containing a pointer to node pNode
131183** in its parent. If pNode is the root node, return -1.
131184*/
131185static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
131186  RtreeNode *pParent = pNode->pParent;
131187  if( pParent ){
131188    return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
131189  }
131190  *piIndex = -1;
131191  return SQLITE_OK;
131192}
131193
131194/*
131195** Rtree virtual table module xNext method.
131196*/
131197static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
131198  Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
131199  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
131200  int rc = SQLITE_OK;
131201
131202  /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
131203  ** already at EOF. It is against the rules to call the xNext() method of
131204  ** a cursor that has already reached EOF.
131205  */
131206  assert( pCsr->pNode );
131207
131208  if( pCsr->iStrategy==1 ){
131209    /* This "scan" is a direct lookup by rowid. There is no next entry. */
131210    nodeRelease(pRtree, pCsr->pNode);
131211    pCsr->pNode = 0;
131212  }else{
131213    /* Move to the next entry that matches the configured constraints. */
131214    int iHeight = 0;
131215    while( pCsr->pNode ){
131216      RtreeNode *pNode = pCsr->pNode;
131217      int nCell = NCELL(pNode);
131218      for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
131219        int isEof;
131220        rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
131221        if( rc!=SQLITE_OK || !isEof ){
131222          return rc;
131223        }
131224      }
131225      pCsr->pNode = pNode->pParent;
131226      rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
131227      if( rc!=SQLITE_OK ){
131228        return rc;
131229      }
131230      nodeReference(pCsr->pNode);
131231      nodeRelease(pRtree, pNode);
131232      iHeight++;
131233    }
131234  }
131235
131236  return rc;
131237}
131238
131239/*
131240** Rtree virtual table module xRowid method.
131241*/
131242static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
131243  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
131244  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
131245
131246  assert(pCsr->pNode);
131247  *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
131248
131249  return SQLITE_OK;
131250}
131251
131252/*
131253** Rtree virtual table module xColumn method.
131254*/
131255static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
131256  Rtree *pRtree = (Rtree *)cur->pVtab;
131257  RtreeCursor *pCsr = (RtreeCursor *)cur;
131258
131259  if( i==0 ){
131260    i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
131261    sqlite3_result_int64(ctx, iRowid);
131262  }else{
131263    RtreeCoord c;
131264    nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
131265    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
131266      sqlite3_result_double(ctx, c.f);
131267    }else{
131268      assert( pRtree->eCoordType==RTREE_COORD_INT32 );
131269      sqlite3_result_int(ctx, c.i);
131270    }
131271  }
131272
131273  return SQLITE_OK;
131274}
131275
131276/*
131277** Use nodeAcquire() to obtain the leaf node containing the record with
131278** rowid iRowid. If successful, set *ppLeaf to point to the node and
131279** return SQLITE_OK. If there is no such record in the table, set
131280** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
131281** to zero and return an SQLite error code.
131282*/
131283static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
131284  int rc;
131285  *ppLeaf = 0;
131286  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
131287  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
131288    i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
131289    rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
131290    sqlite3_reset(pRtree->pReadRowid);
131291  }else{
131292    rc = sqlite3_reset(pRtree->pReadRowid);
131293  }
131294  return rc;
131295}
131296
131297/*
131298** This function is called to configure the RtreeConstraint object passed
131299** as the second argument for a MATCH constraint. The value passed as the
131300** first argument to this function is the right-hand operand to the MATCH
131301** operator.
131302*/
131303static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
131304  RtreeMatchArg *p;
131305  sqlite3_rtree_geometry *pGeom;
131306  int nBlob;
131307
131308  /* Check that value is actually a blob. */
131309  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
131310
131311  /* Check that the blob is roughly the right size. */
131312  nBlob = sqlite3_value_bytes(pValue);
131313  if( nBlob<(int)sizeof(RtreeMatchArg)
131314   || ((nBlob-sizeof(RtreeMatchArg))%sizeof(double))!=0
131315  ){
131316    return SQLITE_ERROR;
131317  }
131318
131319  pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
131320      sizeof(sqlite3_rtree_geometry) + nBlob
131321  );
131322  if( !pGeom ) return SQLITE_NOMEM;
131323  memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
131324  p = (RtreeMatchArg *)&pGeom[1];
131325
131326  memcpy(p, sqlite3_value_blob(pValue), nBlob);
131327  if( p->magic!=RTREE_GEOMETRY_MAGIC
131328   || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(double))
131329  ){
131330    sqlite3_free(pGeom);
131331    return SQLITE_ERROR;
131332  }
131333
131334  pGeom->pContext = p->pContext;
131335  pGeom->nParam = p->nParam;
131336  pGeom->aParam = p->aParam;
131337
131338  pCons->xGeom = p->xGeom;
131339  pCons->pGeom = pGeom;
131340  return SQLITE_OK;
131341}
131342
131343/*
131344** Rtree virtual table module xFilter method.
131345*/
131346static int rtreeFilter(
131347  sqlite3_vtab_cursor *pVtabCursor,
131348  int idxNum, const char *idxStr,
131349  int argc, sqlite3_value **argv
131350){
131351  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
131352  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
131353
131354  RtreeNode *pRoot = 0;
131355  int ii;
131356  int rc = SQLITE_OK;
131357
131358  rtreeReference(pRtree);
131359
131360  freeCursorConstraints(pCsr);
131361  pCsr->iStrategy = idxNum;
131362
131363  if( idxNum==1 ){
131364    /* Special case - lookup by rowid. */
131365    RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
131366    i64 iRowid = sqlite3_value_int64(argv[0]);
131367    rc = findLeafNode(pRtree, iRowid, &pLeaf);
131368    pCsr->pNode = pLeaf;
131369    if( pLeaf ){
131370      assert( rc==SQLITE_OK );
131371      rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
131372    }
131373  }else{
131374    /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
131375    ** with the configured constraints.
131376    */
131377    if( argc>0 ){
131378      pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
131379      pCsr->nConstraint = argc;
131380      if( !pCsr->aConstraint ){
131381        rc = SQLITE_NOMEM;
131382      }else{
131383        memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
131384        assert( (idxStr==0 && argc==0)
131385                || (idxStr && (int)strlen(idxStr)==argc*2) );
131386        for(ii=0; ii<argc; ii++){
131387          RtreeConstraint *p = &pCsr->aConstraint[ii];
131388          p->op = idxStr[ii*2];
131389          p->iCoord = idxStr[ii*2+1]-'a';
131390          if( p->op==RTREE_MATCH ){
131391            /* A MATCH operator. The right-hand-side must be a blob that
131392            ** can be cast into an RtreeMatchArg object. One created using
131393            ** an sqlite3_rtree_geometry_callback() SQL user function.
131394            */
131395            rc = deserializeGeometry(argv[ii], p);
131396            if( rc!=SQLITE_OK ){
131397              break;
131398            }
131399          }else{
131400            p->rValue = sqlite3_value_double(argv[ii]);
131401          }
131402        }
131403      }
131404    }
131405
131406    if( rc==SQLITE_OK ){
131407      pCsr->pNode = 0;
131408      rc = nodeAcquire(pRtree, 1, 0, &pRoot);
131409    }
131410    if( rc==SQLITE_OK ){
131411      int isEof = 1;
131412      int nCell = NCELL(pRoot);
131413      pCsr->pNode = pRoot;
131414      for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
131415        assert( pCsr->pNode==pRoot );
131416        rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
131417        if( !isEof ){
131418          break;
131419        }
131420      }
131421      if( rc==SQLITE_OK && isEof ){
131422        assert( pCsr->pNode==pRoot );
131423        nodeRelease(pRtree, pRoot);
131424        pCsr->pNode = 0;
131425      }
131426      assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
131427    }
131428  }
131429
131430  rtreeRelease(pRtree);
131431  return rc;
131432}
131433
131434/*
131435** Rtree virtual table module xBestIndex method. There are three
131436** table scan strategies to choose from (in order from most to
131437** least desirable):
131438**
131439**   idxNum     idxStr        Strategy
131440**   ------------------------------------------------
131441**     1        Unused        Direct lookup by rowid.
131442**     2        See below     R-tree query or full-table scan.
131443**   ------------------------------------------------
131444**
131445** If strategy 1 is used, then idxStr is not meaningful. If strategy
131446** 2 is used, idxStr is formatted to contain 2 bytes for each
131447** constraint used. The first two bytes of idxStr correspond to
131448** the constraint in sqlite3_index_info.aConstraintUsage[] with
131449** (argvIndex==1) etc.
131450**
131451** The first of each pair of bytes in idxStr identifies the constraint
131452** operator as follows:
131453**
131454**   Operator    Byte Value
131455**   ----------------------
131456**      =        0x41 ('A')
131457**     <=        0x42 ('B')
131458**      <        0x43 ('C')
131459**     >=        0x44 ('D')
131460**      >        0x45 ('E')
131461**   MATCH       0x46 ('F')
131462**   ----------------------
131463**
131464** The second of each pair of bytes identifies the coordinate column
131465** to which the constraint applies. The leftmost coordinate column
131466** is 'a', the second from the left 'b' etc.
131467*/
131468static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
131469  int rc = SQLITE_OK;
131470  int ii;
131471
131472  int iIdx = 0;
131473  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
131474  memset(zIdxStr, 0, sizeof(zIdxStr));
131475  UNUSED_PARAMETER(tab);
131476
131477  assert( pIdxInfo->idxStr==0 );
131478  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
131479    struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
131480
131481    if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
131482      /* We have an equality constraint on the rowid. Use strategy 1. */
131483      int jj;
131484      for(jj=0; jj<ii; jj++){
131485        pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
131486        pIdxInfo->aConstraintUsage[jj].omit = 0;
131487      }
131488      pIdxInfo->idxNum = 1;
131489      pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
131490      pIdxInfo->aConstraintUsage[jj].omit = 1;
131491
131492      /* This strategy involves a two rowid lookups on an B-Tree structures
131493      ** and then a linear search of an R-Tree node. This should be
131494      ** considered almost as quick as a direct rowid lookup (for which
131495      ** sqlite uses an internal cost of 0.0).
131496      */
131497      pIdxInfo->estimatedCost = 10.0;
131498      return SQLITE_OK;
131499    }
131500
131501    if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
131502      u8 op;
131503      switch( p->op ){
131504        case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
131505        case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
131506        case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
131507        case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
131508        case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
131509        default:
131510          assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
131511          op = RTREE_MATCH;
131512          break;
131513      }
131514      zIdxStr[iIdx++] = op;
131515      zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
131516      pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
131517      pIdxInfo->aConstraintUsage[ii].omit = 1;
131518    }
131519  }
131520
131521  pIdxInfo->idxNum = 2;
131522  pIdxInfo->needToFreeIdxStr = 1;
131523  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
131524    return SQLITE_NOMEM;
131525  }
131526  assert( iIdx>=0 );
131527  pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
131528  return rc;
131529}
131530
131531/*
131532** Return the N-dimensional volumn of the cell stored in *p.
131533*/
131534static float cellArea(Rtree *pRtree, RtreeCell *p){
131535  float area = 1.0;
131536  int ii;
131537  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131538    area = (float)(area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
131539  }
131540  return area;
131541}
131542
131543/*
131544** Return the margin length of cell p. The margin length is the sum
131545** of the objects size in each dimension.
131546*/
131547static float cellMargin(Rtree *pRtree, RtreeCell *p){
131548  float margin = 0.0;
131549  int ii;
131550  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131551    margin += (float)(DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
131552  }
131553  return margin;
131554}
131555
131556/*
131557** Store the union of cells p1 and p2 in p1.
131558*/
131559static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
131560  int ii;
131561  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
131562    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131563      p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
131564      p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
131565    }
131566  }else{
131567    for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131568      p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
131569      p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
131570    }
131571  }
131572}
131573
131574/*
131575** Return true if the area covered by p2 is a subset of the area covered
131576** by p1. False otherwise.
131577*/
131578static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
131579  int ii;
131580  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
131581  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
131582    RtreeCoord *a1 = &p1->aCoord[ii];
131583    RtreeCoord *a2 = &p2->aCoord[ii];
131584    if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
131585     || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
131586    ){
131587      return 0;
131588    }
131589  }
131590  return 1;
131591}
131592
131593/*
131594** Return the amount cell p would grow by if it were unioned with pCell.
131595*/
131596static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
131597  float area;
131598  RtreeCell cell;
131599  memcpy(&cell, p, sizeof(RtreeCell));
131600  area = cellArea(pRtree, &cell);
131601  cellUnion(pRtree, &cell, pCell);
131602  return (cellArea(pRtree, &cell)-area);
131603}
131604
131605#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
131606static float cellOverlap(
131607  Rtree *pRtree,
131608  RtreeCell *p,
131609  RtreeCell *aCell,
131610  int nCell,
131611  int iExclude
131612){
131613  int ii;
131614  float overlap = 0.0;
131615  for(ii=0; ii<nCell; ii++){
131616#if VARIANT_RSTARTREE_CHOOSESUBTREE
131617    if( ii!=iExclude )
131618#else
131619    assert( iExclude==-1 );
131620    UNUSED_PARAMETER(iExclude);
131621#endif
131622    {
131623      int jj;
131624      float o = 1.0;
131625      for(jj=0; jj<(pRtree->nDim*2); jj+=2){
131626        double x1;
131627        double x2;
131628
131629        x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
131630        x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
131631
131632        if( x2<x1 ){
131633          o = 0.0;
131634          break;
131635        }else{
131636          o = o * (float)(x2-x1);
131637        }
131638      }
131639      overlap += o;
131640    }
131641  }
131642  return overlap;
131643}
131644#endif
131645
131646#if VARIANT_RSTARTREE_CHOOSESUBTREE
131647static float cellOverlapEnlargement(
131648  Rtree *pRtree,
131649  RtreeCell *p,
131650  RtreeCell *pInsert,
131651  RtreeCell *aCell,
131652  int nCell,
131653  int iExclude
131654){
131655  double before;
131656  double after;
131657  before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
131658  cellUnion(pRtree, p, pInsert);
131659  after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
131660  return (float)(after-before);
131661}
131662#endif
131663
131664
131665/*
131666** This function implements the ChooseLeaf algorithm from Gutman[84].
131667** ChooseSubTree in r*tree terminology.
131668*/
131669static int ChooseLeaf(
131670  Rtree *pRtree,               /* Rtree table */
131671  RtreeCell *pCell,            /* Cell to insert into rtree */
131672  int iHeight,                 /* Height of sub-tree rooted at pCell */
131673  RtreeNode **ppLeaf           /* OUT: Selected leaf page */
131674){
131675  int rc;
131676  int ii;
131677  RtreeNode *pNode;
131678  rc = nodeAcquire(pRtree, 1, 0, &pNode);
131679
131680  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
131681    int iCell;
131682    sqlite3_int64 iBest = 0;
131683
131684    float fMinGrowth = 0.0;
131685    float fMinArea = 0.0;
131686#if VARIANT_RSTARTREE_CHOOSESUBTREE
131687    float fMinOverlap = 0.0;
131688    float overlap;
131689#endif
131690
131691    int nCell = NCELL(pNode);
131692    RtreeCell cell;
131693    RtreeNode *pChild;
131694
131695    RtreeCell *aCell = 0;
131696
131697#if VARIANT_RSTARTREE_CHOOSESUBTREE
131698    if( ii==(pRtree->iDepth-1) ){
131699      int jj;
131700      aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
131701      if( !aCell ){
131702        rc = SQLITE_NOMEM;
131703        nodeRelease(pRtree, pNode);
131704        pNode = 0;
131705        continue;
131706      }
131707      for(jj=0; jj<nCell; jj++){
131708        nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
131709      }
131710    }
131711#endif
131712
131713    /* Select the child node which will be enlarged the least if pCell
131714    ** is inserted into it. Resolve ties by choosing the entry with
131715    ** the smallest area.
131716    */
131717    for(iCell=0; iCell<nCell; iCell++){
131718      int bBest = 0;
131719      float growth;
131720      float area;
131721      nodeGetCell(pRtree, pNode, iCell, &cell);
131722      growth = cellGrowth(pRtree, &cell, pCell);
131723      area = cellArea(pRtree, &cell);
131724
131725#if VARIANT_RSTARTREE_CHOOSESUBTREE
131726      if( ii==(pRtree->iDepth-1) ){
131727        overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
131728      }else{
131729        overlap = 0.0;
131730      }
131731      if( (iCell==0)
131732       || (overlap<fMinOverlap)
131733       || (overlap==fMinOverlap && growth<fMinGrowth)
131734       || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
131735      ){
131736        bBest = 1;
131737        fMinOverlap = overlap;
131738      }
131739#else
131740      if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
131741        bBest = 1;
131742      }
131743#endif
131744      if( bBest ){
131745        fMinGrowth = growth;
131746        fMinArea = area;
131747        iBest = cell.iRowid;
131748      }
131749    }
131750
131751    sqlite3_free(aCell);
131752    rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
131753    nodeRelease(pRtree, pNode);
131754    pNode = pChild;
131755  }
131756
131757  *ppLeaf = pNode;
131758  return rc;
131759}
131760
131761/*
131762** A cell with the same content as pCell has just been inserted into
131763** the node pNode. This function updates the bounding box cells in
131764** all ancestor elements.
131765*/
131766static int AdjustTree(
131767  Rtree *pRtree,                    /* Rtree table */
131768  RtreeNode *pNode,                 /* Adjust ancestry of this node. */
131769  RtreeCell *pCell                  /* This cell was just inserted */
131770){
131771  RtreeNode *p = pNode;
131772  while( p->pParent ){
131773    RtreeNode *pParent = p->pParent;
131774    RtreeCell cell;
131775    int iCell;
131776
131777    if( nodeParentIndex(pRtree, p, &iCell) ){
131778      return SQLITE_CORRUPT_VTAB;
131779    }
131780
131781    nodeGetCell(pRtree, pParent, iCell, &cell);
131782    if( !cellContains(pRtree, &cell, pCell) ){
131783      cellUnion(pRtree, &cell, pCell);
131784      nodeOverwriteCell(pRtree, pParent, &cell, iCell);
131785    }
131786
131787    p = pParent;
131788  }
131789  return SQLITE_OK;
131790}
131791
131792/*
131793** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
131794*/
131795static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
131796  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
131797  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
131798  sqlite3_step(pRtree->pWriteRowid);
131799  return sqlite3_reset(pRtree->pWriteRowid);
131800}
131801
131802/*
131803** Write mapping (iNode->iPar) to the <rtree>_parent table.
131804*/
131805static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
131806  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
131807  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
131808  sqlite3_step(pRtree->pWriteParent);
131809  return sqlite3_reset(pRtree->pWriteParent);
131810}
131811
131812static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
131813
131814#if VARIANT_GUTTMAN_LINEAR_SPLIT
131815/*
131816** Implementation of the linear variant of the PickNext() function from
131817** Guttman[84].
131818*/
131819static RtreeCell *LinearPickNext(
131820  Rtree *pRtree,
131821  RtreeCell *aCell,
131822  int nCell,
131823  RtreeCell *pLeftBox,
131824  RtreeCell *pRightBox,
131825  int *aiUsed
131826){
131827  int ii;
131828  for(ii=0; aiUsed[ii]; ii++);
131829  aiUsed[ii] = 1;
131830  return &aCell[ii];
131831}
131832
131833/*
131834** Implementation of the linear variant of the PickSeeds() function from
131835** Guttman[84].
131836*/
131837static void LinearPickSeeds(
131838  Rtree *pRtree,
131839  RtreeCell *aCell,
131840  int nCell,
131841  int *piLeftSeed,
131842  int *piRightSeed
131843){
131844  int i;
131845  int iLeftSeed = 0;
131846  int iRightSeed = 1;
131847  float maxNormalInnerWidth = 0.0;
131848
131849  /* Pick two "seed" cells from the array of cells. The algorithm used
131850  ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
131851  ** indices of the two seed cells in the array are stored in local
131852  ** variables iLeftSeek and iRightSeed.
131853  */
131854  for(i=0; i<pRtree->nDim; i++){
131855    float x1 = DCOORD(aCell[0].aCoord[i*2]);
131856    float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
131857    float x3 = x1;
131858    float x4 = x2;
131859    int jj;
131860
131861    int iCellLeft = 0;
131862    int iCellRight = 0;
131863
131864    for(jj=1; jj<nCell; jj++){
131865      float left = DCOORD(aCell[jj].aCoord[i*2]);
131866      float right = DCOORD(aCell[jj].aCoord[i*2+1]);
131867
131868      if( left<x1 ) x1 = left;
131869      if( right>x4 ) x4 = right;
131870      if( left>x3 ){
131871        x3 = left;
131872        iCellRight = jj;
131873      }
131874      if( right<x2 ){
131875        x2 = right;
131876        iCellLeft = jj;
131877      }
131878    }
131879
131880    if( x4!=x1 ){
131881      float normalwidth = (x3 - x2) / (x4 - x1);
131882      if( normalwidth>maxNormalInnerWidth ){
131883        iLeftSeed = iCellLeft;
131884        iRightSeed = iCellRight;
131885      }
131886    }
131887  }
131888
131889  *piLeftSeed = iLeftSeed;
131890  *piRightSeed = iRightSeed;
131891}
131892#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
131893
131894#if VARIANT_GUTTMAN_QUADRATIC_SPLIT
131895/*
131896** Implementation of the quadratic variant of the PickNext() function from
131897** Guttman[84].
131898*/
131899static RtreeCell *QuadraticPickNext(
131900  Rtree *pRtree,
131901  RtreeCell *aCell,
131902  int nCell,
131903  RtreeCell *pLeftBox,
131904  RtreeCell *pRightBox,
131905  int *aiUsed
131906){
131907  #define FABS(a) ((a)<0.0?-1.0*(a):(a))
131908
131909  int iSelect = -1;
131910  float fDiff;
131911  int ii;
131912  for(ii=0; ii<nCell; ii++){
131913    if( aiUsed[ii]==0 ){
131914      float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
131915      float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
131916      float diff = FABS(right-left);
131917      if( iSelect<0 || diff>fDiff ){
131918        fDiff = diff;
131919        iSelect = ii;
131920      }
131921    }
131922  }
131923  aiUsed[iSelect] = 1;
131924  return &aCell[iSelect];
131925}
131926
131927/*
131928** Implementation of the quadratic variant of the PickSeeds() function from
131929** Guttman[84].
131930*/
131931static void QuadraticPickSeeds(
131932  Rtree *pRtree,
131933  RtreeCell *aCell,
131934  int nCell,
131935  int *piLeftSeed,
131936  int *piRightSeed
131937){
131938  int ii;
131939  int jj;
131940
131941  int iLeftSeed = 0;
131942  int iRightSeed = 1;
131943  float fWaste = 0.0;
131944
131945  for(ii=0; ii<nCell; ii++){
131946    for(jj=ii+1; jj<nCell; jj++){
131947      float right = cellArea(pRtree, &aCell[jj]);
131948      float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
131949      float waste = growth - right;
131950
131951      if( waste>fWaste ){
131952        iLeftSeed = ii;
131953        iRightSeed = jj;
131954        fWaste = waste;
131955      }
131956    }
131957  }
131958
131959  *piLeftSeed = iLeftSeed;
131960  *piRightSeed = iRightSeed;
131961}
131962#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
131963
131964/*
131965** Arguments aIdx, aDistance and aSpare all point to arrays of size
131966** nIdx. The aIdx array contains the set of integers from 0 to
131967** (nIdx-1) in no particular order. This function sorts the values
131968** in aIdx according to the indexed values in aDistance. For
131969** example, assuming the inputs:
131970**
131971**   aIdx      = { 0,   1,   2,   3 }
131972**   aDistance = { 5.0, 2.0, 7.0, 6.0 }
131973**
131974** this function sets the aIdx array to contain:
131975**
131976**   aIdx      = { 0,   1,   2,   3 }
131977**
131978** The aSpare array is used as temporary working space by the
131979** sorting algorithm.
131980*/
131981static void SortByDistance(
131982  int *aIdx,
131983  int nIdx,
131984  float *aDistance,
131985  int *aSpare
131986){
131987  if( nIdx>1 ){
131988    int iLeft = 0;
131989    int iRight = 0;
131990
131991    int nLeft = nIdx/2;
131992    int nRight = nIdx-nLeft;
131993    int *aLeft = aIdx;
131994    int *aRight = &aIdx[nLeft];
131995
131996    SortByDistance(aLeft, nLeft, aDistance, aSpare);
131997    SortByDistance(aRight, nRight, aDistance, aSpare);
131998
131999    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
132000    aLeft = aSpare;
132001
132002    while( iLeft<nLeft || iRight<nRight ){
132003      if( iLeft==nLeft ){
132004        aIdx[iLeft+iRight] = aRight[iRight];
132005        iRight++;
132006      }else if( iRight==nRight ){
132007        aIdx[iLeft+iRight] = aLeft[iLeft];
132008        iLeft++;
132009      }else{
132010        float fLeft = aDistance[aLeft[iLeft]];
132011        float fRight = aDistance[aRight[iRight]];
132012        if( fLeft<fRight ){
132013          aIdx[iLeft+iRight] = aLeft[iLeft];
132014          iLeft++;
132015        }else{
132016          aIdx[iLeft+iRight] = aRight[iRight];
132017          iRight++;
132018        }
132019      }
132020    }
132021
132022#if 0
132023    /* Check that the sort worked */
132024    {
132025      int jj;
132026      for(jj=1; jj<nIdx; jj++){
132027        float left = aDistance[aIdx[jj-1]];
132028        float right = aDistance[aIdx[jj]];
132029        assert( left<=right );
132030      }
132031    }
132032#endif
132033  }
132034}
132035
132036/*
132037** Arguments aIdx, aCell and aSpare all point to arrays of size
132038** nIdx. The aIdx array contains the set of integers from 0 to
132039** (nIdx-1) in no particular order. This function sorts the values
132040** in aIdx according to dimension iDim of the cells in aCell. The
132041** minimum value of dimension iDim is considered first, the
132042** maximum used to break ties.
132043**
132044** The aSpare array is used as temporary working space by the
132045** sorting algorithm.
132046*/
132047static void SortByDimension(
132048  Rtree *pRtree,
132049  int *aIdx,
132050  int nIdx,
132051  int iDim,
132052  RtreeCell *aCell,
132053  int *aSpare
132054){
132055  if( nIdx>1 ){
132056
132057    int iLeft = 0;
132058    int iRight = 0;
132059
132060    int nLeft = nIdx/2;
132061    int nRight = nIdx-nLeft;
132062    int *aLeft = aIdx;
132063    int *aRight = &aIdx[nLeft];
132064
132065    SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
132066    SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
132067
132068    memcpy(aSpare, aLeft, sizeof(int)*nLeft);
132069    aLeft = aSpare;
132070    while( iLeft<nLeft || iRight<nRight ){
132071      double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
132072      double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
132073      double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
132074      double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
132075      if( (iLeft!=nLeft) && ((iRight==nRight)
132076       || (xleft1<xright1)
132077       || (xleft1==xright1 && xleft2<xright2)
132078      )){
132079        aIdx[iLeft+iRight] = aLeft[iLeft];
132080        iLeft++;
132081      }else{
132082        aIdx[iLeft+iRight] = aRight[iRight];
132083        iRight++;
132084      }
132085    }
132086
132087#if 0
132088    /* Check that the sort worked */
132089    {
132090      int jj;
132091      for(jj=1; jj<nIdx; jj++){
132092        float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
132093        float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
132094        float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
132095        float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
132096        assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
132097      }
132098    }
132099#endif
132100  }
132101}
132102
132103#if VARIANT_RSTARTREE_SPLIT
132104/*
132105** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
132106*/
132107static int splitNodeStartree(
132108  Rtree *pRtree,
132109  RtreeCell *aCell,
132110  int nCell,
132111  RtreeNode *pLeft,
132112  RtreeNode *pRight,
132113  RtreeCell *pBboxLeft,
132114  RtreeCell *pBboxRight
132115){
132116  int **aaSorted;
132117  int *aSpare;
132118  int ii;
132119
132120  int iBestDim = 0;
132121  int iBestSplit = 0;
132122  float fBestMargin = 0.0;
132123
132124  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
132125
132126  aaSorted = (int **)sqlite3_malloc(nByte);
132127  if( !aaSorted ){
132128    return SQLITE_NOMEM;
132129  }
132130
132131  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
132132  memset(aaSorted, 0, nByte);
132133  for(ii=0; ii<pRtree->nDim; ii++){
132134    int jj;
132135    aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
132136    for(jj=0; jj<nCell; jj++){
132137      aaSorted[ii][jj] = jj;
132138    }
132139    SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
132140  }
132141
132142  for(ii=0; ii<pRtree->nDim; ii++){
132143    float margin = 0.0;
132144    float fBestOverlap = 0.0;
132145    float fBestArea = 0.0;
132146    int iBestLeft = 0;
132147    int nLeft;
132148
132149    for(
132150      nLeft=RTREE_MINCELLS(pRtree);
132151      nLeft<=(nCell-RTREE_MINCELLS(pRtree));
132152      nLeft++
132153    ){
132154      RtreeCell left;
132155      RtreeCell right;
132156      int kk;
132157      float overlap;
132158      float area;
132159
132160      memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
132161      memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
132162      for(kk=1; kk<(nCell-1); kk++){
132163        if( kk<nLeft ){
132164          cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
132165        }else{
132166          cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
132167        }
132168      }
132169      margin += cellMargin(pRtree, &left);
132170      margin += cellMargin(pRtree, &right);
132171      overlap = cellOverlap(pRtree, &left, &right, 1, -1);
132172      area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
132173      if( (nLeft==RTREE_MINCELLS(pRtree))
132174       || (overlap<fBestOverlap)
132175       || (overlap==fBestOverlap && area<fBestArea)
132176      ){
132177        iBestLeft = nLeft;
132178        fBestOverlap = overlap;
132179        fBestArea = area;
132180      }
132181    }
132182
132183    if( ii==0 || margin<fBestMargin ){
132184      iBestDim = ii;
132185      fBestMargin = margin;
132186      iBestSplit = iBestLeft;
132187    }
132188  }
132189
132190  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
132191  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
132192  for(ii=0; ii<nCell; ii++){
132193    RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
132194    RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
132195    RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
132196    nodeInsertCell(pRtree, pTarget, pCell);
132197    cellUnion(pRtree, pBbox, pCell);
132198  }
132199
132200  sqlite3_free(aaSorted);
132201  return SQLITE_OK;
132202}
132203#endif
132204
132205#if VARIANT_GUTTMAN_SPLIT
132206/*
132207** Implementation of the regular R-tree SplitNode from Guttman[1984].
132208*/
132209static int splitNodeGuttman(
132210  Rtree *pRtree,
132211  RtreeCell *aCell,
132212  int nCell,
132213  RtreeNode *pLeft,
132214  RtreeNode *pRight,
132215  RtreeCell *pBboxLeft,
132216  RtreeCell *pBboxRight
132217){
132218  int iLeftSeed = 0;
132219  int iRightSeed = 1;
132220  int *aiUsed;
132221  int i;
132222
132223  aiUsed = sqlite3_malloc(sizeof(int)*nCell);
132224  if( !aiUsed ){
132225    return SQLITE_NOMEM;
132226  }
132227  memset(aiUsed, 0, sizeof(int)*nCell);
132228
132229  PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
132230
132231  memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
132232  memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
132233  nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
132234  nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
132235  aiUsed[iLeftSeed] = 1;
132236  aiUsed[iRightSeed] = 1;
132237
132238  for(i=nCell-2; i>0; i--){
132239    RtreeCell *pNext;
132240    pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
132241    float diff =
132242      cellGrowth(pRtree, pBboxLeft, pNext) -
132243      cellGrowth(pRtree, pBboxRight, pNext)
132244    ;
132245    if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
132246     || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
132247    ){
132248      nodeInsertCell(pRtree, pRight, pNext);
132249      cellUnion(pRtree, pBboxRight, pNext);
132250    }else{
132251      nodeInsertCell(pRtree, pLeft, pNext);
132252      cellUnion(pRtree, pBboxLeft, pNext);
132253    }
132254  }
132255
132256  sqlite3_free(aiUsed);
132257  return SQLITE_OK;
132258}
132259#endif
132260
132261static int updateMapping(
132262  Rtree *pRtree,
132263  i64 iRowid,
132264  RtreeNode *pNode,
132265  int iHeight
132266){
132267  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
132268  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
132269  if( iHeight>0 ){
132270    RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
132271    if( pChild ){
132272      nodeRelease(pRtree, pChild->pParent);
132273      nodeReference(pNode);
132274      pChild->pParent = pNode;
132275    }
132276  }
132277  return xSetMapping(pRtree, iRowid, pNode->iNode);
132278}
132279
132280static int SplitNode(
132281  Rtree *pRtree,
132282  RtreeNode *pNode,
132283  RtreeCell *pCell,
132284  int iHeight
132285){
132286  int i;
132287  int newCellIsRight = 0;
132288
132289  int rc = SQLITE_OK;
132290  int nCell = NCELL(pNode);
132291  RtreeCell *aCell;
132292  int *aiUsed;
132293
132294  RtreeNode *pLeft = 0;
132295  RtreeNode *pRight = 0;
132296
132297  RtreeCell leftbbox;
132298  RtreeCell rightbbox;
132299
132300  /* Allocate an array and populate it with a copy of pCell and
132301  ** all cells from node pLeft. Then zero the original node.
132302  */
132303  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
132304  if( !aCell ){
132305    rc = SQLITE_NOMEM;
132306    goto splitnode_out;
132307  }
132308  aiUsed = (int *)&aCell[nCell+1];
132309  memset(aiUsed, 0, sizeof(int)*(nCell+1));
132310  for(i=0; i<nCell; i++){
132311    nodeGetCell(pRtree, pNode, i, &aCell[i]);
132312  }
132313  nodeZero(pRtree, pNode);
132314  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
132315  nCell++;
132316
132317  if( pNode->iNode==1 ){
132318    pRight = nodeNew(pRtree, pNode);
132319    pLeft = nodeNew(pRtree, pNode);
132320    pRtree->iDepth++;
132321    pNode->isDirty = 1;
132322    writeInt16(pNode->zData, pRtree->iDepth);
132323  }else{
132324    pLeft = pNode;
132325    pRight = nodeNew(pRtree, pLeft->pParent);
132326    nodeReference(pLeft);
132327  }
132328
132329  if( !pLeft || !pRight ){
132330    rc = SQLITE_NOMEM;
132331    goto splitnode_out;
132332  }
132333
132334  memset(pLeft->zData, 0, pRtree->iNodeSize);
132335  memset(pRight->zData, 0, pRtree->iNodeSize);
132336
132337  rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
132338  if( rc!=SQLITE_OK ){
132339    goto splitnode_out;
132340  }
132341
132342  /* Ensure both child nodes have node numbers assigned to them by calling
132343  ** nodeWrite(). Node pRight always needs a node number, as it was created
132344  ** by nodeNew() above. But node pLeft sometimes already has a node number.
132345  ** In this case avoid the all to nodeWrite().
132346  */
132347  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
132348   || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
132349  ){
132350    goto splitnode_out;
132351  }
132352
132353  rightbbox.iRowid = pRight->iNode;
132354  leftbbox.iRowid = pLeft->iNode;
132355
132356  if( pNode->iNode==1 ){
132357    rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
132358    if( rc!=SQLITE_OK ){
132359      goto splitnode_out;
132360    }
132361  }else{
132362    RtreeNode *pParent = pLeft->pParent;
132363    int iCell;
132364    rc = nodeParentIndex(pRtree, pLeft, &iCell);
132365    if( rc==SQLITE_OK ){
132366      nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
132367      rc = AdjustTree(pRtree, pParent, &leftbbox);
132368    }
132369    if( rc!=SQLITE_OK ){
132370      goto splitnode_out;
132371    }
132372  }
132373  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
132374    goto splitnode_out;
132375  }
132376
132377  for(i=0; i<NCELL(pRight); i++){
132378    i64 iRowid = nodeGetRowid(pRtree, pRight, i);
132379    rc = updateMapping(pRtree, iRowid, pRight, iHeight);
132380    if( iRowid==pCell->iRowid ){
132381      newCellIsRight = 1;
132382    }
132383    if( rc!=SQLITE_OK ){
132384      goto splitnode_out;
132385    }
132386  }
132387  if( pNode->iNode==1 ){
132388    for(i=0; i<NCELL(pLeft); i++){
132389      i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
132390      rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
132391      if( rc!=SQLITE_OK ){
132392        goto splitnode_out;
132393      }
132394    }
132395  }else if( newCellIsRight==0 ){
132396    rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
132397  }
132398
132399  if( rc==SQLITE_OK ){
132400    rc = nodeRelease(pRtree, pRight);
132401    pRight = 0;
132402  }
132403  if( rc==SQLITE_OK ){
132404    rc = nodeRelease(pRtree, pLeft);
132405    pLeft = 0;
132406  }
132407
132408splitnode_out:
132409  nodeRelease(pRtree, pRight);
132410  nodeRelease(pRtree, pLeft);
132411  sqlite3_free(aCell);
132412  return rc;
132413}
132414
132415/*
132416** If node pLeaf is not the root of the r-tree and its pParent pointer is
132417** still NULL, load all ancestor nodes of pLeaf into memory and populate
132418** the pLeaf->pParent chain all the way up to the root node.
132419**
132420** This operation is required when a row is deleted (or updated - an update
132421** is implemented as a delete followed by an insert). SQLite provides the
132422** rowid of the row to delete, which can be used to find the leaf on which
132423** the entry resides (argument pLeaf). Once the leaf is located, this
132424** function is called to determine its ancestry.
132425*/
132426static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
132427  int rc = SQLITE_OK;
132428  RtreeNode *pChild = pLeaf;
132429  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
132430    int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
132431    sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
132432    rc = sqlite3_step(pRtree->pReadParent);
132433    if( rc==SQLITE_ROW ){
132434      RtreeNode *pTest;           /* Used to test for reference loops */
132435      i64 iNode;                  /* Node number of parent node */
132436
132437      /* Before setting pChild->pParent, test that we are not creating a
132438      ** loop of references (as we would if, say, pChild==pParent). We don't
132439      ** want to do this as it leads to a memory leak when trying to delete
132440      ** the referenced counted node structures.
132441      */
132442      iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
132443      for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
132444      if( !pTest ){
132445        rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
132446      }
132447    }
132448    rc = sqlite3_reset(pRtree->pReadParent);
132449    if( rc==SQLITE_OK ) rc = rc2;
132450    if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
132451    pChild = pChild->pParent;
132452  }
132453  return rc;
132454}
132455
132456static int deleteCell(Rtree *, RtreeNode *, int, int);
132457
132458static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
132459  int rc;
132460  int rc2;
132461  RtreeNode *pParent = 0;
132462  int iCell;
132463
132464  assert( pNode->nRef==1 );
132465
132466  /* Remove the entry in the parent cell. */
132467  rc = nodeParentIndex(pRtree, pNode, &iCell);
132468  if( rc==SQLITE_OK ){
132469    pParent = pNode->pParent;
132470    pNode->pParent = 0;
132471    rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
132472  }
132473  rc2 = nodeRelease(pRtree, pParent);
132474  if( rc==SQLITE_OK ){
132475    rc = rc2;
132476  }
132477  if( rc!=SQLITE_OK ){
132478    return rc;
132479  }
132480
132481  /* Remove the xxx_node entry. */
132482  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
132483  sqlite3_step(pRtree->pDeleteNode);
132484  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
132485    return rc;
132486  }
132487
132488  /* Remove the xxx_parent entry. */
132489  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
132490  sqlite3_step(pRtree->pDeleteParent);
132491  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
132492    return rc;
132493  }
132494
132495  /* Remove the node from the in-memory hash table and link it into
132496  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
132497  */
132498  nodeHashDelete(pRtree, pNode);
132499  pNode->iNode = iHeight;
132500  pNode->pNext = pRtree->pDeleted;
132501  pNode->nRef++;
132502  pRtree->pDeleted = pNode;
132503
132504  return SQLITE_OK;
132505}
132506
132507static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
132508  RtreeNode *pParent = pNode->pParent;
132509  int rc = SQLITE_OK;
132510  if( pParent ){
132511    int ii;
132512    int nCell = NCELL(pNode);
132513    RtreeCell box;                            /* Bounding box for pNode */
132514    nodeGetCell(pRtree, pNode, 0, &box);
132515    for(ii=1; ii<nCell; ii++){
132516      RtreeCell cell;
132517      nodeGetCell(pRtree, pNode, ii, &cell);
132518      cellUnion(pRtree, &box, &cell);
132519    }
132520    box.iRowid = pNode->iNode;
132521    rc = nodeParentIndex(pRtree, pNode, &ii);
132522    if( rc==SQLITE_OK ){
132523      nodeOverwriteCell(pRtree, pParent, &box, ii);
132524      rc = fixBoundingBox(pRtree, pParent);
132525    }
132526  }
132527  return rc;
132528}
132529
132530/*
132531** Delete the cell at index iCell of node pNode. After removing the
132532** cell, adjust the r-tree data structure if required.
132533*/
132534static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
132535  RtreeNode *pParent;
132536  int rc;
132537
132538  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
132539    return rc;
132540  }
132541
132542  /* Remove the cell from the node. This call just moves bytes around
132543  ** the in-memory node image, so it cannot fail.
132544  */
132545  nodeDeleteCell(pRtree, pNode, iCell);
132546
132547  /* If the node is not the tree root and now has less than the minimum
132548  ** number of cells, remove it from the tree. Otherwise, update the
132549  ** cell in the parent node so that it tightly contains the updated
132550  ** node.
132551  */
132552  pParent = pNode->pParent;
132553  assert( pParent || pNode->iNode==1 );
132554  if( pParent ){
132555    if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
132556      rc = removeNode(pRtree, pNode, iHeight);
132557    }else{
132558      rc = fixBoundingBox(pRtree, pNode);
132559    }
132560  }
132561
132562  return rc;
132563}
132564
132565static int Reinsert(
132566  Rtree *pRtree,
132567  RtreeNode *pNode,
132568  RtreeCell *pCell,
132569  int iHeight
132570){
132571  int *aOrder;
132572  int *aSpare;
132573  RtreeCell *aCell;
132574  float *aDistance;
132575  int nCell;
132576  float aCenterCoord[RTREE_MAX_DIMENSIONS];
132577  int iDim;
132578  int ii;
132579  int rc = SQLITE_OK;
132580
132581  memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
132582
132583  nCell = NCELL(pNode)+1;
132584
132585  /* Allocate the buffers used by this operation. The allocation is
132586  ** relinquished before this function returns.
132587  */
132588  aCell = (RtreeCell *)sqlite3_malloc(nCell * (
132589    sizeof(RtreeCell) +         /* aCell array */
132590    sizeof(int)       +         /* aOrder array */
132591    sizeof(int)       +         /* aSpare array */
132592    sizeof(float)               /* aDistance array */
132593  ));
132594  if( !aCell ){
132595    return SQLITE_NOMEM;
132596  }
132597  aOrder    = (int *)&aCell[nCell];
132598  aSpare    = (int *)&aOrder[nCell];
132599  aDistance = (float *)&aSpare[nCell];
132600
132601  for(ii=0; ii<nCell; ii++){
132602    if( ii==(nCell-1) ){
132603      memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
132604    }else{
132605      nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
132606    }
132607    aOrder[ii] = ii;
132608    for(iDim=0; iDim<pRtree->nDim; iDim++){
132609      aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2]);
132610      aCenterCoord[iDim] += (float)DCOORD(aCell[ii].aCoord[iDim*2+1]);
132611    }
132612  }
132613  for(iDim=0; iDim<pRtree->nDim; iDim++){
132614    aCenterCoord[iDim] = (float)(aCenterCoord[iDim]/((float)nCell*2.0));
132615  }
132616
132617  for(ii=0; ii<nCell; ii++){
132618    aDistance[ii] = 0.0;
132619    for(iDim=0; iDim<pRtree->nDim; iDim++){
132620      float coord = (float)(DCOORD(aCell[ii].aCoord[iDim*2+1]) -
132621          DCOORD(aCell[ii].aCoord[iDim*2]));
132622      aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
132623    }
132624  }
132625
132626  SortByDistance(aOrder, nCell, aDistance, aSpare);
132627  nodeZero(pRtree, pNode);
132628
132629  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
132630    RtreeCell *p = &aCell[aOrder[ii]];
132631    nodeInsertCell(pRtree, pNode, p);
132632    if( p->iRowid==pCell->iRowid ){
132633      if( iHeight==0 ){
132634        rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
132635      }else{
132636        rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
132637      }
132638    }
132639  }
132640  if( rc==SQLITE_OK ){
132641    rc = fixBoundingBox(pRtree, pNode);
132642  }
132643  for(; rc==SQLITE_OK && ii<nCell; ii++){
132644    /* Find a node to store this cell in. pNode->iNode currently contains
132645    ** the height of the sub-tree headed by the cell.
132646    */
132647    RtreeNode *pInsert;
132648    RtreeCell *p = &aCell[aOrder[ii]];
132649    rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
132650    if( rc==SQLITE_OK ){
132651      int rc2;
132652      rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
132653      rc2 = nodeRelease(pRtree, pInsert);
132654      if( rc==SQLITE_OK ){
132655        rc = rc2;
132656      }
132657    }
132658  }
132659
132660  sqlite3_free(aCell);
132661  return rc;
132662}
132663
132664/*
132665** Insert cell pCell into node pNode. Node pNode is the head of a
132666** subtree iHeight high (leaf nodes have iHeight==0).
132667*/
132668static int rtreeInsertCell(
132669  Rtree *pRtree,
132670  RtreeNode *pNode,
132671  RtreeCell *pCell,
132672  int iHeight
132673){
132674  int rc = SQLITE_OK;
132675  if( iHeight>0 ){
132676    RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
132677    if( pChild ){
132678      nodeRelease(pRtree, pChild->pParent);
132679      nodeReference(pNode);
132680      pChild->pParent = pNode;
132681    }
132682  }
132683  if( nodeInsertCell(pRtree, pNode, pCell) ){
132684#if VARIANT_RSTARTREE_REINSERT
132685    if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
132686      rc = SplitNode(pRtree, pNode, pCell, iHeight);
132687    }else{
132688      pRtree->iReinsertHeight = iHeight;
132689      rc = Reinsert(pRtree, pNode, pCell, iHeight);
132690    }
132691#else
132692    rc = SplitNode(pRtree, pNode, pCell, iHeight);
132693#endif
132694  }else{
132695    rc = AdjustTree(pRtree, pNode, pCell);
132696    if( rc==SQLITE_OK ){
132697      if( iHeight==0 ){
132698        rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
132699      }else{
132700        rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
132701      }
132702    }
132703  }
132704  return rc;
132705}
132706
132707static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
132708  int ii;
132709  int rc = SQLITE_OK;
132710  int nCell = NCELL(pNode);
132711
132712  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
132713    RtreeNode *pInsert;
132714    RtreeCell cell;
132715    nodeGetCell(pRtree, pNode, ii, &cell);
132716
132717    /* Find a node to store this cell in. pNode->iNode currently contains
132718    ** the height of the sub-tree headed by the cell.
132719    */
132720    rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
132721    if( rc==SQLITE_OK ){
132722      int rc2;
132723      rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
132724      rc2 = nodeRelease(pRtree, pInsert);
132725      if( rc==SQLITE_OK ){
132726        rc = rc2;
132727      }
132728    }
132729  }
132730  return rc;
132731}
132732
132733/*
132734** Select a currently unused rowid for a new r-tree record.
132735*/
132736static int newRowid(Rtree *pRtree, i64 *piRowid){
132737  int rc;
132738  sqlite3_bind_null(pRtree->pWriteRowid, 1);
132739  sqlite3_bind_null(pRtree->pWriteRowid, 2);
132740  sqlite3_step(pRtree->pWriteRowid);
132741  rc = sqlite3_reset(pRtree->pWriteRowid);
132742  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
132743  return rc;
132744}
132745
132746/*
132747** Remove the entry with rowid=iDelete from the r-tree structure.
132748*/
132749static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
132750  int rc;                         /* Return code */
132751  RtreeNode *pLeaf;               /* Leaf node containing record iDelete */
132752  int iCell;                      /* Index of iDelete cell in pLeaf */
132753  RtreeNode *pRoot;               /* Root node of rtree structure */
132754
132755
132756  /* Obtain a reference to the root node to initialise Rtree.iDepth */
132757  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
132758
132759  /* Obtain a reference to the leaf node that contains the entry
132760  ** about to be deleted.
132761  */
132762  if( rc==SQLITE_OK ){
132763    rc = findLeafNode(pRtree, iDelete, &pLeaf);
132764  }
132765
132766  /* Delete the cell in question from the leaf node. */
132767  if( rc==SQLITE_OK ){
132768    int rc2;
132769    rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
132770    if( rc==SQLITE_OK ){
132771      rc = deleteCell(pRtree, pLeaf, iCell, 0);
132772    }
132773    rc2 = nodeRelease(pRtree, pLeaf);
132774    if( rc==SQLITE_OK ){
132775      rc = rc2;
132776    }
132777  }
132778
132779  /* Delete the corresponding entry in the <rtree>_rowid table. */
132780  if( rc==SQLITE_OK ){
132781    sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
132782    sqlite3_step(pRtree->pDeleteRowid);
132783    rc = sqlite3_reset(pRtree->pDeleteRowid);
132784  }
132785
132786  /* Check if the root node now has exactly one child. If so, remove
132787  ** it, schedule the contents of the child for reinsertion and
132788  ** reduce the tree height by one.
132789  **
132790  ** This is equivalent to copying the contents of the child into
132791  ** the root node (the operation that Gutman's paper says to perform
132792  ** in this scenario).
132793  */
132794  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
132795    int rc2;
132796    RtreeNode *pChild;
132797    i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
132798    rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
132799    if( rc==SQLITE_OK ){
132800      rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
132801    }
132802    rc2 = nodeRelease(pRtree, pChild);
132803    if( rc==SQLITE_OK ) rc = rc2;
132804    if( rc==SQLITE_OK ){
132805      pRtree->iDepth--;
132806      writeInt16(pRoot->zData, pRtree->iDepth);
132807      pRoot->isDirty = 1;
132808    }
132809  }
132810
132811  /* Re-insert the contents of any underfull nodes removed from the tree. */
132812  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
132813    if( rc==SQLITE_OK ){
132814      rc = reinsertNodeContent(pRtree, pLeaf);
132815    }
132816    pRtree->pDeleted = pLeaf->pNext;
132817    sqlite3_free(pLeaf);
132818  }
132819
132820  /* Release the reference to the root node. */
132821  if( rc==SQLITE_OK ){
132822    rc = nodeRelease(pRtree, pRoot);
132823  }else{
132824    nodeRelease(pRtree, pRoot);
132825  }
132826
132827  return rc;
132828}
132829
132830/*
132831** The xUpdate method for rtree module virtual tables.
132832*/
132833static int rtreeUpdate(
132834  sqlite3_vtab *pVtab,
132835  int nData,
132836  sqlite3_value **azData,
132837  sqlite_int64 *pRowid
132838){
132839  Rtree *pRtree = (Rtree *)pVtab;
132840  int rc = SQLITE_OK;
132841  RtreeCell cell;                 /* New cell to insert if nData>1 */
132842  int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
132843
132844  rtreeReference(pRtree);
132845  assert(nData>=1);
132846
132847  /* Constraint handling. A write operation on an r-tree table may return
132848  ** SQLITE_CONSTRAINT for two reasons:
132849  **
132850  **   1. A duplicate rowid value, or
132851  **   2. The supplied data violates the "x2>=x1" constraint.
132852  **
132853  ** In the first case, if the conflict-handling mode is REPLACE, then
132854  ** the conflicting row can be removed before proceeding. In the second
132855  ** case, SQLITE_CONSTRAINT must be returned regardless of the
132856  ** conflict-handling mode specified by the user.
132857  */
132858  if( nData>1 ){
132859    int ii;
132860
132861    /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
132862    assert( nData==(pRtree->nDim*2 + 3) );
132863    if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
132864      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
132865        cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
132866        cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
132867        if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
132868          rc = SQLITE_CONSTRAINT;
132869          goto constraint;
132870        }
132871      }
132872    }else{
132873      for(ii=0; ii<(pRtree->nDim*2); ii+=2){
132874        cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
132875        cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
132876        if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
132877          rc = SQLITE_CONSTRAINT;
132878          goto constraint;
132879        }
132880      }
132881    }
132882
132883    /* If a rowid value was supplied, check if it is already present in
132884    ** the table. If so, the constraint has failed. */
132885    if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
132886      cell.iRowid = sqlite3_value_int64(azData[2]);
132887      if( sqlite3_value_type(azData[0])==SQLITE_NULL
132888       || sqlite3_value_int64(azData[0])!=cell.iRowid
132889      ){
132890        int steprc;
132891        sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
132892        steprc = sqlite3_step(pRtree->pReadRowid);
132893        rc = sqlite3_reset(pRtree->pReadRowid);
132894        if( SQLITE_ROW==steprc ){
132895          if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
132896            rc = rtreeDeleteRowid(pRtree, cell.iRowid);
132897          }else{
132898            rc = SQLITE_CONSTRAINT;
132899            goto constraint;
132900          }
132901        }
132902      }
132903      bHaveRowid = 1;
132904    }
132905  }
132906
132907  /* If azData[0] is not an SQL NULL value, it is the rowid of a
132908  ** record to delete from the r-tree table. The following block does
132909  ** just that.
132910  */
132911  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
132912    rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
132913  }
132914
132915  /* If the azData[] array contains more than one element, elements
132916  ** (azData[2]..azData[argc-1]) contain a new record to insert into
132917  ** the r-tree structure.
132918  */
132919  if( rc==SQLITE_OK && nData>1 ){
132920    /* Insert the new record into the r-tree */
132921    RtreeNode *pLeaf;
132922
132923    /* Figure out the rowid of the new row. */
132924    if( bHaveRowid==0 ){
132925      rc = newRowid(pRtree, &cell.iRowid);
132926    }
132927    *pRowid = cell.iRowid;
132928
132929    if( rc==SQLITE_OK ){
132930      rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
132931    }
132932    if( rc==SQLITE_OK ){
132933      int rc2;
132934      pRtree->iReinsertHeight = -1;
132935      rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
132936      rc2 = nodeRelease(pRtree, pLeaf);
132937      if( rc==SQLITE_OK ){
132938        rc = rc2;
132939      }
132940    }
132941  }
132942
132943constraint:
132944  rtreeRelease(pRtree);
132945  return rc;
132946}
132947
132948/*
132949** The xRename method for rtree module virtual tables.
132950*/
132951static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
132952  Rtree *pRtree = (Rtree *)pVtab;
132953  int rc = SQLITE_NOMEM;
132954  char *zSql = sqlite3_mprintf(
132955    "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
132956    "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
132957    "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
132958    , pRtree->zDb, pRtree->zName, zNewName
132959    , pRtree->zDb, pRtree->zName, zNewName
132960    , pRtree->zDb, pRtree->zName, zNewName
132961  );
132962  if( zSql ){
132963    rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
132964    sqlite3_free(zSql);
132965  }
132966  return rc;
132967}
132968
132969static sqlite3_module rtreeModule = {
132970  0,                          /* iVersion */
132971  rtreeCreate,                /* xCreate - create a table */
132972  rtreeConnect,               /* xConnect - connect to an existing table */
132973  rtreeBestIndex,             /* xBestIndex - Determine search strategy */
132974  rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
132975  rtreeDestroy,               /* xDestroy - Drop a table */
132976  rtreeOpen,                  /* xOpen - open a cursor */
132977  rtreeClose,                 /* xClose - close a cursor */
132978  rtreeFilter,                /* xFilter - configure scan constraints */
132979  rtreeNext,                  /* xNext - advance a cursor */
132980  rtreeEof,                   /* xEof */
132981  rtreeColumn,                /* xColumn - read data */
132982  rtreeRowid,                 /* xRowid - read data */
132983  rtreeUpdate,                /* xUpdate - write data */
132984  0,                          /* xBegin - begin transaction */
132985  0,                          /* xSync - sync transaction */
132986  0,                          /* xCommit - commit transaction */
132987  0,                          /* xRollback - rollback transaction */
132988  0,                          /* xFindFunction - function overloading */
132989  rtreeRename,                /* xRename - rename the table */
132990  0,                          /* xSavepoint */
132991  0,                          /* xRelease */
132992  0                           /* xRollbackTo */
132993};
132994
132995static int rtreeSqlInit(
132996  Rtree *pRtree,
132997  sqlite3 *db,
132998  const char *zDb,
132999  const char *zPrefix,
133000  int isCreate
133001){
133002  int rc = SQLITE_OK;
133003
133004  #define N_STATEMENT 9
133005  static const char *azSql[N_STATEMENT] = {
133006    /* Read and write the xxx_node table */
133007    "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
133008    "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
133009    "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
133010
133011    /* Read and write the xxx_rowid table */
133012    "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
133013    "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
133014    "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
133015
133016    /* Read and write the xxx_parent table */
133017    "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
133018    "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
133019    "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
133020  };
133021  sqlite3_stmt **appStmt[N_STATEMENT];
133022  int i;
133023
133024  pRtree->db = db;
133025
133026  if( isCreate ){
133027    char *zCreate = sqlite3_mprintf(
133028"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
133029"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
133030"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
133031"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
133032      zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
133033    );
133034    if( !zCreate ){
133035      return SQLITE_NOMEM;
133036    }
133037    rc = sqlite3_exec(db, zCreate, 0, 0, 0);
133038    sqlite3_free(zCreate);
133039    if( rc!=SQLITE_OK ){
133040      return rc;
133041    }
133042  }
133043
133044  appStmt[0] = &pRtree->pReadNode;
133045  appStmt[1] = &pRtree->pWriteNode;
133046  appStmt[2] = &pRtree->pDeleteNode;
133047  appStmt[3] = &pRtree->pReadRowid;
133048  appStmt[4] = &pRtree->pWriteRowid;
133049  appStmt[5] = &pRtree->pDeleteRowid;
133050  appStmt[6] = &pRtree->pReadParent;
133051  appStmt[7] = &pRtree->pWriteParent;
133052  appStmt[8] = &pRtree->pDeleteParent;
133053
133054  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
133055    char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
133056    if( zSql ){
133057      rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
133058    }else{
133059      rc = SQLITE_NOMEM;
133060    }
133061    sqlite3_free(zSql);
133062  }
133063
133064  return rc;
133065}
133066
133067/*
133068** The second argument to this function contains the text of an SQL statement
133069** that returns a single integer value. The statement is compiled and executed
133070** using database connection db. If successful, the integer value returned
133071** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
133072** code is returned and the value of *piVal after returning is not defined.
133073*/
133074static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
133075  int rc = SQLITE_NOMEM;
133076  if( zSql ){
133077    sqlite3_stmt *pStmt = 0;
133078    rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
133079    if( rc==SQLITE_OK ){
133080      if( SQLITE_ROW==sqlite3_step(pStmt) ){
133081        *piVal = sqlite3_column_int(pStmt, 0);
133082      }
133083      rc = sqlite3_finalize(pStmt);
133084    }
133085  }
133086  return rc;
133087}
133088
133089/*
133090** This function is called from within the xConnect() or xCreate() method to
133091** determine the node-size used by the rtree table being created or connected
133092** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
133093** Otherwise, an SQLite error code is returned.
133094**
133095** If this function is being called as part of an xConnect(), then the rtree
133096** table already exists. In this case the node-size is determined by inspecting
133097** the root node of the tree.
133098**
133099** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
133100** This ensures that each node is stored on a single database page. If the
133101** database page-size is so large that more than RTREE_MAXCELLS entries
133102** would fit in a single node, use a smaller node-size.
133103*/
133104static int getNodeSize(
133105  sqlite3 *db,                    /* Database handle */
133106  Rtree *pRtree,                  /* Rtree handle */
133107  int isCreate                    /* True for xCreate, false for xConnect */
133108){
133109  int rc;
133110  char *zSql;
133111  if( isCreate ){
133112    int iPageSize = 0;
133113    zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
133114    rc = getIntFromStmt(db, zSql, &iPageSize);
133115    if( rc==SQLITE_OK ){
133116      pRtree->iNodeSize = iPageSize-64;
133117      if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
133118        pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
133119      }
133120    }
133121  }else{
133122    zSql = sqlite3_mprintf(
133123        "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
133124        pRtree->zDb, pRtree->zName
133125    );
133126    rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
133127  }
133128
133129  sqlite3_free(zSql);
133130  return rc;
133131}
133132
133133/*
133134** This function is the implementation of both the xConnect and xCreate
133135** methods of the r-tree virtual table.
133136**
133137**   argv[0]   -> module name
133138**   argv[1]   -> database name
133139**   argv[2]   -> table name
133140**   argv[...] -> column names...
133141*/
133142static int rtreeInit(
133143  sqlite3 *db,                        /* Database connection */
133144  void *pAux,                         /* One of the RTREE_COORD_* constants */
133145  int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
133146  sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
133147  char **pzErr,                       /* OUT: Error message, if any */
133148  int isCreate                        /* True for xCreate, false for xConnect */
133149){
133150  int rc = SQLITE_OK;
133151  Rtree *pRtree;
133152  int nDb;              /* Length of string argv[1] */
133153  int nName;            /* Length of string argv[2] */
133154  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
133155
133156  const char *aErrMsg[] = {
133157    0,                                                    /* 0 */
133158    "Wrong number of columns for an rtree table",         /* 1 */
133159    "Too few columns for an rtree table",                 /* 2 */
133160    "Too many columns for an rtree table"                 /* 3 */
133161  };
133162
133163  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
133164  if( aErrMsg[iErr] ){
133165    *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
133166    return SQLITE_ERROR;
133167  }
133168
133169  sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
133170
133171  /* Allocate the sqlite3_vtab structure */
133172  nDb = (int)strlen(argv[1]);
133173  nName = (int)strlen(argv[2]);
133174  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
133175  if( !pRtree ){
133176    return SQLITE_NOMEM;
133177  }
133178  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
133179  pRtree->nBusy = 1;
133180  pRtree->base.pModule = &rtreeModule;
133181  pRtree->zDb = (char *)&pRtree[1];
133182  pRtree->zName = &pRtree->zDb[nDb+1];
133183  pRtree->nDim = (argc-4)/2;
133184  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
133185  pRtree->eCoordType = eCoordType;
133186  memcpy(pRtree->zDb, argv[1], nDb);
133187  memcpy(pRtree->zName, argv[2], nName);
133188
133189  /* Figure out the node size to use. */
133190  rc = getNodeSize(db, pRtree, isCreate);
133191
133192  /* Create/Connect to the underlying relational database schema. If
133193  ** that is successful, call sqlite3_declare_vtab() to configure
133194  ** the r-tree table schema.
133195  */
133196  if( rc==SQLITE_OK ){
133197    if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
133198      *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
133199    }else{
133200      char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
133201      char *zTmp;
133202      int ii;
133203      for(ii=4; zSql && ii<argc; ii++){
133204        zTmp = zSql;
133205        zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
133206        sqlite3_free(zTmp);
133207      }
133208      if( zSql ){
133209        zTmp = zSql;
133210        zSql = sqlite3_mprintf("%s);", zTmp);
133211        sqlite3_free(zTmp);
133212      }
133213      if( !zSql ){
133214        rc = SQLITE_NOMEM;
133215      }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
133216        *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
133217      }
133218      sqlite3_free(zSql);
133219    }
133220  }
133221
133222  if( rc==SQLITE_OK ){
133223    *ppVtab = (sqlite3_vtab *)pRtree;
133224  }else{
133225    rtreeRelease(pRtree);
133226  }
133227  return rc;
133228}
133229
133230
133231/*
133232** Implementation of a scalar function that decodes r-tree nodes to
133233** human readable strings. This can be used for debugging and analysis.
133234**
133235** The scalar function takes two arguments, a blob of data containing
133236** an r-tree node, and the number of dimensions the r-tree indexes.
133237** For a two-dimensional r-tree structure called "rt", to deserialize
133238** all nodes, a statement like:
133239**
133240**   SELECT rtreenode(2, data) FROM rt_node;
133241**
133242** The human readable string takes the form of a Tcl list with one
133243** entry for each cell in the r-tree node. Each entry is itself a
133244** list, containing the 8-byte rowid/pageno followed by the
133245** <num-dimension>*2 coordinates.
133246*/
133247static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
133248  char *zText = 0;
133249  RtreeNode node;
133250  Rtree tree;
133251  int ii;
133252
133253  UNUSED_PARAMETER(nArg);
133254  memset(&node, 0, sizeof(RtreeNode));
133255  memset(&tree, 0, sizeof(Rtree));
133256  tree.nDim = sqlite3_value_int(apArg[0]);
133257  tree.nBytesPerCell = 8 + 8 * tree.nDim;
133258  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
133259
133260  for(ii=0; ii<NCELL(&node); ii++){
133261    char zCell[512];
133262    int nCell = 0;
133263    RtreeCell cell;
133264    int jj;
133265
133266    nodeGetCell(&tree, &node, ii, &cell);
133267    sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
133268    nCell = (int)strlen(zCell);
133269    for(jj=0; jj<tree.nDim*2; jj++){
133270      sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
133271      nCell = (int)strlen(zCell);
133272    }
133273
133274    if( zText ){
133275      char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
133276      sqlite3_free(zText);
133277      zText = zTextNew;
133278    }else{
133279      zText = sqlite3_mprintf("{%s}", zCell);
133280    }
133281  }
133282
133283  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
133284}
133285
133286static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
133287  UNUSED_PARAMETER(nArg);
133288  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
133289   || sqlite3_value_bytes(apArg[0])<2
133290  ){
133291    sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
133292  }else{
133293    u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
133294    sqlite3_result_int(ctx, readInt16(zBlob));
133295  }
133296}
133297
133298/*
133299** Register the r-tree module with database handle db. This creates the
133300** virtual table module "rtree" and the debugging/analysis scalar
133301** function "rtreenode".
133302*/
133303SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
133304  const int utf8 = SQLITE_UTF8;
133305  int rc;
133306
133307  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
133308  if( rc==SQLITE_OK ){
133309    rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
133310  }
133311  if( rc==SQLITE_OK ){
133312    void *c = (void *)RTREE_COORD_REAL32;
133313    rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
133314  }
133315  if( rc==SQLITE_OK ){
133316    void *c = (void *)RTREE_COORD_INT32;
133317    rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
133318  }
133319
133320  return rc;
133321}
133322
133323/*
133324** A version of sqlite3_free() that can be used as a callback. This is used
133325** in two places - as the destructor for the blob value returned by the
133326** invocation of a geometry function, and as the destructor for the geometry
133327** functions themselves.
133328*/
133329static void doSqlite3Free(void *p){
133330  sqlite3_free(p);
133331}
133332
133333/*
133334** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
133335** scalar user function. This C function is the callback used for all such
133336** registered SQL functions.
133337**
133338** The scalar user functions return a blob that is interpreted by r-tree
133339** table MATCH operators.
133340*/
133341static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
133342  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
133343  RtreeMatchArg *pBlob;
133344  int nBlob;
133345
133346  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(double);
133347  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
133348  if( !pBlob ){
133349    sqlite3_result_error_nomem(ctx);
133350  }else{
133351    int i;
133352    pBlob->magic = RTREE_GEOMETRY_MAGIC;
133353    pBlob->xGeom = pGeomCtx->xGeom;
133354    pBlob->pContext = pGeomCtx->pContext;
133355    pBlob->nParam = nArg;
133356    for(i=0; i<nArg; i++){
133357      pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
133358    }
133359    sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
133360  }
133361}
133362
133363/*
133364** Register a new geometry function for use with the r-tree MATCH operator.
133365*/
133366SQLITE_API int sqlite3_rtree_geometry_callback(
133367  sqlite3 *db,
133368  const char *zGeom,
133369  int (*xGeom)(sqlite3_rtree_geometry *, int, double *, int *),
133370  void *pContext
133371){
133372  RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
133373
133374  /* Allocate and populate the context object. */
133375  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
133376  if( !pGeomCtx ) return SQLITE_NOMEM;
133377  pGeomCtx->xGeom = xGeom;
133378  pGeomCtx->pContext = pContext;
133379
133380  /* Create the new user-function. Register a destructor function to delete
133381  ** the context object when it is no longer required.  */
133382  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
133383      (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
133384  );
133385}
133386
133387#if !SQLITE_CORE
133388SQLITE_API int sqlite3_extension_init(
133389  sqlite3 *db,
133390  char **pzErrMsg,
133391  const sqlite3_api_routines *pApi
133392){
133393  SQLITE_EXTENSION_INIT2(pApi)
133394  return sqlite3RtreeInit(db);
133395}
133396#endif
133397
133398#endif
133399
133400/************** End of rtree.c ***********************************************/
133401/************** Begin file icu.c *********************************************/
133402/*
133403** 2007 May 6
133404**
133405** The author disclaims copyright to this source code.  In place of
133406** a legal notice, here is a blessing:
133407**
133408**    May you do good and not evil.
133409**    May you find forgiveness for yourself and forgive others.
133410**    May you share freely, never taking more than you give.
133411**
133412*************************************************************************
133413** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
133414**
133415** This file implements an integration between the ICU library
133416** ("International Components for Unicode", an open-source library
133417** for handling unicode data) and SQLite. The integration uses
133418** ICU to provide the following to SQLite:
133419**
133420**   * An implementation of the SQL regexp() function (and hence REGEXP
133421**     operator) using the ICU uregex_XX() APIs.
133422**
133423**   * Implementations of the SQL scalar upper() and lower() functions
133424**     for case mapping.
133425**
133426**   * Integration of ICU and SQLite collation seqences.
133427**
133428**   * An implementation of the LIKE operator that uses ICU to
133429**     provide case-independent matching.
133430*/
133431
133432#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
133433
133434/* Include ICU headers */
133435#include <unicode/utypes.h>
133436#include <unicode/uregex.h>
133437#include <unicode/ustring.h>
133438#include <unicode/ucol.h>
133439
133440/* #include <assert.h> */
133441
133442#ifndef SQLITE_CORE
133443  SQLITE_EXTENSION_INIT1
133444#else
133445#endif
133446
133447/*
133448** Maximum length (in bytes) of the pattern in a LIKE or GLOB
133449** operator.
133450*/
133451#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
133452# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
133453#endif
133454
133455/*
133456** Version of sqlite3_free() that is always a function, never a macro.
133457*/
133458static void xFree(void *p){
133459  sqlite3_free(p);
133460}
133461
133462/*
133463** Compare two UTF-8 strings for equality where the first string is
133464** a "LIKE" expression. Return true (1) if they are the same and
133465** false (0) if they are different.
133466*/
133467static int icuLikeCompare(
133468  const uint8_t *zPattern,   /* LIKE pattern */
133469  const uint8_t *zString,    /* The UTF-8 string to compare against */
133470  const UChar32 uEsc         /* The escape character */
133471){
133472  static const int MATCH_ONE = (UChar32)'_';
133473  static const int MATCH_ALL = (UChar32)'%';
133474
133475  int iPattern = 0;       /* Current byte index in zPattern */
133476  int iString = 0;        /* Current byte index in zString */
133477
133478  int prevEscape = 0;     /* True if the previous character was uEsc */
133479
133480  while( zPattern[iPattern]!=0 ){
133481
133482    /* Read (and consume) the next character from the input pattern. */
133483    UChar32 uPattern;
133484    U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
133485    assert(uPattern!=0);
133486
133487    /* There are now 4 possibilities:
133488    **
133489    **     1. uPattern is an unescaped match-all character "%",
133490    **     2. uPattern is an unescaped match-one character "_",
133491    **     3. uPattern is an unescaped escape character, or
133492    **     4. uPattern is to be handled as an ordinary character
133493    */
133494    if( !prevEscape && uPattern==MATCH_ALL ){
133495      /* Case 1. */
133496      uint8_t c;
133497
133498      /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
133499      ** MATCH_ALL. For each MATCH_ONE, skip one character in the
133500      ** test string.
133501      */
133502      while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
133503        if( c==MATCH_ONE ){
133504          if( zString[iString]==0 ) return 0;
133505          U8_FWD_1_UNSAFE(zString, iString);
133506        }
133507        iPattern++;
133508      }
133509
133510      if( zPattern[iPattern]==0 ) return 1;
133511
133512      while( zString[iString] ){
133513        if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
133514          return 1;
133515        }
133516        U8_FWD_1_UNSAFE(zString, iString);
133517      }
133518      return 0;
133519
133520    }else if( !prevEscape && uPattern==MATCH_ONE ){
133521      /* Case 2. */
133522      if( zString[iString]==0 ) return 0;
133523      U8_FWD_1_UNSAFE(zString, iString);
133524
133525    }else if( !prevEscape && uPattern==uEsc){
133526      /* Case 3. */
133527      prevEscape = 1;
133528
133529    }else{
133530      /* Case 4. */
133531      UChar32 uString;
133532      U8_NEXT_UNSAFE(zString, iString, uString);
133533      uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
133534      uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
133535      if( uString!=uPattern ){
133536        return 0;
133537      }
133538      prevEscape = 0;
133539    }
133540  }
133541
133542  return zString[iString]==0;
133543}
133544
133545/*
133546** Implementation of the like() SQL function.  This function implements
133547** the build-in LIKE operator.  The first argument to the function is the
133548** pattern and the second argument is the string.  So, the SQL statements:
133549**
133550**       A LIKE B
133551**
133552** is implemented as like(B, A). If there is an escape character E,
133553**
133554**       A LIKE B ESCAPE E
133555**
133556** is mapped to like(B, A, E).
133557*/
133558static void icuLikeFunc(
133559  sqlite3_context *context,
133560  int argc,
133561  sqlite3_value **argv
133562){
133563  const unsigned char *zA = sqlite3_value_text(argv[0]);
133564  const unsigned char *zB = sqlite3_value_text(argv[1]);
133565  UChar32 uEsc = 0;
133566
133567  /* Limit the length of the LIKE or GLOB pattern to avoid problems
133568  ** of deep recursion and N*N behavior in patternCompare().
133569  */
133570  if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
133571    sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
133572    return;
133573  }
133574
133575
133576  if( argc==3 ){
133577    /* The escape character string must consist of a single UTF-8 character.
133578    ** Otherwise, return an error.
133579    */
133580    int nE= sqlite3_value_bytes(argv[2]);
133581    const unsigned char *zE = sqlite3_value_text(argv[2]);
133582    int i = 0;
133583    if( zE==0 ) return;
133584    U8_NEXT(zE, i, nE, uEsc);
133585    if( i!=nE){
133586      sqlite3_result_error(context,
133587          "ESCAPE expression must be a single character", -1);
133588      return;
133589    }
133590  }
133591
133592  if( zA && zB ){
133593    sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
133594  }
133595}
133596
133597/*
133598** This function is called when an ICU function called from within
133599** the implementation of an SQL scalar function returns an error.
133600**
133601** The scalar function context passed as the first argument is
133602** loaded with an error message based on the following two args.
133603*/
133604static void icuFunctionError(
133605  sqlite3_context *pCtx,       /* SQLite scalar function context */
133606  const char *zName,           /* Name of ICU function that failed */
133607  UErrorCode e                 /* Error code returned by ICU function */
133608){
133609  char zBuf[128];
133610  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
133611  zBuf[127] = '\0';
133612  sqlite3_result_error(pCtx, zBuf, -1);
133613}
133614
133615/*
133616** Function to delete compiled regexp objects. Registered as
133617** a destructor function with sqlite3_set_auxdata().
133618*/
133619static void icuRegexpDelete(void *p){
133620  URegularExpression *pExpr = (URegularExpression *)p;
133621  uregex_close(pExpr);
133622}
133623
133624/*
133625** Implementation of SQLite REGEXP operator. This scalar function takes
133626** two arguments. The first is a regular expression pattern to compile
133627** the second is a string to match against that pattern. If either
133628** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
133629** is 1 if the string matches the pattern, or 0 otherwise.
133630**
133631** SQLite maps the regexp() function to the regexp() operator such
133632** that the following two are equivalent:
133633**
133634**     zString REGEXP zPattern
133635**     regexp(zPattern, zString)
133636**
133637** Uses the following ICU regexp APIs:
133638**
133639**     uregex_open()
133640**     uregex_matches()
133641**     uregex_close()
133642*/
133643static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
133644  UErrorCode status = U_ZERO_ERROR;
133645  URegularExpression *pExpr;
133646  UBool res;
133647  const UChar *zString = sqlite3_value_text16(apArg[1]);
133648
133649  (void)nArg;  /* Unused parameter */
133650
133651  /* If the left hand side of the regexp operator is NULL,
133652  ** then the result is also NULL.
133653  */
133654  if( !zString ){
133655    return;
133656  }
133657
133658  pExpr = sqlite3_get_auxdata(p, 0);
133659  if( !pExpr ){
133660    const UChar *zPattern = sqlite3_value_text16(apArg[0]);
133661    if( !zPattern ){
133662      return;
133663    }
133664    pExpr = uregex_open(zPattern, -1, 0, 0, &status);
133665
133666    if( U_SUCCESS(status) ){
133667      sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
133668    }else{
133669      assert(!pExpr);
133670      icuFunctionError(p, "uregex_open", status);
133671      return;
133672    }
133673  }
133674
133675  /* Configure the text that the regular expression operates on. */
133676  uregex_setText(pExpr, zString, -1, &status);
133677  if( !U_SUCCESS(status) ){
133678    icuFunctionError(p, "uregex_setText", status);
133679    return;
133680  }
133681
133682  /* Attempt the match */
133683  res = uregex_matches(pExpr, 0, &status);
133684  if( !U_SUCCESS(status) ){
133685    icuFunctionError(p, "uregex_matches", status);
133686    return;
133687  }
133688
133689  /* Set the text that the regular expression operates on to a NULL
133690  ** pointer. This is not really necessary, but it is tidier than
133691  ** leaving the regular expression object configured with an invalid
133692  ** pointer after this function returns.
133693  */
133694  uregex_setText(pExpr, 0, 0, &status);
133695
133696  /* Return 1 or 0. */
133697  sqlite3_result_int(p, res ? 1 : 0);
133698}
133699
133700/*
133701** Implementations of scalar functions for case mapping - upper() and
133702** lower(). Function upper() converts its input to upper-case (ABC).
133703** Function lower() converts to lower-case (abc).
133704**
133705** ICU provides two types of case mapping, "general" case mapping and
133706** "language specific". Refer to ICU documentation for the differences
133707** between the two.
133708**
133709** To utilise "general" case mapping, the upper() or lower() scalar
133710** functions are invoked with one argument:
133711**
133712**     upper('ABC') -> 'abc'
133713**     lower('abc') -> 'ABC'
133714**
133715** To access ICU "language specific" case mapping, upper() or lower()
133716** should be invoked with two arguments. The second argument is the name
133717** of the locale to use. Passing an empty string ("") or SQL NULL value
133718** as the second argument is the same as invoking the 1 argument version
133719** of upper() or lower().
133720**
133721**     lower('I', 'en_us') -> 'i'
133722**     lower('I', 'tr_tr') -> 'ı' (small dotless i)
133723**
133724** http://www.icu-project.org/userguide/posix.html#case_mappings
133725*/
133726static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
133727  const UChar *zInput;
133728  UChar *zOutput;
133729  int nInput;
133730  int nOutput;
133731
133732  UErrorCode status = U_ZERO_ERROR;
133733  const char *zLocale = 0;
133734
133735  assert(nArg==1 || nArg==2);
133736  if( nArg==2 ){
133737    zLocale = (const char *)sqlite3_value_text(apArg[1]);
133738  }
133739
133740  zInput = sqlite3_value_text16(apArg[0]);
133741  if( !zInput ){
133742    return;
133743  }
133744  nInput = sqlite3_value_bytes16(apArg[0]);
133745
133746  nOutput = nInput * 2 + 2;
133747  zOutput = sqlite3_malloc(nOutput);
133748  if( !zOutput ){
133749    return;
133750  }
133751
133752  if( sqlite3_user_data(p) ){
133753    u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
133754  }else{
133755    u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
133756  }
133757
133758  if( !U_SUCCESS(status) ){
133759    icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
133760    return;
133761  }
133762
133763  sqlite3_result_text16(p, zOutput, -1, xFree);
133764}
133765
133766/*
133767** Collation sequence destructor function. The pCtx argument points to
133768** a UCollator structure previously allocated using ucol_open().
133769*/
133770static void icuCollationDel(void *pCtx){
133771  UCollator *p = (UCollator *)pCtx;
133772  ucol_close(p);
133773}
133774
133775/*
133776** Collation sequence comparison function. The pCtx argument points to
133777** a UCollator structure previously allocated using ucol_open().
133778*/
133779static int icuCollationColl(
133780  void *pCtx,
133781  int nLeft,
133782  const void *zLeft,
133783  int nRight,
133784  const void *zRight
133785){
133786  UCollationResult res;
133787  UCollator *p = (UCollator *)pCtx;
133788  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
133789  switch( res ){
133790    case UCOL_LESS:    return -1;
133791    case UCOL_GREATER: return +1;
133792    case UCOL_EQUAL:   return 0;
133793  }
133794  assert(!"Unexpected return value from ucol_strcoll()");
133795  return 0;
133796}
133797
133798/*
133799** Implementation of the scalar function icu_load_collation().
133800**
133801** This scalar function is used to add ICU collation based collation
133802** types to an SQLite database connection. It is intended to be called
133803** as follows:
133804**
133805**     SELECT icu_load_collation(<locale>, <collation-name>);
133806**
133807** Where <locale> is a string containing an ICU locale identifier (i.e.
133808** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
133809** collation sequence to create.
133810*/
133811static void icuLoadCollation(
133812  sqlite3_context *p,
133813  int nArg,
133814  sqlite3_value **apArg
133815){
133816  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
133817  UErrorCode status = U_ZERO_ERROR;
133818  const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
133819  const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
133820  UCollator *pUCollator;    /* ICU library collation object */
133821  int rc;                   /* Return code from sqlite3_create_collation_x() */
133822
133823  assert(nArg==2);
133824  zLocale = (const char *)sqlite3_value_text(apArg[0]);
133825  zName = (const char *)sqlite3_value_text(apArg[1]);
133826
133827  if( !zLocale || !zName ){
133828    return;
133829  }
133830
133831  pUCollator = ucol_open(zLocale, &status);
133832  if( !U_SUCCESS(status) ){
133833    icuFunctionError(p, "ucol_open", status);
133834    return;
133835  }
133836  assert(p);
133837
133838  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
133839      icuCollationColl, icuCollationDel
133840  );
133841  if( rc!=SQLITE_OK ){
133842    ucol_close(pUCollator);
133843    sqlite3_result_error(p, "Error registering collation function", -1);
133844  }
133845}
133846
133847/*
133848** Register the ICU extension functions with database db.
133849*/
133850SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
133851  struct IcuScalar {
133852    const char *zName;                        /* Function name */
133853    int nArg;                                 /* Number of arguments */
133854    int enc;                                  /* Optimal text encoding */
133855    void *pContext;                           /* sqlite3_user_data() context */
133856    void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
133857  } scalars[] = {
133858    {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
133859
133860    {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
133861    {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
133862    {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
133863    {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
133864
133865    {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
133866    {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
133867    {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
133868    {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
133869
133870    {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
133871    {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
133872
133873    {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
133874  };
133875
133876  int rc = SQLITE_OK;
133877  int i;
133878
133879  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
133880    struct IcuScalar *p = &scalars[i];
133881    rc = sqlite3_create_function(
133882        db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
133883    );
133884  }
133885
133886  return rc;
133887}
133888
133889#if !SQLITE_CORE
133890SQLITE_API int sqlite3_extension_init(
133891  sqlite3 *db,
133892  char **pzErrMsg,
133893  const sqlite3_api_routines *pApi
133894){
133895  SQLITE_EXTENSION_INIT2(pApi)
133896  return sqlite3IcuInit(db);
133897}
133898#endif
133899
133900#endif
133901
133902/************** End of icu.c *************************************************/
133903/************** Begin file fts3_icu.c ****************************************/
133904/*
133905** 2007 June 22
133906**
133907** The author disclaims copyright to this source code.  In place of
133908** a legal notice, here is a blessing:
133909**
133910**    May you do good and not evil.
133911**    May you find forgiveness for yourself and forgive others.
133912**    May you share freely, never taking more than you give.
133913**
133914*************************************************************************
133915** This file implements a tokenizer for fts3 based on the ICU library.
133916*/
133917#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
133918#ifdef SQLITE_ENABLE_ICU
133919
133920/* #include <assert.h> */
133921/* #include <string.h> */
133922
133923#include <unicode/ubrk.h>
133924/* #include <unicode/ucol.h> */
133925/* #include <unicode/ustring.h> */
133926#include <unicode/utf16.h>
133927
133928typedef struct IcuTokenizer IcuTokenizer;
133929typedef struct IcuCursor IcuCursor;
133930
133931struct IcuTokenizer {
133932  sqlite3_tokenizer base;
133933  char *zLocale;
133934};
133935
133936struct IcuCursor {
133937  sqlite3_tokenizer_cursor base;
133938
133939  UBreakIterator *pIter;      /* ICU break-iterator object */
133940  int nChar;                  /* Number of UChar elements in pInput */
133941  UChar *aChar;               /* Copy of input using utf-16 encoding */
133942  int *aOffset;               /* Offsets of each character in utf-8 input */
133943
133944  int nBuffer;
133945  char *zBuffer;
133946
133947  int iToken;
133948};
133949
133950/*
133951** Create a new tokenizer instance.
133952*/
133953static int icuCreate(
133954  int argc,                            /* Number of entries in argv[] */
133955  const char * const *argv,            /* Tokenizer creation arguments */
133956  sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
133957){
133958  IcuTokenizer *p;
133959  int n = 0;
133960
133961  if( argc>0 ){
133962    n = strlen(argv[0])+1;
133963  }
133964  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
133965  if( !p ){
133966    return SQLITE_NOMEM;
133967  }
133968  memset(p, 0, sizeof(IcuTokenizer));
133969
133970  if( n ){
133971    p->zLocale = (char *)&p[1];
133972    memcpy(p->zLocale, argv[0], n);
133973  }
133974
133975  *ppTokenizer = (sqlite3_tokenizer *)p;
133976
133977  return SQLITE_OK;
133978}
133979
133980/*
133981** Destroy a tokenizer
133982*/
133983static int icuDestroy(sqlite3_tokenizer *pTokenizer){
133984  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
133985  sqlite3_free(p);
133986  return SQLITE_OK;
133987}
133988
133989/*
133990** Prepare to begin tokenizing a particular string.  The input
133991** string to be tokenized is pInput[0..nBytes-1].  A cursor
133992** used to incrementally tokenize this string is returned in
133993** *ppCursor.
133994*/
133995static int icuOpen(
133996  sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
133997  const char *zInput,                    /* Input string */
133998  int nInput,                            /* Length of zInput in bytes */
133999  sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
134000){
134001  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
134002  IcuCursor *pCsr;
134003
134004  const int32_t opt = U_FOLD_CASE_DEFAULT;
134005  UErrorCode status = U_ZERO_ERROR;
134006  int nChar;
134007
134008  UChar32 c;
134009  int iInput = 0;
134010  int iOut = 0;
134011
134012  *ppCursor = 0;
134013
134014  if( nInput<0 ){
134015    nInput = strlen(zInput);
134016  }
134017  nChar = nInput+1;
134018  pCsr = (IcuCursor *)sqlite3_malloc(
134019      sizeof(IcuCursor) +                /* IcuCursor */
134020      nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
134021      (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
134022  );
134023  if( !pCsr ){
134024    return SQLITE_NOMEM;
134025  }
134026  memset(pCsr, 0, sizeof(IcuCursor));
134027  pCsr->aChar = (UChar *)&pCsr[1];
134028  pCsr->aOffset = (int *)&pCsr->aChar[nChar];
134029
134030  pCsr->aOffset[iOut] = iInput;
134031  U8_NEXT(zInput, iInput, nInput, c);
134032  while( c>0 ){
134033    int isError = 0;
134034    c = u_foldCase(c, opt);
134035    U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
134036    if( isError ){
134037      sqlite3_free(pCsr);
134038      return SQLITE_ERROR;
134039    }
134040    pCsr->aOffset[iOut] = iInput;
134041
134042    if( iInput<nInput ){
134043      U8_NEXT(zInput, iInput, nInput, c);
134044    }else{
134045      c = 0;
134046    }
134047  }
134048
134049  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
134050  if( !U_SUCCESS(status) ){
134051    sqlite3_free(pCsr);
134052    return SQLITE_ERROR;
134053  }
134054  pCsr->nChar = iOut;
134055
134056  ubrk_first(pCsr->pIter);
134057  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
134058  return SQLITE_OK;
134059}
134060
134061/*
134062** Close a tokenization cursor previously opened by a call to icuOpen().
134063*/
134064static int icuClose(sqlite3_tokenizer_cursor *pCursor){
134065  IcuCursor *pCsr = (IcuCursor *)pCursor;
134066  ubrk_close(pCsr->pIter);
134067  sqlite3_free(pCsr->zBuffer);
134068  sqlite3_free(pCsr);
134069  return SQLITE_OK;
134070}
134071
134072/*
134073** Extract the next token from a tokenization cursor.
134074*/
134075static int icuNext(
134076  sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
134077  const char **ppToken,               /* OUT: *ppToken is the token text */
134078  int *pnBytes,                       /* OUT: Number of bytes in token */
134079  int *piStartOffset,                 /* OUT: Starting offset of token */
134080  int *piEndOffset,                   /* OUT: Ending offset of token */
134081  int *piPosition                     /* OUT: Position integer of token */
134082){
134083  IcuCursor *pCsr = (IcuCursor *)pCursor;
134084
134085  int iStart = 0;
134086  int iEnd = 0;
134087  int nByte = 0;
134088
134089  while( iStart==iEnd ){
134090    UChar32 c;
134091
134092    iStart = ubrk_current(pCsr->pIter);
134093    iEnd = ubrk_next(pCsr->pIter);
134094    if( iEnd==UBRK_DONE ){
134095      return SQLITE_DONE;
134096    }
134097
134098    while( iStart<iEnd ){
134099      int iWhite = iStart;
134100      U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
134101      if( u_isspace(c) ){
134102        iStart = iWhite;
134103      }else{
134104        break;
134105      }
134106    }
134107    assert(iStart<=iEnd);
134108  }
134109
134110  do {
134111    UErrorCode status = U_ZERO_ERROR;
134112    if( nByte ){
134113      char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
134114      if( !zNew ){
134115        return SQLITE_NOMEM;
134116      }
134117      pCsr->zBuffer = zNew;
134118      pCsr->nBuffer = nByte;
134119    }
134120
134121    u_strToUTF8(
134122        pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
134123        &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
134124        &status                                  /* Output success/failure */
134125    );
134126  } while( nByte>pCsr->nBuffer );
134127
134128  *ppToken = pCsr->zBuffer;
134129  *pnBytes = nByte;
134130  *piStartOffset = pCsr->aOffset[iStart];
134131  *piEndOffset = pCsr->aOffset[iEnd];
134132  *piPosition = pCsr->iToken++;
134133
134134  return SQLITE_OK;
134135}
134136
134137/*
134138** The set of routines that implement the simple tokenizer
134139*/
134140static const sqlite3_tokenizer_module icuTokenizerModule = {
134141  0,                           /* iVersion */
134142  icuCreate,                   /* xCreate  */
134143  icuDestroy,                  /* xCreate  */
134144  icuOpen,                     /* xOpen    */
134145  icuClose,                    /* xClose   */
134146  icuNext,                     /* xNext    */
134147};
134148
134149/*
134150** Set *ppModule to point at the implementation of the ICU tokenizer.
134151*/
134152SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
134153  sqlite3_tokenizer_module const**ppModule
134154){
134155  *ppModule = &icuTokenizerModule;
134156}
134157
134158#endif /* defined(SQLITE_ENABLE_ICU) */
134159#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
134160
134161/************** End of fts3_icu.c ********************************************/
134162